Sunday, February 26, 2012

Hot to get list of all AppDomains inside current process?



In my earlier post, I have explained how to create AppDomain inside process and how we can share data between AppDomains. As per request from one of you, in this post I am going to explain how we can get list of all AppDomains inside process.

To enumerate all the AppDomains inside process we can use class called CorRuntimeHost. This class is available inside mscoree namespace and can be added externally from C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscoree.tlb location. This class provides EnumDomains method which is used to enumerate AppDomains inside process. The NextDomain method of this class is used to get next available AppDomain if no AppDomain found, sets domain to null. 

Let’s have a look on below code snippet.

AppDomain.CreateDomain("AppDomain 1");
AppDomain.CreateDomain("AppDomain 2");
AppDomain.CreateDomain("AppDomain 3");

List<AppDomain> appDomains = new List<AppDomain>();

IntPtr handle = IntPtr.Zero;
CorRuntimeHost host = new CorRuntimeHost();
try
{
    host.EnumDomains(out handle);
    while (true)
    {
        object domain;
        host.NextDomain(handle, out domain);
        if (domain == null)
            break;
        appDomains.Add((AppDomain)domain);
    }
}
finally
{
    host.CloseEnum(handle);
}

foreach (AppDomain appDom in appDomains)
{
    Console.WriteLine(appDom.FriendlyName);
}

Output –
AppDomain 1
AppDomain 2
AppDomain 3


How to get specific AppDomin from process?

We can get specific AppDomain using the same code but with little modification. Let’s have a look on below code.

public void GetAppDomain(string name)
{
    IntPtr handle = IntPtr.Zero;
    CorRuntimeHost host = new CorRuntimeHost();
    try
    {
        host.EnumDomains(out handle);
        while (true)
        {
            object domain;
            host.NextDomain(handle, out domain);
            AppDomain myAppDomain = domain as AppDomain;
            if (myAppDomain == null)
                break;
            if (myAppDomain.FriendlyName.Equals(name))
            {
            Console.WriteLine("AppDomain Name - {0}", myAppDomain.FriendlyName);
            }
        }
    }
    finally
    {
        host.CloseEnum(handle);
    }
}

See Also –

Sunday, February 19, 2012

Accessing Network Card Information using .Net (C#)?



In today’s computer, multiple Network card is installed on single machine. Sometimes we might need to get information like how many network cards are installed and details of each network card. Dotnet provides NetworkInterface class to get information about all network cards installed on machine. This class is available in System.Net.NetworkInformation namespace.

NetworkInterface class provides low level information about Network card installed on computer. NetworkInterface class is an abstract class and provides GetAllNetworkInterfaces method to retrieve all the Network cards installed on machine. This class gives us lots of fun things. Let’s have a look on below example.

//retrieves all network interface cards
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
if (netInterfaces.Length < 1 || netInterfaces == null)
{
    Console.WriteLine("No Network card installed on your machine...");
    return;
}
Console.WriteLine("Total Network card installed on your machine is: {0}", netInterfaces.Length);
//loop all the NICs
foreach (NetworkInterface nic in netInterfaces)
{
    Console.WriteLine("{0}", new String('-', 30));
    Console.WriteLine("NIC ID: {0}", nic.Id);
    Console.WriteLine("Name: {0}", nic.Name);
    Console.WriteLine("Description: {0}", nic.Description);
    Console.WriteLine("Physical Address: {0}", nic.GetPhysicalAddress().ToString());
    Console.WriteLine("Interface Type: {0}", nic.NetworkInterfaceType);
    Console.WriteLine("Operational Status: {0}", nic.OperationalStatus);
    Console.WriteLine("Supports Multicast: {0}", nic.SupportsMulticast);
    Console.WriteLine("IPv4: {0}", nic.Supports(NetworkInterfaceComponent.IPv4) ? "Yes" : "No");
    Console.WriteLine("IPv6: {0}", nic.Supports(NetworkInterfaceComponent.IPv6) ? "Yes" : "No");
   
    //retrieves ip related information from NIC
    IPInterfaceProperties ipProp = nic.GetIPProperties();

    Console.WriteLine("DNS Enabled: {0}", ipProp.IsDnsEnabled);
    Console.WriteLine("DNS Suffix: {0}", ipProp.DnsSuffix);
    Console.WriteLine("Dynamically enabled DNS: {0}", ipProp.IsDynamicDnsEnabled);
}

Output –

Total Network card installed on your machine is: 3
------------------------------
NIC ID: {137F90A1-8654-4F46-6523-072636A6E415}
Name: Wireless Network Connection
Description: Intel(R) WiFi Link 1000 BGN
Physical Address: 0026C7CB31FC
Interface Type: Wireless80211
Operational Status: Up
Supports Multicast: True
IPv4: Yes
IPv6: Yes
DNS Enabled: False
DNS Suffix: broadband.mtnl.com
Dynamically enabled DNS: True
------------------------------
NIC ID: {846EE342-8654-11DE-2451-806E6F6E6963}
Name: Loopback Pseudo-Interface 1
Description: Software Loopback Interface 1
Physical Address:
Interface Type: Loopback
Operational Status: Up
Supports Multicast: True
IPv4: Yes
IPv6: Yes
DNS Enabled: False
DNS Suffix:
Dynamically enabled DNS: True
------------------------------
NIC ID: {BE831E47-9874-4EF1-5412-C087C5FEED04}
Name: Local Area Connection* 17
Description: Teredo Tunneling Pseudo-Interface
Physical Address: 00000000000000E0
Interface Type: Tunnel
Operational Status: Up
Supports Multicast: False
IPv4: No
IPv6: Yes
DNS Enabled: False
DNS Suffix:
Dynamically enabled DNS: False


See Also –


Saturday, February 18, 2012

How to Ping Machine using C#?



Ping is used to check whether remote machine is reachable or not. We usually use ping.exe to ping machine using command prompt but what when we need to ping remote machine through code. Microsoft Dotnet provides Ping class to ping machine using code. Ping class is available in System.Net.NetworkInformation class. If you can successfully ping remote machine it means you can reach that machine through network.

Ping class provides Send method to request message to remote computer and waits for reply. Ping class also provides SendAsync method to ping remote machine asynchronously. Send method returns PingReply object and we can check status property of pingreply object whether machine reachable or not. Some networks are not allowing ping outside from their network in such case PingException throws.

Following code demonstrate how we can ping remote machine using Ping Class.

string hostname = "www.google.com";
int timeout = 100;
Ping ping = new Ping();
           
try
{
    PingReply reply = ping.Send(hostname, timeout);
    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine("Address: {0}" , reply.Address);
        Console.WriteLine("Round trip time: {0}", reply.RoundtripTime);
        Console.WriteLine("Status: {0}", reply.Status);
    }
}
catch (PingException ex)
{
    Console.WriteLine(ex);
}

Output –
Address: 74.125.236.82
Round trip time: 33
Status: Success


See Also –


How to get IP Address and host name of machine?



DNS (Domain Name Service) class provides some useful methods to retrieve local computer Host Name, IP Address and other useful information. DNS class is static class and contains static methods. DNS class is available in System.Net namespace.

Dns class provides GetHostName method which returns local machine’s host name. Another method named GetHostAddresses returns array of IPAddress which accepts hostname as an input. Let’s have a look on below example which displays host name and IP addresses of local machine.

//returns local host name
string localHostName = Dns.GetHostName();
Console.WriteLine("Host name is: {0} ", localHostName);

//returns an array of IPAddresses
IPAddress[] ipAddresses = Dns.GetHostAddresses(localHostName);

//Displays all addresses
Console.Write("All addresses");
foreach (IPAddress ipAddress in ipAddresses)
{
    Console.WriteLine(ipAddress.ToString());
}
           
//Displays only IPV4 address
Console.Write("Only IPV4 addresses");
foreach (IPAddress ipAddress in ipAddresses.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork))
{
    Console.WriteLine(ipAddress.ToString());
}

//Displays only IPV6 addresses
Console.Write("Only IPV6 addresses");
foreach (IPAddress ipAddress in ipAddresses.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6))
{
    Console.WriteLine(ipAddress.ToString());
}

Output –
Host name is: Mitesh_Laptop

All addresses
fe80::c597:8d4:1936:994%13
fe80::3cda:3d13:f58d:9689%29
18.118.106.118
2001:0:5ef5:79fd:3cda:3d13:f58d:9689

Only IPV4 addresses
18.118.106.118

Only IPV6 addresses
fe80::c597:8d4:1936:994%13
fe80::3cda:3d13:f58d:9689%29
2001:0:5ef5:79fd:3cda:3d13:f58d:9689

Get IP Addresses based on host name

We can also pass any domain name to GetHostAddresses method of DNS class and retrieve all the IP Addresses of that domain.  Let’s have a look on below code.

string hostName = "www.google.com";
foreach (IPAddress ipAddress in Dns.GetHostAddresses(hostName))
{
    Console.WriteLine(ipAddress.ToString());
}

Output –
74.125.236.82
74.125.236.81
74.125.236.83
74.125.236.84
74.125.236.80

Above code displays all the IP Addresses of www.google.com domain. Similarly we can get IP addresses of different domain like www.microsoft.com , www.amazon.com etc.

Get host name based on IP Address

Based on IP address we can retrieve domain name using GetHostEntry method of DNS class. It requires IP address as an input of valid domain. Let’s see how it works.

string IPAddrs = "209.85.175.191";
IPHostEntry hostEntry = Dns.GetHostEntry(IPAddrs);
Console.WriteLine(hostEntry.HostName);

Ouput –
nx-in-f191.1e100.net


See Also –


Sunday, February 12, 2012

Working with Path Class in .Net (C#)


Path class is static class and has collection of static methods and fields. Path class is available in System.IO namespace. Path provides the location of file or folder located on disk. Path class used to perform operations like getting file name and extension part of the URL, combining two strings into single path, getting temp directory path etc. Let's have a look on major operations using Path.

string path = @"d:\temp\test.txt";

Console.WriteLine("File Name: {0}",Path.GetFileName(path));
Console.WriteLine("Full Path: {0}",Path.GetFullPath(path));
Console.WriteLine("Extension: {0}",Path.GetExtension(path));
Console.WriteLine("Directory Name: {0}",Path.GetDirectoryName(path));
Console.WriteLine("Path Root: {0}",Path.GetPathRoot(path));
Console.WriteLine("File Name w/o extn: {0}",Path.GetFileNameWithoutExtension(path));
Console.WriteLine("Has Extn: {0}",Path.HasExtension(path));
Console.WriteLine("Temp Path: {0}", Path.GetTempPath());
Console.WriteLine("Directory Seperator: {0}", Path.AltDirectorySeparatorChar);
Console.WriteLine("Volume Seperator: {0}", Path.VolumeSeparatorChar);
Console.WriteLine("Combine : {0}", Path.Combine("Dir1","File1.txt"));


Output –
File Name: test.txt
Full Path: d:\temp\test.txt
Extension: .txt
Directory Name: d:\temp
Path Root: d:\
File Name w/o extn: test
Has Extn: True
Temp Path: C:\Users\msureja\AppData\Local\Temp\
Directory Seperator: /
Volume Seperator: :
Combine : Dir1\File1.txt

See Also - 


Saturday, February 11, 2012

Working with Directory Class in .Net (C#)



Directory class is static class provides static methods to do normal directory related operations such as Copy, Paste, Move, Rename, Delete etcIt is available in System.IO namespace.  Below code demonstrates some basic majorly used methods of directory class.


//Creates temp directory if not exist
if (!Directory.Exists(@"d:\temp"))
    Directory.CreateDirectory(@"d:\temp");

//set/get current directory
Directory.SetCurrentDirectory(@"d:\temp");
Console.WriteLine(Directory.GetCurrentDirectory());

//gets root of directory
Console.WriteLine(Directory.GetDirectoryRoot(@"d:\temp"));

//gets creation and last modified time of directory
Console.WriteLine(Directory.GetCreationTime(@"d:\temp"));
Console.WriteLine(Directory.GetLastWriteTime(@"d:\temp"));
           
//enumerates all files available in temp directory          
foreach (string file in Directory.EnumerateFiles(@"d:\temp"))
    Console.WriteLine(file);

//enumerates all directories available in temp directory
foreach (string directory in Directory.EnumerateDirectories(@"d:\temp"))
    Console.WriteLine(directory);

//enumerates all logical drives
foreach (string drive in Directory.GetLogicalDrives())
    Console.WriteLine(drive);

//deletes an empty directory. if not empty throws an exception
Directory.Delete(@"d:\temp");


Enumerate files and folders using DirectoryInfo
DirectoryInfo class provides some basic features to create, copy, move, rename and delete operations. It also provides some basic information like directory name, full path, attribute, root name etc. Let’s have a look on below code which loop through all the files and directories in specific directory.


DirectoryInfo di = new DirectoryInfo(@"d:\temp");
Console.WriteLine(di.FullName);

//gets all files in temp directory
foreach (FileInfo file in di.GetFiles())
    Console.WriteLine(file.Name);
//gets all directories in temp directory
foreach (DirectoryInfo dir in di.GetDirectories())
    Console.WriteLine(dir.Name);


How to get Special Folders?
Special folders are defined under Environment.SpecialFolder enum. This enum is available in System.Environment class. Let’s see how to get path for special folders like MyDocuments, MyPictures, Desktop, ProgramFiles, System, Windows etc.

Console.WriteLine("My Documents - {0}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
Console.WriteLine("My Videos - {0}", Environment.GetFolderPath(Environment.SpecialFolder.MyVideos));
Console.WriteLine("Windows - {0}", Environment.GetFolderPath(Environment.SpecialFolder.Windows));
Console.WriteLine("ProgramFiles - {0}", Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
Console.WriteLine("System - {0}", Environment.GetFolderPath(Environment.SpecialFolder.System));

Output –
My Documents - D:\Users\mitesh\Documents
My Videos - D:\Users\mitesh\Videos
Windows - C:\WINDOWS
ProgramFiles - C:\Program Files
System - C:\WINDOWS\system32

//Enumerates all SpecialFolders available in Enviroment.SpecialFolder enum
foreach (var specialFolder in Enum.GetValues(typeof(Environment.SpecialFolder)))
    Console.WriteLine(specialFolder);

Output –
Desktop
Programs
MyDocuments
Favorites
Startup
Recent
SendTo
StartMenu

Working with File Class in .Net (C#)


File class is static class provides static methods to do normal file related operationsIt is available in System.IO namespaceFile class used to do some file related operations like Copy, Paste, Move, Replace, Delete etc. Let’s have a look on below code.

string filePath = @"D:\Temp\Test.txt";
//Checkes whether Test.txt file is exists or not
if (File.Exists(filePath))
{
    //Copies Test.txt file to TestCopy.txt.
    File.Copy(filePath, @"D:\Temp\TestCopy.txt", true);
    //Moves Test.txt file to TestMove.txt.
    //Throws an exception if file already exists.
    File.Move(filePath, @"D:\Temp\TestMove.txt");
    //Replace TextMove.txt file with TextCopy.txt file with
    //provisional backup file TestBKP.txt.
    File.Replace(@"D:\Temp\TestMove.txt", @"D:\Temp\TestCopy.txt", @"D:\Temp\TestBKP.txt");      

    //Deletes TextBKP.txt file.
    //Throws an exception if file is readonly.
    File.Delete(@"D:\Temp\TestBKP.txt");
}
else
{
    //Creates new file named Test.txt
    File.Create(filePath);
}

Getting File Attributes

File class provides SetAttributes and GetAttributes methods to set attributes to file. The file attributes enum contains value like Archieve, Normal, Hidden, ReadOnly etc. We can change file attributes using Get/Set attributes method of File Class. Let’s have a look on below code.

//sets hidden attribute to Text.txt file.
File.SetAttributes(@"d:\temp\Test.txt", FileAttributes.Hidden);

//returns attributes of Test.txt
FileAttributes fileAttribute = File.GetAttributes(@"d:\temp\Test.txt");

if ((fileAttribute & FileAttributes.Hidden) == FileAttributes.Hidden)
    Console.WriteLine("This file is hidden");
else
    Console.WriteLine("this file is not hidden");


Getting Creation/Modification Times

File class provides methods to get creation time and modified time of file.

Method Name
Description
GetCreationTime
Gets creation time of specified file.
GetLastWriteTime
Gets last modified date time of specified file
GetLastAccessTime
Gets last accessed date time of specified file.
SetCreationTime
Sets creation date and time to file.
SetLastWriteTime
Sets last write date and time to file.
SetLastAccessTime
Sets last accessed date and time to file.

Let’s have a look on below code.

//Gets creation time of specified file.
DateTime createdTime = File.GetCreationTime(@"d:\temp\Test.txt");
Console.WriteLine(createdTime.ToString());

//Gets last modified date time of specified file.
DateTime modifiedTime = File.GetLastWriteTime(@"d:\temp\Test.txt");
Console.WriteLine(modifiedTime.ToString());

//Gets last accessed date time of specified file.
DateTime lastAccessTime = File.GetAccessTime(@"d:\temp\Test.txt");
Console.WriteLine(lastAccessTime.ToString());

//Sets creation date and time to file.
File.SetCreationTime(@"d:\temp\Test.txt", DateTime.Now);

//Sets last accessed date and time to file.
File.SetLastAccessTime(@"d:\temp\Test.txt", DateTime.Now.AddMinutes(5));

//Sets last write date and time to file.
File.SetLastWriteTime(@"d:\temp\Test.txt", DateTime.Now.AddMinutes(10));

Output –
20-01-2012 08:09:37 PM
20-01-2012 08:19:37 PM
20-01-2012 08:14:37 PM

Encrypt / Decrypt file

Encrypt method of file class can encrypt file or directory while Decrypt method of file class can decrypt file. Using Encrypt and Decrypt we can protect file or folder from unwanted access.

File.Encrypt(@"d:\temp\test.txt");
File.Decrypt(@"d:\temp\test.txt");



When file encrypted the file name appears as green color in window 7. When file decrypted it will be appear as normal.

FileInfo Class

FileInfo class provides method to get file related information such as length, name, directory name, extension etc. Let’s have a look on below code.

FileInfo fileInfo = new FileInfo(@"d:\temp\test.txt");
Console.WriteLine("Name - {0}", fileInfo.Name);
Console.WriteLine("Full Name - {0}", fileInfo.FullName);
Console.WriteLine("Directory Name - {0}", fileInfo.DirectoryName);
Console.WriteLine("File Length - {0}", fileInfo.Length);
Console.WriteLine("File Extension - {0}", fileInfo.Extension);
Console.WriteLine("File Attributes - {0}", fileInfo.Attributes);
Console.WriteLine("Created On - {0}", fileInfo.CreationTime);
Console.WriteLine("Modified On - {0}", fileInfo.LastWriteTime);

Output -
Name - test.txt
Full Name - d:\temp\test.txt
Directory Name - d:\temp
File Length - 9
File Extension - .txt
File Attributes - Archive
Created On - 20-01-2012 08:14:48 PM
Modified On - 20-01-2012 08:18:04 PM