What is LINQ?
■ 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.
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.
Remove special characters from string ?
public override string ToString()
{
string specialCharacters = "~!@#$%^&*<()+=`',.?>/\\\"";
string[] stringAfterRemovingSpecialCharacters= displayText.Split(specialCharacters .ToCharArray());
return string.Concat(stringAfterRemovingSpecialCharacters);
}
{
string specialCharacters = "~!@#$%^&*<()+=`',.?>/\\\"";
string[] stringAfterRemovingSpecialCharacters= displayText.Split(specialCharacters .ToCharArray());
return string.Concat(stringAfterRemovingSpecialCharacters);
}
File/Folder is being used by another process Error?
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 :-
node is treeNode of tree.
Shell32.FolderItem folderItem = (Shell32.FolderItem)node.Tag.FolderItem;
Shell32.Folder folder = (Shell32.Folder)folderItem.GetFolder;
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.
Happy to code.
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 :-
node is treeNode of tree.
Shell32.FolderItem folderItem = (Shell32.FolderItem)node.Tag.FolderItem;
Shell32.Folder folder = (Shell32.Folder)folderItem.GetFolder;
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.
Happy to code.
List with ForEach
List Names = new List();
Names.Add("Saurabh");
Names.Add("Somu");
Names.Add("Sandy");
//For every item in the list, say you want to append the last name "Somu" and print it
//WITHOUT ForEach()
foreach (string name in Names)
{
Console.WriteLine(name + " Somu");
}
//WITH ForEach
Names.ForEach(delegate(string name) { Console.WriteLine( name + " Somu" ); });
Names.Add("Saurabh");
Names.Add("Somu");
Names.Add("Sandy");
//For every item in the list, say you want to append the last name "Somu" and print it
//WITHOUT ForEach()
foreach (string name in Names)
{
Console.WriteLine(name + " Somu");
}
//WITH ForEach
Names.ForEach(delegate(string name) { Console.WriteLine( name + " Somu" ); });
Yield Keyword
class Program
{
static void Main(string[] args)
{
List Names = new List();
Names.Add("saurabh");
Names.Add("somu");
Names.Add("vivek");
foreach (string item in GetNames(Names))
{
Console.WriteLine(item);
}
}
public static IEnumerable GetNames(List Names)
{
for (int i = 0; i < Names.Count; i++)
{
yield return Names[i];
}
}
}
{
static void Main(string[] args)
{
List
Names.Add("saurabh");
Names.Add("somu");
Names.Add("vivek");
foreach (string item in GetNames(Names))
{
Console.WriteLine(item);
}
}
public static IEnumerable
{
for (int i = 0; i < Names.Count; i++)
{
yield return Names[i];
}
}
}
?? keyword
?? keyword is used to check null.
Example using if-else statement:-
if (tempString == null)
{
x = "Null string";
}
else
{
x = tempString ;
}
Console.WriteLine(x);
Example using ?? Keyword
string tempString = null;
string x = tempString ?? "Null string";
Console.WriteLine(x); //Prints "Null string"
Example using if-else statement:-
if (tempString == null)
{
x = "Null string";
}
else
{
x = tempString ;
}
Console.WriteLine(x);
Example using ?? Keyword
string tempString = null;
string x = tempString ?? "Null string";
Console.WriteLine(x); //Prints "Null string"
Problem about Instances...
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.
Enjoy the Code..
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.
Enjoy the Code..
How to Copy,Delete,Rename and Move files and create new directory using Shell32 in C#?
#region Enum
public enum FileOp
{
Move = 0x0001,
Copy = 0x0002,
Delete = 0x0003,
Rename = 0x0004
}
[Flags]
public enum FileOpFlags
{
MultiDestFiles = 0x0001,
ConfirmMouse = 0x0002,
Silent = 0x0004,
RenameCollision = 0x0008,
NoConfirmation = 0x0010,
WantMappingHandle = 0x0020,
AllowUndo = 0x0040,
FilesOnly = 0x0080,
SimpleProgress = 0x0100,
NoConfirmMkDir = 0x0200,
NoErrorUI = 0x0400,
NoCopySecurityAttributes = 0x0800,
NoRecursion = 0x1000,
NoConnectedElements = 0x2000,
WantNukeWarning = 0x4000,
NoRecursiveReparse = 0x8000
}
#endregion
#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);
if (result != 0)
{
success = false;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Application.ProductName, MessageBoxButtons.OK);
}
return success;
}
How to call this method :-
To Delete the file or folder.
FileOperation(newFolderPath, string.Empty, FileOp.Delete);
To Copy the File or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Move);
To Rename the file or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Rename);
public enum FileOp
{
Move = 0x0001,
Copy = 0x0002,
Delete = 0x0003,
Rename = 0x0004
}
[Flags]
public enum FileOpFlags
{
MultiDestFiles = 0x0001,
ConfirmMouse = 0x0002,
Silent = 0x0004,
RenameCollision = 0x0008,
NoConfirmation = 0x0010,
WantMappingHandle = 0x0020,
AllowUndo = 0x0040,
FilesOnly = 0x0080,
SimpleProgress = 0x0100,
NoConfirmMkDir = 0x0200,
NoErrorUI = 0x0400,
NoCopySecurityAttributes = 0x0800,
NoRecursion = 0x1000,
NoConnectedElements = 0x2000,
WantNukeWarning = 0x4000,
NoRecursiveReparse = 0x8000
}
#endregion
#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);
if (result != 0)
{
success = false;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Application.ProductName, MessageBoxButtons.OK);
}
return success;
}
How to call this method :-
To Delete the file or folder.
FileOperation(newFolderPath, string.Empty, FileOp.Delete);
To Copy the File or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Move);
To Rename the file or Folder.
FileOperation(sourcePath, destinationPath, FileOp.Rename);
How to create FilePropertyDialog like Windows in C#?
#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
private const int SW_SHOW = 5;
private const uint SEE_MASK_INVOKEIDLIST = 12;
[DllImport("shell32.dll")]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
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);
}
[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
private const int SW_SHOW = 5;
private const uint SEE_MASK_INVOKEIDLIST = 12;
[DllImport("shell32.dll")]
static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
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);
}
How many instances are running in my application using C# ?
#region Directives
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();
}
}
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();
}
}
How to Create a Zip file using C#
public bool CreateZip(string ZipFileName)
{
try
{
Create an empty zip file
byte[] ZipFolder = new byte[]{100,75,50,16,10,5,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(ZipFileName);
fs.Write(ZipFolder , 0, ZipFolder.Length);
fs.Flush();
fs.Close();
fs = null;
}
catch(Exception ignore)
{
}
return true;
}
{
try
{
Create an empty zip file
byte[] ZipFolder = new byte[]{100,75,50,16,10,5,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(ZipFileName);
fs.Write(ZipFolder , 0, ZipFolder.Length);
fs.Flush();
fs.Close();
fs = null;
}
catch(Exception ignore)
{
}
return true;
}
How to open a zip file using C# ?
#region Namespace
using Shell32;
#endregion
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);
}
}
}
}
Enjoy the code.
using Shell32;
#endregion
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);
}
}
}
}
Enjoy the code.
Differences between Connected and disconnected architecture ?
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.
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.
What do you meant by Containment in C#?
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).
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).
How to handle generic errors in WinApp using C# ?
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;
EventLog.WriteEntry(sourceName , msg, EventLogEntryType.Error, errorCode );
MessageBox.Show(msg, "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.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;
EventLog.WriteEntry(sourceName , msg, EventLogEntryType.Error, errorCode );
MessageBox.Show(msg, "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
What is interface and why we implement interfaces ?
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;
}
}
}
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;
}
}
}
How to combine two images into one image in C#?
using System.Drawing;
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;
}
}
return finalImage;
}
catch(Exception ex)
{
if (finalImage != null)
{
finalImage.Dispose();
}
throw ex;
}
finally
{
//clean up memory
foreach (Bitmap image in images)
{
image.Dispose();
}
}
}
public static System.Drawing.Bitmap Combine(string[] files)
{
Create a list for images and read images
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;
}
}
return finalImage;
}
catch(Exception ex)
{
if (finalImage != null)
{
finalImage.Dispose();
}
throw ex;
}
finally
{
//clean up memory
foreach (Bitmap image in images)
{
image.Dispose();
}
}
}
Location of opening of dialog boxes(window form) in C#
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);
About aboutInfo = new About();
aboutInfo .ShowDialog(this);
or,
aboutInfo .ShowDialog(this.toplevelcontrol);