Friday, February 15, 2008

Find if network is available and connected using C#

There are different ways to find out manually that whether we're connecte to some network or not. But how we do this via programming - especially in .Net? In this post I'll give you the idea to find out that if we're connected to the network or not. This code snippet can also give us the number of the networks available to our machine.

In order to find out connected networks in Microsoft.Net using either C# or Visual Basic.Net we can use System.Management namespace. There are two classes available in this namespace that can help us achieve this goal. These two calsses are ObjectQuery and ManagementObjectSearcher. The following code snippet first creates a query object that will be used to get all the networks available to our machine and then the ManagementObjectSearcher class' object will execute this query to return the results.

ObjectQuery objQuery = new ObjectQuery("select * from Win32_NetworkAdapter Where NetConnectionStatus=2");

Here NetConnectionStatus=2 means the network connections that are connected right now. Normally, these are the connections which are connected to the internet i.e. Cable, Wireless internet connection etc.

ManagementObjectSearcher searcher = new ManagementObjectSearcher(objQuery);

int connectednetworks = searcher.Get().Count;

if (connectednetworks <= 0)
return false;

Wednesday, February 13, 2008

How to ping a server programatically in .net using C#

Normally, in Windows operating system we can ping a machine using Ping command in the command window. What we need to do is just provide the IP of the target machine we want to ping. Ping command returns the response which tells us that the other machine is active on the network and available. This same kind of functionality need to be achieved via programming. In this article I'll show you the code snippet which can help you ping a system in C# or Visual Basic.Net.

Microsoft.Net framework 2.0 provides Ping class under System.Net.NetworkInformation namespace which can be used to ping an IP. Following is the snippet which let you do this:

Ping objPing = new Ping();
PingReply objPingReply = objPing.Send("IP of the Machine");

if (objPingReply.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}

Tuesday, February 12, 2008

Register a COM DLL from .Net application using C#

The problem with the COM components i.e. DLL is that they need to be registered in the windows to put them to work. Registry Server can be used to register those DLLs. While doing this task manually one need to use command window to register the DLL file using Registry Server executable. Whoever, sometimes we also need to register some DLL from our application code using either C# or Visual Basic.Net. In this post I'll show you the code to register a COM DLL using C# code. This procedure can also be used with Visual Basic.Net as well with a slight modifications in syntax.

Following code snippet uses Process class of System.Diagnostics namespace. Just create an object of process class and pass few arguments to get the DLL registered in windows.

System.Diagnostics.Process Proc = new System.Diagnostics.Process(); Proc.StartInfo.FileName = "regsvr32.exe";
Proc.StartInfo.Arguments = "filename.dll /s";
Proc.StartInfo.CreateNoWindow = true;
Proc.Start();
Proc.WaitForExit();

Monday, February 11, 2008

Open a webpage on button click in asp.net using C#

Sometimes we need to open a web page using a button click event. This post contains a sample code that can be used in a button click event to show a page using Javascript Window.open method. This code snippet is just a small piece just to give you an idea for the startup stuff. I hope you can improve, and modify it according to your need to achieve your required goal.

Here is the sample code. You can put this code in the click event of a button etc.


string strpage = "Url of the page to be opened";
string url = "";
this.RegisterStartupScript("", url);

Friday, February 08, 2008

Get date and time parts in SQL Server 2005 using Transact SQL

Datetime data type in SQL Server 2000 or SQL Server 2005 provides a way to store data in date and time format. This type of variable or field contains both date and time togather, but sometimes we need either date or time portion only separately. For that purpose we can use Transact SQL. In this article I'll explain the way we can process datetime type data and get date and time parts as string.

We'll use some variations of Convert function to get both date and time. Let say we have an AddressBook table in our database which contains an UpdateDateTime field.

First of all we'll get only the time part of this datetime field:

SELECT CONVERT(CHAR(8),UpdateDateTime,8) FROM AddressBook

Above statement will give you the time part in string or text format like 15:13:03, Sowe can use it accordingly.

Following four Transact SQL statements return date part in different formats using Convert funciton:


--Date Part 10-26-2007
SELECT CONVERT(CHAR(10),UpdateDateTime,110) FROM AddressBook
--Date Part 2007/10/26
SELECT CONVERT(CHAR(10),UpdateDateTime,111) FROM AddressBook
--Date Part 20071026
SELECT CONVERT(CHAR(10),UpdateDateTime,112) FROM AddressBook
--Date Part 26 Oct 2007
SELECT CONVERT(CHAR(11),UpdateDateTime,113) FROM AddressBook

The date format returned is given as comments above the statements.

Thursday, February 07, 2008

Release memory in Windows Form application using C#

Windows Form applications (Microsoft.Net Desktop applications) sometimes start consuming a lot of memory, which has different drawbacks, but I'll not get into the details of them here. What we'll look into is how to avoid the excess use of the memory resource in a windows application in C#.

In fact, you need to flush memory to release all the unused memory to make more space available for your current and other applications. First of all include following two namespaces:

using Microsoft.Win32;
using System.Runtime.InteropServices;

and then use the following code snippet to flush excesssive use of memory. You can view the currently consumed memory by viewing the application process name in the currently running processes list. For that purpose just go to the Task Manager, and then go to Processes tab and find out your application's process.

Following code imports a win32 dll and flushes the memory. But, before that it also uses Microsoft.Net's garbage collector to force an immidiate garbage collection:

public class MemoryManagement
{
[DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet =
CharSet.Ansi, SetLastError = true)]

private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int
maximumWorkingSetSize);

public static void FlushMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}

copy and use this class in your code and have fun reducing the memory size!

Wednesday, February 06, 2008

Read data from XML File using DataTable in C#

Reading data from an xml file with the help of DataTable in C# is very easy. You just need to use one method of DataTable called ReadXML. Here is this article I'll show you how to complete this task of reading xml data into a DataTable.

Before reading xml data into a DataTable you need to make sure that the table structure is consistent with the structure of the xml. The good idea would be to first write the xml file using this same table structure in this DataTable. You can write xml using DataTable and the detail is given in the follwing post:

Write XML file using DataTable in C#

Import follwing namespace:
using System.Data;

We need a DataTable object:

DataTable dt;

This DataTable requires a structure compatible with the xml file structure. We can make sure this compatibility with the help of xml schema as well, but in this article I'll not explain how can we use xml schema to make sure that the structure is same. However, in some next post I'll definitly explain that as well.

Here is the table structure:

dt = new DataTable("MyTempTable");
dt.Columns.Add("FirstName", System.Type.GetType("System.String"));
dt.Columns.Add("LastName", Type.GetType("System.String"));
dt.Columns.Add("Address", Type.GetType("System.String"));

Now, read the xml file into this data table.

dt.ReadXml("filename");

Now, you can process data in the dt as a normal DataTable.