■ LINQ is a uniform programming model for any kind of data. LINQ enables you to query and manipulate data with a consistent model that is independent from data sources. ■ LINQ is just another tool for embedding SQL queries into code. ■ LINQ is yet another data abstraction layer.
Hi Friends.. Resolved Error - File/Folder is being used by another process
As i discussed in my current project i made a self explorer.exe so i accessed all the folders,files .i am doing same behaviour as lioke window explorer.exe. But I was facing a error This file/folder is being used by another process and all that and i face all these errors when i rename,delete,move,copy,drag-drop.
Solution :- I add folders runtime and updation is all as real time.so I used shell com object and make tree using shell namespace like :-
then iterate thorugh foreach and used break statement because i add a dummynode in each node who have folders and when i expand that node then delete the dummynode and create the nodes for that treenode beacuase of efficiency.So on creating dummyNode i used foreach statement like :-
bool hasFolders = false; foreach (Shell32.FolderItem item in folder.Items()) { if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable) { hasFolders = true; break; } } if (hasFolders) { TreeNode newTreeNode = new TreeNode(); newTreeNode.Tag = STRING_DUMMY_TREENODE; treeNode.Nodes.Add(newTreeNode); } so this foreach actually its an iterator so when i use break statement so tis break from the loop but still it holds the object and shell thinks its used by some other program and all so dont use foreach if you using break statement like this :-
Shell32.FolderItems items = folder.Items(); for (int itemIndex = 0; itemIndex < items.Count; itemIndex++) { Shell32.FolderItem item = items.Item(itemIndex); if (item.IsFileSystem && item.IsFolder && !item.IsBrowsable) { hasFolders = true; break; } } and now as above you will never face the error like file/folder is being used by another process so in your application if you are facing then firstly check it out and make sure you are not using any iterator.
Hii..Frends this is very genuine problem. Functionality :-When i was developing Window Explorer control for my application then i just stuck in a problem I had three instances of window - explorer.. One is as similar as Window file explorer by which you can drag drop files and that will open in any editor.(We had given additional functionality like to show INF,INI,BAK and ORG files) and other two are as same as Window File - Folder Explorer like in left hand side Folder Explorer(TreeView) and Right hand side ListView which shows all the files with size,Modified date and type of file.and you can sort using coloumn click.(Like Window File detail view in windows) and the third one which is just below of this one has same feature but the root node of this tree will be a path where ever we want to show we said this is destination view and above one is source view .You can drag files from Source listView to Destination TreeView and ListView both and that will copy the whole directory at that path physically and You can add folder from source treeview to destination treeView and we can move folder and files from destination listView to destination treeview.We given the special functionality like we can add new folder,delete the folder and rename the folder.That all the features we have given in all the controls. Problem:-I have only one control with three instances if i m doing some changes from application and rename and bla bla..n all the tree view has opened a same path then i want to make all the controls as real time like if we add a folder of some path then in all the controls will be the same...So i need some notification then i know the methods about shell if we add , delete and rename from shell then shell will send a notification to application and then WndProc method will send the notification to all the instances and to invoke shell methods i have already make a post related to How to Copy,Delete,Rename from Shell.
If you add delete , add folder,media and other devices and rename and all other changes then how system invokes the message and will reflect real time.
#region Structure [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)] public struct SHFILEOPSTRUCT { public IntPtr hwnd; [MarshalAs(UnmanagedType.U4)] public int wFunc; public string pFrom; public string pTo; public short fFlags; [MarshalAs(UnmanagedType.Bool)] public bool fAnyOperationsAborted; public IntPtr hNameMappings; public string lpszProgressTitle; } #endregion
Import a shell method to copy file from one location to another,delete file,copy file and rename files and folders. [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
Import a shell method to create a new directory. [DllImport("shell32.dll")] public static extern int SHCreateDirectoryEx(IntPtr hwnd, string pszPath, IntPtr psa);
To create a new folder : private const string NULL_STRING = "\0"; newFolderPath is the path where you want to create your directory. SHCreateDirectoryEx(this.Handle, newFolderPath + NULL_STRING, IntPtr.Zero);
To do all the file operation like move , copy ,delete and rename :- public bool FileOperation(string sourceFileName, string destinationFileName, FileOp fileOp) { bool success = true; try { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = (int)fileOp; shf.fFlags = (short)FileOpFlags.AllowUndo | (short)FileOpFlags.NoConfirmation; if(!string.IsNullOrEmpty(sourceFileName)) { shf.pFrom = sourceFileName + NULL_STRING; } if(!string.IsNullOrEmpty(destinationFileName)) { shf.pTo = destinationFileName + NULL_STRING; } int result = SHFileOperation(ref shf);
#region Enum [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct SHELLEXECUTEINFO { public int cbSize; public uint fMask; public IntPtr hwnd; [MarshalAs(UnmanagedType.LPTStr)] public string lpVerb; [MarshalAs(UnmanagedType.LPTStr)] public string lpFile; [MarshalAs(UnmanagedType.LPTStr)] public string lpParameters; [MarshalAs(UnmanagedType.LPTStr)] public string lpDirectory; public int nShow; public IntPtr hInstApp; public IntPtr lpIDList; [MarshalAs(UnmanagedType.LPTStr)] public string lpClass; public IntPtr hkeyClass; public uint dwHotKey; public IntPtr hIcon; public IntPtr hProcess; } #endregion
Pass the file name for which you want to see the file property dialog. public static void ShowFileProperties(string Filename) { SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO(); shellInfo .cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info); shellInfo .lpVerb = "properties"; shellInfo .lpFile = Filename; shellInfo .nShow = SW_SHOW; shellInfo .fMask = SEE_MASK_INVOKEIDLIST; ShellExecuteEx(ref info); }
using System.text; using System.Threading; using System.Reflection;
#endregion
public class TestApplication { #region Private Fields
The default instance private static TestApplication DefValue = new TestApplication (); The system-wide semaphore private Semaphore semaphore; Initial count for the semaphore(Randonm you can choose any big count) private const int MAXCOUNT = 10000; private static bool _pvInstance ;
#endregion
#region Properties
The PrevInstance property returns True if there was a previous instance running when the default instance was created public static bool PrevInstance { get { return _pvInstance ; } }
Return the total number of instances of the same application that are currently running public static int InstanceCount { get { // release the semaphore and grab the previous count int prevCount = DefValue.semaphore.Release(); // acquire the semaphore again DefValue.semaphore.WaitOne(); // evaluate number of other instances that are currently running. return MAXCOUNT - prevCount; } }
#endregion
Constructor. private TestApplication () { // create a named (system-wide semaphore) bool ownership = false; // create the semaphore or get a reference to an existing semaphore
string appName = "TestApplication _" + Assembly.GetExecutingAssembly().Location.Replace(":", string.Empty).Replace("\\", string.Empty); semaphore = new Semaphore( MAXCOUNT, MAXCOUNT, appName , out ownership); // decrement its value semaphore.WaitOne(); // if we got ownership, this app has no previous instances _prevInstance = !ownership; } Destructor to destroy. ~TestApplication () { // increment the semaphore when the application terminates semaphore.Release(); } }
namespace TestApplicationToZip { class ZipApplication { public static void Main(string[] args) { Create the object of shell. Shell sh = new Shell(); Create a namespace and folderItem for the existing folder path. Folder ShellFolder = sh.NameSpace("D:\\saurabh.zip"); Folder DirectoryFolder = sh.NameSpace("D:\\Unzipped Files"); Traverse each file. foreach (FolderItem folderItem in ShellFolder .Items()) { DirectoryFolder .CopyHere(folderItem ,o); } } } }
Hii friends,Today one of my frend ask about what approach is better connected or disconnected architecture ..So let me explain more about this problem :-
As the nature of HTTP protocol,.Net web applications are always disconnected so your problem is about connected or disconnected data models.
"connected" data is always faster as compare to "disconnected" because of the internal optimizations provided by the data provider,data adopters and others like data tables but always remeber that fetch out the data when you need so disconnected data model is good.
Connected :- **User can get the data from database in connection state using data reader,adaptor,data table.1 :- Using this communication will possible in between the front end & backend (UI and database). 2 :- This command object have some parameters and have some methods to execute stored procedure ExecuteNonQuery(),ExecuteReader(),ExecuteScalar(), ExecuteXMLReader() ExecuteNonQuery :- For executing DML statements. ExecuteReader :- This method returns DataReader. ExecuteScalar :- This method is used for executing those SQL statements which generates single value. ExecuteXMLReader :- This method is mainly used for reading an XML file content.
Disconnected :- ** User can get the data from database in connectionless state using data set.
Containment is the replacement of inheritence,no no if inheritance isn’t the right choice,then the answer is containment, also known as aggregation. Rather than saying that an object is an example of another object, an instance of that other object will be contained inside the object. So,instead of having a class look like a string, the class will contain a string (or array, or hash table). The default design choice should be containment, and you should switch to inheritance only if needed(i.e., if there really is an “is-a” relationship).
Pass your exception or error through catch block to this method this will catch your error and show the messagebox regarding that error.
Method which take error exception as a parameter and handle that error. public static void LogError(Exception ex) { string sourceName = "Application Name"; int errorCode = "99"; string message = "The application encountered an unknown error:"; msg += "\r\nExecuting Method: " + new System.Diagnostics.StackFrame(1, false).GetMethod().Name; message += "\r\nError Message: " + ex.Message;
Interface defined by using interface keyword .In visualstudio you can directly add class as a interface its not a class it behaves as a template of the class. Interfaces describe a group of related functionalities that can belong to any class or struct.Interfaces are provided in C# as a replacement of multiple inheritance because C# does not support multiple inheritance and it's very necessary to inherit the behaviour of one or more classes.classes can only implement the methods defined in the interface because in C#, an interface is a built-in keyword that declares a reference type that includes method declarations. if a base class implements an interface, the derived class inherits that implementation.
I am giving an example to better understand :- Interface which contains profile name strings public interface IProfile { string FirstName {get;} string LastName {get;} } Implements IloggedUser interface. public interface ILoggedUser { IProfile Profile { get; set; } } Class LoggedUser which implements ILoggedUser interface. public class LoggedUser : ILoggedUser { protected IProfile _profile = null; Constructor public LoggedUser(IProfile Profile) { _profile=Profile; }
public static LoggedUser Create(IProfile Profile) { LoggedUser User = new LoggedUser(Profile); return User; } public IProfile Profile { get { if (_profile== null) { return _profile; } } set { _profile=value; } } } Class profile which implements IProfile interface. public class Profile : IProfile { string _firstName = string.Empty; string _lastName = string.Empty; public string FirstName { get { return _firstName; } } public string LastName { get { return _lastName; } } }
public static System.Drawing.Bitmap Combine(string[] files) { Create a list for images and read images List images = new List(); Bitmap finalImage = null;
try { int width = 0; int height = 0;
foreach (string image in files) { create a Bitmap from the file and add it to the list. Bitmap bitmap = new Bitmap(image);
Update the size of the final bitmap. width += bitmap.Width; if(bitmap.Height > height ) { height = bitmap.Height ; } else { height = height ; } images.Add(bitmap); }
create a bitmap to hold the combined image. finalImage = new Bitmap(width, height);
Get a graphics object from the image so we can draw on it. using (Graphics g = Graphics.FromImage(finalImage)) { set background color. g.Clear(Color.Black);
Go through each image and draw it on the final image. int offset = 0; foreach (Bitmap image in images) { g.DrawImage(image, new System.Drawing.Rectangle(offset, 0, image.Width, image.Height)); offset += image.Width; } }
In my application i used some dialog boxes like about of company some customize message boxes and all that in some dialog boxes I used start position as Center parent but i forget to pass the IWin32Window Owner in show dialog as a parameter regarding that when focus is lost from my application then dialog took desktop as a parent and opens in different locations so always pass window owner as a parameter.
About aboutInfo = new About(); aboutInfo .ShowDialog(this); or, aboutInfo .ShowDialog(this.toplevelcontrol);
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Drawing.Imaging;
public class Form1 : System.Windows.Forms.Form { Constructor. public Form1() { InitializeComponent(); } Initialize all the controls. private void InitializeComponent() { this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); this.Text = ""; this.Resize += new System.EventHandler(this.Form1_Resize); this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
} Main method(Entry point). public static void Main() { Application.Run(new Form1()); } Handles the paint event.Create the grapics for the image,then set the resolution and then draw the image. private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; Bitmap bmp = new Bitmap("winter.jpg");
This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.