There is a bug or some called microsoft functionality in the microsoft flowlayout panel .I have used flowlayout panel in my current project in that panel i have add controls like : Checklistbox control,radiolistbox,regitry flags and many more they all had labels in their top with some fixed size but when i added in the panel then they all are docked in the panel (Top) property but size of the labels was remain same.then i come to know it's a bug then i used panel instead of flowlayout panel.
Algorithms in C# (Anagram Method)
Input :-
1:- cba
2:- dsef
3:- sandy
Output :-
1:- abc
2:- defs
3:- adnsy
This is called alphabetized sorting using Anagram method.
To Use Anagram Method :-
Dictionary : 4556 ms
If we use generic list in dictionary then it will take longer time to compute
Dictionary : 5647 ms
Namespace :-
using System;
using System.Collections.Generic;
using System.IO;
Public class Anagrams
{
public static void Main()
{
Read and sort dictionary
var data = ReadText();
Read in user input and show anagrams
string lineToRead;
while ((lineToRead = Console.ReadLine()) != null)
{
ShowOutput(data, lineToRead);
}
}
Public Dictionary ReadText()
{
var data = new Dictionary();
Read each line
using (StreamReader readWholeText = new StreamReader("Some File .Text"))
{
string line;
while ((line = readWholeText.ReadLine()) != null)
{
Alphabetize the line for the key,Then add to the string
string alphabetize = Alphabetize(line);
string tempString = string.Empty;
if (data.TryGetValue(alphabetize, out tempString))
{
data[alphabetize] = tempString + "," + line;
}
else
{
data.Add(alphabetize, line);
}
}
}
return data;
}
Convert the text and sort it according to alphabet.
Public string Alphabetize(string text)
{
// Convert to char array, then sort and return
char[] arrayOfLine = text.ToCharArray();
Array.Sort(arrayOfLine);
return new string(arrayOfLine);
}
This method will show the output.
Public void ShowOutput(Dictionary objDictionary, string temp)
{
// Write value for alphabetized word
string tempText;
if (objDictionary.TryGetValue(Alphabetize(temp), out tempText))
{
Console.WriteLine(tempText);
}
else
{
Console.WriteLine("-");
}
}
}
1:- cba
2:- dsef
3:- sandy
Output :-
1:- abc
2:- defs
3:- adnsy
This is called alphabetized sorting using Anagram method.
To Use Anagram Method :-
Dictionary
If we use generic list in dictionary then it will take longer time to compute
Dictionary
Namespace :-
using System;
using System.Collections.Generic;
using System.IO;
Public class Anagrams
{
public static void Main()
{
Read and sort dictionary
var data = ReadText();
Read in user input and show anagrams
string lineToRead;
while ((lineToRead = Console.ReadLine()) != null)
{
ShowOutput(data, lineToRead);
}
}
Public Dictionary
{
var data = new Dictionary
Read each line
using (StreamReader readWholeText = new StreamReader("Some File .Text"))
{
string line;
while ((line = readWholeText.ReadLine()) != null)
{
Alphabetize the line for the key,Then add to the string
string alphabetize = Alphabetize(line);
string tempString = string.Empty;
if (data.TryGetValue(alphabetize, out tempString))
{
data[alphabetize] = tempString + "," + line;
}
else
{
data.Add(alphabetize, line);
}
}
}
return data;
}
Convert the text and sort it according to alphabet.
Public string Alphabetize(string text)
{
// Convert to char array, then sort and return
char[] arrayOfLine = text.ToCharArray();
Array.Sort(arrayOfLine);
return new string(arrayOfLine);
}
This method will show the output.
Public void ShowOutput(Dictionary
{
// Write value for alphabetized word
string tempText;
if (objDictionary.TryGetValue(Alphabetize(temp), out tempText))
{
Console.WriteLine(tempText);
}
else
{
Console.WriteLine("-");
}
}
}
MSIL code for Singleton and Static class
MSIL code for singleton
L_0000: ldsfld class Perls.Metadata Perls.Metadata::Instance
L_0005: ldarg.0
L_0006: ldloca.s data
L_0008: callvirt instance bool Perls.Metadata::TryGetFile(string, class Perls.FileData&)
MSIL code for static class
L_0000: ldarg.0
L_0001: ldloca.s data
L_0003: call bool Perls.Metadata::TryGetFile(string, class Perls.FileData&)
L_0000: ldsfld class Perls.Metadata Perls.Metadata::Instance
L_0005: ldarg.0
L_0006: ldloca.s data
L_0008: callvirt instance bool Perls.Metadata::TryGetFile(string, class Perls.FileData&)
MSIL code for static class
L_0000: ldarg.0
L_0001: ldloca.s data
L_0003: call bool Perls.Metadata::TryGetFile(string, class Perls.FileData&)
Comparison between NullCheckSingleton and OptimizedSingleton in C#
NullCheckSingleton
public sealed class SampleProgram
{
static readonly SampleProgram _instance;
public static readonly SampleProgram Instance
{
if (_instance == null)
{
_instance = new SampleProgram();
}
return _instance;
}
SampleProgram()
{
}
}
Optimized singleton
public sealed class SampleProgram
{
static readonly SampleProgram _instance = new SampleProgram();
public static readonly SampleProgram Instance
{
get
{
return _instance;
}
}
SampleProgram()
{
}
}
Optimized singleton is much faster than NullcheckSingleton Have a look on the above example and as i am discussed in my previous thread about the time comparison in both singleton pattern.
[Reference Jon Skeet's thorough singleton page.]
public sealed class SampleProgram
{
static readonly SampleProgram _instance;
public static readonly SampleProgram Instance
{
if (_instance == null)
{
_instance = new SampleProgram();
}
return _instance;
}
SampleProgram()
{
}
}
Optimized singleton
public sealed class SampleProgram
{
static readonly SampleProgram _instance = new SampleProgram();
public static readonly SampleProgram Instance
{
get
{
return _instance;
}
}
SampleProgram()
{
}
}
Optimized singleton is much faster than NullcheckSingleton Have a look on the above example and as i am discussed in my previous thread about the time comparison in both singleton pattern.
[Reference Jon Skeet's thorough singleton page.]
Singleton Class Uses and Drawbacks
Singleton :-
Singleton is controversial design pattern of OOPS. It allows you to restrict the number of instances of an object.It's an interface that allows a class to enforce that it is only allocated once.
Sample Code :-
Namespace :-
using system.text;
using System.collections;
class SampleProgram
{
public static void Main()
{
SingletonStructure singleton = SingletonStructure.Instance;
}
}
public sealed class SingletonStructure
{
static readonly SingletonStructure _instance = new SingletonStructure();
public static SingletonStructure Instance
{
get
{
return _instance;
}
}
Constructor which will be initialize and create the instance
SingletonStructure()
{
// Initialize.
}
}
Null check singleton: 435 ms
Optimized singleton : 42 ms (As Above)
This method is fast beacause instance member is created directly in its declaration
Singleton is controversial design pattern of OOPS. It allows you to restrict the number of instances of an object.It's an interface that allows a class to enforce that it is only allocated once.
Sample Code :-
Namespace :-
using system.text;
using System.collections;
class SampleProgram
{
public static void Main()
{
SingletonStructure singleton = SingletonStructure.Instance;
}
}
public sealed class SingletonStructure
{
static readonly SingletonStructure _instance = new SingletonStructure();
public static SingletonStructure Instance
{
get
{
return _instance;
}
}
Constructor which will be initialize and create the instance
SingletonStructure()
{
// Initialize.
}
}
Null check singleton: 435 ms
Optimized singleton : 42 ms (As Above)
This method is fast beacause instance member is created directly in its declaration
How to read XML Node using C#
Load an XML File
XmlDocument xdXml = new XmlDocument();
xdXml.Load("Index.xml");
Make a nodelist
XmlNodeList xnNodes = xdXml.SelectNodes("/Tools/Download");
Walk through the list
foreach (XmlNode node in xnNodes)
{
if (node.FirstChild.InnerText == ddlTools.Text)
{
//Get all the child nodes
XmlNodeList childNodes = node.ChildNodes;
//And walk through them
foreach (XmlNode child in childNodes)
{
//Check which node we have now
switch (child.Name)
{
case "Name":
txtName.Text = child.InnerText;
break;
case "Version":
txtVersion.Text = child.InnerText;
break;
case "Category":
txtCategory.Text = child.InnerText;
break;
case "Description":
txtDescription.Text = child.InnerText;
break;
}
}
childNodes = null;
break;
}
}
Clean up
xdXml = null;
xnNodes = null;
XmlDocument xdXml = new XmlDocument();
xdXml.Load("Index.xml");
Make a nodelist
XmlNodeList xnNodes = xdXml.SelectNodes("/Tools/Download");
Walk through the list
foreach (XmlNode node in xnNodes)
{
if (node.FirstChild.InnerText == ddlTools.Text)
{
//Get all the child nodes
XmlNodeList childNodes = node.ChildNodes;
//And walk through them
foreach (XmlNode child in childNodes)
{
//Check which node we have now
switch (child.Name)
{
case "Name":
txtName.Text = child.InnerText;
break;
case "Version":
txtVersion.Text = child.InnerText;
break;
case "Category":
txtCategory.Text = child.InnerText;
break;
case "Description":
txtDescription.Text = child.InnerText;
break;
}
}
childNodes = null;
break;
}
}
Clean up
xdXml = null;
xnNodes = null;
Transparent images not displaying correctly
If images are not displaying correctly or showing a black spot at the back side of the image then play with the color depth property of imagelist or picture box.
Example :-
ImageList imageList = new ImageList();
imagelist.colorDepth = colorDepth.32Bit;
Example :-
ImageList imageList = new ImageList();
imagelist.colorDepth = colorDepth.32Bit;
Collection of Regular Expressions
Regular expression to match email address
1 :- [\w-]+@([\w-]+\.)+[\w-]+
2 :- (?(?![ ])(\w|[.])*@(\w|[.])*)
3 :- ^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$
4 :- /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@
([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
Regular Expression to validate US-Phone number.
Example :- (999) 999-9999 or (999)123-7869
1 :- /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/
Regular Expression which validate string which contains only valid numbers.
1 :- /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/
Regular Expression which validate string which contains only valid integer numbers.
1 :- /(^-?\d\d*$)/
Regular Expression to validate US-Zip Code
1:- /(^\d{5}$)|(^\d{5}-\d{4}$)/;
Regular Expression to check any social number :-
Replace 9 by any valid nuber you want to check
1 :-/^\d{9}$/
Expression to check amount example :- 100,100.00,$100,$100.00
1 :- /^((\$\d*)|(\$\d*\.\d{2})|(\d*)|(\d*\.\d{2}))$/
Regular Expression to check IP Address (0-255):-
/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
Regular Expression to check Time :-
/^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/
Like :- HH:MM:SS, HH:MM, HH:MM:SS.mmm
1 :- [\w-]+@([\w-]+\.)+[\w-]+
2 :- (?
3 :- ^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$
4 :- /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@
([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
Regular Expression to validate US-Phone number.
Example :- (999) 999-9999 or (999)123-7869
1 :- /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/
Regular Expression which validate string which contains only valid numbers.
1 :- /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/
Regular Expression which validate string which contains only valid integer numbers.
1 :- /(^-?\d\d*$)/
Regular Expression to validate US-Zip Code
1:- /(^\d{5}$)|(^\d{5}-\d{4}$)/;
Regular Expression to check any social number :-
Replace 9 by any valid nuber you want to check
1 :-/^\d{9}$/
Expression to check amount example :- 100,100.00,$100,$100.00
1 :- /^((\$\d*)|(\$\d*\.\d{2})|(\d*)|(\d*\.\d{2}))$/
Regular Expression to check IP Address (0-255):-
/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
Regular Expression to check Time :-
/^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/
Like :- HH:MM:SS, HH:MM, HH:MM:SS.mmm
Detect the Encoding Type of given file
Encoding type : To add new Encoding we have to add new member in here,with the CodePage value as an value of the new encoding and have to modify FileHandler.DetectEncoding function.
public enum EncodingType
{
WindowsANSI = 1252,
Unicode = 1200,
UnixANSI = 28591
}
You can pass the path of the file and this method returns the encoding format
of type which has been defined in enum EncodingType.You just modify the enum with your encoding and code page value and get the encoding format of any file.
private Encoding DetectEncoding(string fileName)
{
byte[] data = new byte[4];
Encoding encoding = null;
StreamReader streamReader = new StreamReader(fileName);
streamReader.BaseStream.Read(data, 0, data.Length);
ApplicationNativeMethods.IsTextUnicodeFlags isTextUnicodeFlags = ApplicationNativeMethods.IsTextUnicodeFlags.UnicodeMask;
bool isTextUnicode = ApplicationNativeMethods.IsTextUnicode(data, 4, ref isTextUnicodeFlags);
if ((data[0] == 0xFF && data[1] == 0xFE) || (isTextUnicode == true))
{
encoding = Encoding.GetEncoding((int)EncodingType.Unicode);
}
else
{
streamReader.BaseStream.Position = 0;
char cr = char.MinValue;
char lf = char.MinValue;
char peekLf = char.MinValue;
while ((streamReader.EndOfStream != true))
{
peekLf = (char)streamReader.Peek();
if (peekLf == Constants.SYMBOL_LINEFEED)
{
cr = lf;
lf = (char)streamReader.Read();
break;
}
lf = (char)streamReader.Read();
}
if (cr != Constants.SYMBOL_CARRIAGERETURN)
{
encoding = Encoding.GetEncoding((int)EncodingType.UnixANSI);
}
else
{
encoding = Encoding.GetEncoding((int)EncodingType.WindowsANSI);
}
}
streamReader.Close();
return encoding;
}
public enum EncodingType
{
WindowsANSI = 1252,
Unicode = 1200,
UnixANSI = 28591
}
You can pass the path of the file and this method returns the encoding format
of type which has been defined in enum EncodingType.You just modify the enum with your encoding and code page value and get the encoding format of any file.
private Encoding DetectEncoding(string fileName)
{
byte[] data = new byte[4];
Encoding encoding = null;
StreamReader streamReader = new StreamReader(fileName);
streamReader.BaseStream.Read(data, 0, data.Length);
ApplicationNativeMethods.IsTextUnicodeFlags isTextUnicodeFlags = ApplicationNativeMethods.IsTextUnicodeFlags.UnicodeMask;
bool isTextUnicode = ApplicationNativeMethods.IsTextUnicode(data, 4, ref isTextUnicodeFlags);
if ((data[0] == 0xFF && data[1] == 0xFE) || (isTextUnicode == true))
{
encoding = Encoding.GetEncoding((int)EncodingType.Unicode);
}
else
{
streamReader.BaseStream.Position = 0;
char cr = char.MinValue;
char lf = char.MinValue;
char peekLf = char.MinValue;
while ((streamReader.EndOfStream != true))
{
peekLf = (char)streamReader.Peek();
if (peekLf == Constants.SYMBOL_LINEFEED)
{
cr = lf;
lf = (char)streamReader.Read();
break;
}
lf = (char)streamReader.Read();
}
if (cr != Constants.SYMBOL_CARRIAGERETURN)
{
encoding = Encoding.GetEncoding((int)EncodingType.UnixANSI);
}
else
{
encoding = Encoding.GetEncoding((int)EncodingType.WindowsANSI);
}
}
streamReader.Close();
return encoding;
}
Sorted List Implementation
In C# You can implement Sortedlist and sort the values according to the key.
using System;
using System.Collections;
Code:
static void Main(string[] args)
{
values in sorted list are sorted according to key
SortedList myList = new SortedList();
myList.Add(12, "December");
myList.Add(9, "September");
myList.Add(10, "October");
myList.Add(4, "April");
myList.Add(5, "May");
myList.Add(6, "June");
myList.Add(2, "February");
myList.Add(8, "August");
myList.Add(7, "July");
myList.Add(3, "March");
myList.Add(11, "November");
myList.Add(1, "January");
output values that are sorted according to key
foreach (DictionaryEntry item in myList)
{
Console.WriteLine(item.Value);
}
}
using System;
using System.Collections;
Code:
static void Main(string[] args)
{
values in sorted list are sorted according to key
SortedList myList = new SortedList();
myList.Add(12, "December");
myList.Add(9, "September");
myList.Add(10, "October");
myList.Add(4, "April");
myList.Add(5, "May");
myList.Add(6, "June");
myList.Add(2, "February");
myList.Add(8, "August");
myList.Add(7, "July");
myList.Add(3, "March");
myList.Add(11, "November");
myList.Add(1, "January");
output values that are sorted according to key
foreach (DictionaryEntry item in myList)
{
Console.WriteLine(item.Value);
}
}
Hash Table Implementation
using System;
using System.Collections;
Code:
static void Main(string[] args)
{
Create an object of hash table
Hashtable myHash = new Hashtable();
Add key-pair values
myHash.Add("Saurabh", 1);
myHash.Add("Sandy", 2);
myHash.Add("Vivek", 3);
Move through hashtable data in cycle
foreach (DictionaryEntry item in myHash)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
Get first item
Console.WriteLine("Get first item: " + myHash["Saurabh"]);
This will not work, name of item is not identical
Console.WriteLine("Get second item: " + myHash["Sandy"]);
}
using System.Collections;
Code:
static void Main(string[] args)
{
Create an object of hash table
Hashtable myHash = new Hashtable();
Add key-pair values
myHash.Add("Saurabh", 1);
myHash.Add("Sandy", 2);
myHash.Add("Vivek", 3);
Move through hashtable data in cycle
foreach (DictionaryEntry item in myHash)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
Get first item
Console.WriteLine("Get first item: " + myHash["Saurabh"]);
This will not work, name of item is not identical
Console.WriteLine("Get second item: " + myHash["Sandy"]);
}
Get System Boot Configuration using C#
using System;
using System.Management;
Code:
static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_BootConfiguration");
ManagementObjectSearcher find = new ManagementObjectSearcher(query);
foreach (ManagementObject mo in find.Get())
{
Console.WriteLine("Boot directory with files required for booting.." + mo["BootDirectory"]);
Console.WriteLine("Description.." + mo["Description"]);
Console.WriteLine("Directory with temporary files for booting.." + mo["ScratchDirectory"]);
Console.WriteLine("Directory with temporary files.." + mo["TempDirectory"]);
}
}
using System.Management;
Code:
static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_BootConfiguration");
ManagementObjectSearcher find = new ManagementObjectSearcher(query);
foreach (ManagementObject mo in find.Get())
{
Console.WriteLine("Boot directory with files required for booting.." + mo["BootDirectory"]);
Console.WriteLine("Description.." + mo["Description"]);
Console.WriteLine("Directory with temporary files for booting.." + mo["ScratchDirectory"]);
Console.WriteLine("Directory with temporary files.." + mo["TempDirectory"]);
}
}
Get Environment variables..
Namespaces:
using System;
using System.Management;
Code:
static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("Select * from Win32_Environment");
ManagementObjectSearcher find = new ManagementObjectSearcher(query);
Console.WriteLine("Description - Name - User Name - Value");
foreach (ManagementObject mo in find.Get())
{
Console.WriteLine(mo["Description"] + " - " + mo["Name"] + " - " + mo["UserName"] + " - " + mo["VariableValue"]);
}
}
using System;
using System.Management;
Code:
static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("Select * from Win32_Environment");
ManagementObjectSearcher find = new ManagementObjectSearcher(query);
Console.WriteLine("Description - Name - User Name - Value");
foreach (ManagementObject mo in find.Get())
{
Console.WriteLine(mo["Description"] + " - " + mo["Name"] + " - " + mo["UserName"] + " - " + mo["VariableValue"]);
}
}
Obtain IP address and host
Namespaces:
using System;
using System.Net;
Code:
static void Main(string[] args)
{
Get Host Name
string host = Dns.GetHostName();
Console.WriteLine("Hostname is: {0}", host);
GetIP Entry
IPHostEntry entry = Dns.GetHostByName(host);
foreach (IPAddress ip in entry.AddressList)
{
Console.WriteLine("IP address: " + ip.ToString());
}
}
using System;
using System.Net;
Code:
static void Main(string[] args)
{
Get Host Name
string host = Dns.GetHostName();
Console.WriteLine("Hostname is: {0}", host);
GetIP Entry
IPHostEntry entry = Dns.GetHostByName(host);
foreach (IPAddress ip in entry.AddressList)
{
Console.WriteLine("IP address: " + ip.ToString());
}
}
Send mail message to .net Environment (Enjoy Mail System)
Namespaces:
using System;
using System.Web.Mail;
Code:
static void Main(string[] args)
{
MailMessage mailMsg = new MailMessage();
mailMsg.From = "saurabhsingh_jnu06@yahoo.co.in";
mailMsg.To = "saurabhjnumca@gmail.com";
mailMsg.Cc = string.Empty;
mailMsg.Bcc = string.Empty;
mailMsg.Subject = "Here goes a subject";
mailMsg.Body = "Here goes email body";
mailMsg.Priority = (MailPriority)1;
mailMsg.Attachments.Add(new MailAttachment("d:\\myText.txt"));
SmtpMail.SmtpServer = "smarthost";
SmtpMail.Send(mailMsg);
}
using System;
using System.Web.Mail;
Code:
static void Main(string[] args)
{
MailMessage mailMsg = new MailMessage();
mailMsg.From = "saurabhsingh_jnu06@yahoo.co.in";
mailMsg.To = "saurabhjnumca@gmail.com";
mailMsg.Cc = string.Empty;
mailMsg.Bcc = string.Empty;
mailMsg.Subject = "Here goes a subject";
mailMsg.Body = "Here goes email body";
mailMsg.Priority = (MailPriority)1;
mailMsg.Attachments.Add(new MailAttachment("d:\\myText.txt"));
SmtpMail.SmtpServer = "smarthost";
SmtpMail.Send(mailMsg);
}
Network Operations in C# (Play with system)
Retrieve DNS computer name
public static void Main(string[] args)
{
Console.WriteLine(“DNS: {0}”, System.Net.Dns.GetHostByName“LocalHost”).HostName);
}
Retrieve NetBIOS computer name
public static void Main(string[] args)
{
Console.WriteLine(“NetBIOS: {0}”, System.Environment.MachineName);}
public static void Main(string[] args)
{
Console.WriteLine(“DNS: {0}”, System.Net.Dns.GetHostByName“LocalHost”).HostName);
}
Retrieve NetBIOS computer name
public static void Main(string[] args)
{
Console.WriteLine(“NetBIOS: {0}”, System.Environment.MachineName);}
To get the system Icons(handle of system imagelist)
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags); }
//the handle to the system image list
IntPtr hImgSmall;
//the handle to the system image list
//IntPtr hImgLarge;
//Create an object of
SHFILEINFO shinfo = new SHFILEINFO();
try
{
//Use this to get the small Icon
hImgSmall = Win32.SHGetFileInfo( Path of file, 0, ref shinfo,
(uint)Marshal.SizeOf(shinfo),
Win32.SHGFI_ICON |
Win32.SHGFI_SMALLICON
);
Icon myIcon =Icon.FromHandle(shinfo.hIcon);
//This return the index on=f system image list
int iconIndex = shinfo.iIcon;
//Add the icon to imagelist or where ever you want to use you can
imageList.Images.Add(myIcon);
}
catch (Exception)
{
}
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath,
uint dwFileAttributes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags); }
//the handle to the system image list
IntPtr hImgSmall;
//the handle to the system image list
//IntPtr hImgLarge;
//Create an object of
SHFILEINFO shinfo = new SHFILEINFO();
try
{
//Use this to get the small Icon
hImgSmall = Win32.SHGetFileInfo( Path of file, 0, ref shinfo,
(uint)Marshal.SizeOf(shinfo),
Win32.SHGFI_ICON |
Win32.SHGFI_SMALLICON
);
Icon myIcon =Icon.FromHandle(shinfo.hIcon);
//This return the index on=f system image list
int iconIndex = shinfo.iIcon;
//Add the icon to imagelist or where ever you want to use you can
imageList.Images.Add(myIcon);
}
catch (Exception)
{
}
To close the application from task manager.
If you have closed your appplication but still it runs in task manager then you can use this method to kill the thread.It happens only when some thread of your application is not closed.
Code:-
public const int SC_CLOSE = 0xF060;
public const int WM_SYSCOMMAND = 0x0112;
//Override method when You will close the window
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
//close the application
MyClose();
// your method that cleans everything up and then runs
// System.Environment.Exit(0) which WILL close the threads forcefully if needed
base.WndProc(ref m);
}
Code:-
public const int SC_CLOSE = 0xF060;
public const int WM_SYSCOMMAND = 0x0112;
//Override method when You will close the window
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
//close the application
MyClose();
// your method that cleans everything up and then runs
// System.Environment.Exit(0) which WILL close the threads forcefully if needed
base.WndProc(ref m);
}
Play with Date-Time-Formats in C#
Code:
public static void Main(string[] args)
{
//Get the cureent date time
DateTime datetTime= DateTime.Now;
Formatting DateTime to full pattern (dddd, MMMM dd, yyyy hh:mm:ss)
Console.WriteLine(dt.ToString("F"));
Formatting DateTime to short date- time pattern (dddd, MMMM dd, yyyy, hh:mm)
Console.WriteLine(dt.ToString("f"));
Formatting DateTime to short date numerical pattern (M/d/yyyy)
Console.WriteLine(dt.ToString("d"));
Formatting DateTime to full date numeric pattern (dddd, MMMM dd, yyyy)
Console.WriteLine(dt.ToString("D"));
To the short date&time numerical pattern (M/d/yyyy hh:mm)
Console.WriteLine(dt.ToString("g"));
To the full date&time numerical pattern (M/d/yyyy hh:mm:ss)
Console.WriteLine(dt.ToString("G"));
DateTime to the month name pattern (MMMM dd)
Console.WriteLine(dt.ToString("m"));
DateTime to the short date pattern (MMMM, yyyy)
Console.WriteLine(dt.ToString("y"));
DateTime to the long time pattern (hh:mm:ss)
Console.WriteLine(dt.ToString("T"));
DateTime to the short time pattern (hh:mm)
Console.WriteLine(dt.ToString("t"));
DateTime to the RFC1123 pattern (ddd, dd MMM yyyy HH':'mm':'ss 'GMT')
Console.WriteLine(dt.ToString("r"));
DateTime to sortable pattern This format is based on ISO 8601 and uses local time.
Console.WriteLine(dt.ToString("s"));
DateTime to full date&time using universal time
Console.WriteLine(dt.ToString("U"));
DateTime to universal sortable pattern (yyyy'-'MM'-'dd HH':'mm':'ss'Z')
Console.WriteLine(dt.ToString("u"));
}
public static void Main(string[] args)
{
//Get the cureent date time
DateTime datetTime= DateTime.Now;
Formatting DateTime to full pattern (dddd, MMMM dd, yyyy hh:mm:ss)
Console.WriteLine(dt.ToString("F"));
Formatting DateTime to short date- time pattern (dddd, MMMM dd, yyyy, hh:mm)
Console.WriteLine(dt.ToString("f"));
Formatting DateTime to short date numerical pattern (M/d/yyyy)
Console.WriteLine(dt.ToString("d"));
Formatting DateTime to full date numeric pattern (dddd, MMMM dd, yyyy)
Console.WriteLine(dt.ToString("D"));
To the short date&time numerical pattern (M/d/yyyy hh:mm)
Console.WriteLine(dt.ToString("g"));
To the full date&time numerical pattern (M/d/yyyy hh:mm:ss)
Console.WriteLine(dt.ToString("G"));
DateTime to the month name pattern (MMMM dd)
Console.WriteLine(dt.ToString("m"));
DateTime to the short date pattern (MMMM, yyyy)
Console.WriteLine(dt.ToString("y"));
DateTime to the long time pattern (hh:mm:ss)
Console.WriteLine(dt.ToString("T"));
DateTime to the short time pattern (hh:mm)
Console.WriteLine(dt.ToString("t"));
DateTime to the RFC1123 pattern (ddd, dd MMM yyyy HH':'mm':'ss 'GMT')
Console.WriteLine(dt.ToString("r"));
DateTime to sortable pattern This format is based on ISO 8601 and uses local time.
Console.WriteLine(dt.ToString("s"));
DateTime to full date&time using universal time
Console.WriteLine(dt.ToString("U"));
DateTime to universal sortable pattern (yyyy'-'MM'-'dd HH':'mm':'ss'Z')
Console.WriteLine(dt.ToString("u"));
}
How to get Memory Info
Namespaces:
using System;
using System.Management;
Code:
static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
ManagementObjectSearcher find = new ManagementObjectSearcher(query);
//Traverse each management object.
foreach (ManagementObject mo in find.Get())
{
Console.WriteLine("Available bytes: " + mo["AvailableBytes"]);
Console.WriteLine("Available KBs: " + mo["AvailableKBytes"]);
Console.WriteLine("Available MBs: " + mo["AvailableMBytes"]);
Console.WriteLine("Cache bytes: " + mo["CacheBytes"]);
Console.WriteLine("Cache bytes peak: " + mo["CacheBytesPeak"]);
Console.WriteLine("Cache bytes: " + mo["CacheBytes"]);
Console.WriteLine("Commit limit: " + mo["CommitLimit"]);
Console.WriteLine("Committed bytes: " + mo["CommittedBytes"]);
Console.WriteLine("Free system page table entries: " + mo["FreeSystemPageTableEntries"]);
Console.WriteLine("Pool paged bytes: " + mo["PoolPagedBytes"]);
Console.WriteLine("System code total bytes: " + mo["SystemCodeTotalBytes"]);
Console.WriteLine("System driver total bytes: " + mo["SystemDriverTotalBytes"]);
}
}
using System;
using System.Management;
Code:
static void Main(string[] args)
{
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
ManagementObjectSearcher find = new ManagementObjectSearcher(query);
//Traverse each management object.
foreach (ManagementObject mo in find.Get())
{
Console.WriteLine("Available bytes: " + mo["AvailableBytes"]);
Console.WriteLine("Available KBs: " + mo["AvailableKBytes"]);
Console.WriteLine("Available MBs: " + mo["AvailableMBytes"]);
Console.WriteLine("Cache bytes: " + mo["CacheBytes"]);
Console.WriteLine("Cache bytes peak: " + mo["CacheBytesPeak"]);
Console.WriteLine("Cache bytes: " + mo["CacheBytes"]);
Console.WriteLine("Commit limit: " + mo["CommitLimit"]);
Console.WriteLine("Committed bytes: " + mo["CommittedBytes"]);
Console.WriteLine("Free system page table entries: " + mo["FreeSystemPageTableEntries"]);
Console.WriteLine("Pool paged bytes: " + mo["PoolPagedBytes"]);
Console.WriteLine("System code total bytes: " + mo["SystemCodeTotalBytes"]);
Console.WriteLine("System driver total bytes: " + mo["SystemDriverTotalBytes"]);
}
}
Open Control Panel Items using Shell (COM)
Namespaces:
using System;
// this is COM component that can be found under the name "Microsoft Shell Controls And Automation"
// this must be added to project references
using Shell32;
Code:
static void Main()
{
//Creating an object of shell to access all the control panel items.
Shell shell = new Shell();
// accessibility options
shell.ControlPanelItem("access.cpl");
// add-remove programs
shell.ControlPanelItem("appwiz.cpl");
// bluetooth configuration
shell.ControlPanelItem("btcpl.cpl");
// desktop settings
shell.ControlPanelItem("desk.cpl");
// directX properties
shell.ControlPanelItem("directx.cpl");
// add hardware wizard
shell.ControlPanelItem("hdwwiz.cpl");
// internet properties
shell.ControlPanelItem("inetcpl.cpl");
// regional and language options
shell.ControlPanelItem("intl.cpl");
// Wireless link
shell.ControlPanelItem("irprops.cpl");
// Game controllers
shell.ControlPanelItem("joy.cpl");
// Mouse properties
shell.ControlPanelItem("main.cpl");
// Sounds and audio devices properties
shell.ControlPanelItem("mmsys.cpl");
// Network connections
shell.ControlPanelItem("ncpa.cpl");
// User accounts
shell.ControlPanelItem("nusrmgr.cpl");
// ODBC datasource administrator
shell.ControlPanelItem("odbccp32.cpl");
// Power options properties
shell.ControlPanelItem("powercfg.cpl");
// System properties
shell.ControlPanelItem("sysdm.cpl");
// Location information - telephone properties
shell.ControlPanelItem("telephon.cpl");
// Date and time properties
shell.ControlPanelItem("timedate.cpl");
// Automatic updates - WindowsUpdate settings
shell.ControlPanelItem("wuaucpl.cpl");
}
using System;
// this is COM component that can be found under the name "Microsoft Shell Controls And Automation"
// this must be added to project references
using Shell32;
Code:
static void Main()
{
//Creating an object of shell to access all the control panel items.
Shell shell = new Shell();
// accessibility options
shell.ControlPanelItem("access.cpl");
// add-remove programs
shell.ControlPanelItem("appwiz.cpl");
// bluetooth configuration
shell.ControlPanelItem("btcpl.cpl");
// desktop settings
shell.ControlPanelItem("desk.cpl");
// directX properties
shell.ControlPanelItem("directx.cpl");
// add hardware wizard
shell.ControlPanelItem("hdwwiz.cpl");
// internet properties
shell.ControlPanelItem("inetcpl.cpl");
// regional and language options
shell.ControlPanelItem("intl.cpl");
// Wireless link
shell.ControlPanelItem("irprops.cpl");
// Game controllers
shell.ControlPanelItem("joy.cpl");
// Mouse properties
shell.ControlPanelItem("main.cpl");
// Sounds and audio devices properties
shell.ControlPanelItem("mmsys.cpl");
// Network connections
shell.ControlPanelItem("ncpa.cpl");
// User accounts
shell.ControlPanelItem("nusrmgr.cpl");
// ODBC datasource administrator
shell.ControlPanelItem("odbccp32.cpl");
// Power options properties
shell.ControlPanelItem("powercfg.cpl");
// System properties
shell.ControlPanelItem("sysdm.cpl");
// Location information - telephone properties
shell.ControlPanelItem("telephon.cpl");
// Date and time properties
shell.ControlPanelItem("timedate.cpl");
// Automatic updates - WindowsUpdate settings
shell.ControlPanelItem("wuaucpl.cpl");
}
Get folder items using Windows folder dialog
Namespaces:
using System;
using Shell32;
Code:
static void Main()
{
Shell shell = new Shell();
// open dialog for desktop folder
// use appropriate constant for folder type ShellSpecialFolderConstants
Folder folder = shell.BrowseForFolder(0, "folderPath/FilePath",0 ,ShellSpecialFolderConstants.ssfDESKTOP); if (folder != null)
{
foreach (FolderItem fi in folder.Items())
{
Console.WriteLine(fi.Name);
}
}
}
using System;
using Shell32;
Code:
static void Main()
{
Shell shell = new Shell();
// open dialog for desktop folder
// use appropriate constant for folder type ShellSpecialFolderConstants
Folder folder = shell.BrowseForFolder(0, "folderPath/FilePath",0 ,ShellSpecialFolderConstants.ssfDESKTOP); if (folder != null)
{
foreach (FolderItem fi in folder.Items())
{
Console.WriteLine(fi.Name);
}
}
}