All about DataGridView

6. November 2009 22:21

C# 

 No Rating

Microsoft WMI Code Creator

27. October 2009 01:15

.NET Framework C# Utils 

The WMI Code Creator tool generates code that uses WMI to obtain management information or perform management tasks. You can use the tool to learn how to manage computers using WMI scripting and WMI .NET. The tool generates code that runs on the local computer, a remote computer, or a group of remote computers based on your selection from the Target Computer menu on the tool. You can also execute the generated code directly from the tool.

The tool is meant to help IT Professionals quickly create management scripts and to help developers learn WMI scripting and WMI .NET. The tool helps take the complexity out of writing code that uses WMI and helps developers and IT Professionals understand how powerful and useful WMI can be for managing computers.

Using the tool, you can query for management information such as the name and version of an operating system, how much free disk space is on a hard drive, or the state of a service. You can also use the tool to execute a method from a WMI class to perform a management task. For example, you can create code that executes the Create method of the Win32_Process class to create a new process such as Notepad or another executable. The tool also allows you to generate code to receive event notifications using WMI. For example, you can select to receive an event every time a process is started or stopped, or when a computer shuts down.

The tool also allows you to browse through the available WMI namespaces and classes on the local computer to find their descriptions, properties, methods, and qualifiers.

The code that creates the tool is also included in the download. The tool was created using WMI .NET, and the code for the tool can help developers understand how WMI .NET is used to create applications and manage information. Be sure to read the end-user license agreement that is included in the download.

The above overview and other technical details about Microsoft WMI Code Creator can be found here at Microsoft download center.

Download: WMICodeCreator.zip (121.38 kb)

 No Rating

Read/Write settings to INI File using C#

21. October 2009 18:12

C# Code Snippets 

When we design application we always face problems to save settings for the application and to achieve that we use different options available to us. A very common method to use in accordance of complexity XML files, Registry, Application.config or other/normal files. Best option is to use application configuration file but it seems that most of the people are not fully aware with the usage of the application configuration file. I will discuss late on the application configuration file a.k.a. app.config, but here is the way to use the INI files to save application settings.
Here I am using a simple class which has two methods Write & Read methods which internally calls the functions inside the Kernel32.dll which are WritePrivateProfileString and ReadPrivateProfileString. Both methods take parameters and write it to the INI file. Here is the complete listing of the class which can be use to read and write settings to the INI file.
INI files have sections and keys from where the data can be read on the combination of the sections and keys. As there can be a common key in different sections of the INI file. A section is defined in [SECTION NAME] and then it have a Key and its KeyValue.

class INIFile
    {
        private string filePath;
        
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
        string key,
        string val,
        string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
        string key,
        string def,
        StringBuilder retVal,
        int size,
        string filePath);
       
        public INIFile(string filePath)
        {
            this.filePath = filePath;
        }

        public void Write(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value.ToLower(), this.filePath);
        }

        public string Read(string section, string key)
        {
            StringBuilder SB = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, "", SB, 255, this.filePath);
            return SB.ToString();
        }
        
        public string FilePath
        {
            get { return this.filePath; }
            set { this.filePath = value; }
        }
    }

Now when you have to perform the read and write operations to the INI file you have to just call the Write and Read method from the above class. Initialize the above class anywhere in your application and then call the below methods to work.

To write a new entry to an INI file use the write method. As you can see in the below method you need to first initialize a class which takes in the path of the INI fie. The write method takes 3 arguments which have Section, Key and KeyValue respectively. I have used a single section and a key to demonstrate the usage, but you can call the write method a number of time to write different settings value.

INIFile inif = new INIFile("D:\\config.ini");
inif.Write("Database", "Devs", "sa");

When the write is complete to the INI file, open the file to see the newly written values. Your file should look like the one below.


To read the particular value from the INI file use the read method. It takes in 2 arguments i.e. Section and Key respectively to read a KeyValue.

INIFile inif = new INIFile("D:\\config.ini");
Console.WriteLine("The Value is:" +inif.Read("Database", "Devs"));


I have just displayed the value after reading from the file after the write operation is completed. You can set a local variable to preserve the value and then take a required action.

 

Currently rated 4.8 by 13 people

Passing Parameters to Crystal Reports

20. October 2009 16:26

C# 

I found many tutorials on the internet that shows how to pass the parameters (Discreet Parameters) to crystal reports, I tried all of them, but unfortunately I didn't get anyone of it to work. Therefore I though to give a trial on my code and eventually I got it running. I assume that you have a report ready with a parameter.

Firstly to get it running we have to use the below namespaces:

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

After you added a namespace now we have to pass a value to the report parameter, Here is the code to do this: Step 1: Create a ReportDocument object and initialize it

ReportDocument crReportDocument = new ReportDocument();

Step 2: Use the Load method of the ReportDocument object to load the report in the memory and use it.

crReportDocument.Load("C:\\report.rpt");

Step 3: After loading the report in the ReportDocument object, we can now set the value to the report parameter using SetParameterValue method. This is an overloaded method which we can use according to the requirement. I have used the parameter name and parmeter value which are of string and object type respectively.

crReportDocument.SetParameterValue("id", 115);

Step 4: As the data in the report is being populated from the database according to the parameter provided in the previous step. So to populate the data from the database we also have to set the database credentials to log in to the database and populate the report data.

crReportDocument.SetDatabaseLogon("sa", "pass#word1", "MX", "AdventureWorks");

Step 5: After the credentials have been set up for he database, the last step is to set the ReportSource property of the Crystal Report Viewer.

crystalReportViewer1.ReportSource = crReportDocument;

Here is the complete code:

ReportDocument crReportDocument = new ReportDocument();
crReportDocument.Load("C:\\report.rpt");
crReportDocument.SetParameterValue("id", 115);
crReportDocument.SetDatabaseLogon("sa", "pass#word1", "MX", "AdventureWorks"); crystalReportViewer1.ReportSource = crReportDocument;
Currently rated 3.0 by 1 person

Requesting delivery/read receipt from C# using MailMessage class

16. October 2009 15:38

.NET Framework C# 

Sending e-mail through code is easy, but how do we get to know that an e-mail that we send is delivered and read by the intended recipient. When we send e-mail through code we can request a delivery notification and read receipt from the receiver, similar to the way we do in outlook. But the problem is not every mail server supports this kind of request from the code. We set a mail header while sending mail from code which is then processed by the mail server and the sender of the mail gets the intended response. I have test the below code with Microsoft Exchange Server and it works perfectly fine. So let’s see what the code has:

First we need the namespace to use MailMessage class.

using System.Net;
using System.Net.Mail;

Initialize MailMessage class and set To, From, Subject and Body parameters

//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("prashantmx@xyz.com"); mail.To.Add("ankur@abc.com"); //set the content mail.Subject = "This is an email"; mail.Body = "this is the body content of the email.";

Now we have to set the Header property of the mail message class to request read/delivery recipt. As usual I first want to get notified for the e-mail I have sent has been delivered or not and then I want to get notified when my e-mail has been read by the recipient. Here I have also commented the deprecated method which is used in the previous version of .NET framework.

//This method has been deprecated.
//mail.Headers.Add("Return-Receipt-To", "prashantmx@xyz.com");
//Use this if you need a delivery notification of an email. DeliveryNotificationOption is an //umeration and can be used to set the delivery notification on the following options:
//1. Delay
//2. Never
//3. None
//4. OnFailure
//5. OnSuccess
/You can use also use OnFailure enum with OnSuccess enum. If in case the e-mail fails to 
//delivered you'll get notification for both the cases
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
//Add "Disposition-Notification-To" for Read receipt
mail.Headers.Add("Disposition-Notification-To", "");

When you set the headers for requesting delivery and read receipt, set the mail server and login credentials for the domain or for the e-mail service you use and then in the end call the Send method to send the e-mail.

//Set the SMTP server. You can also set the hostname instead of IP Address
SmtpClient smtp = new SmtpClient("192.168.1.5"); 
//Set the user network/domain credentials
NetworkCredential netCredit = new NetworkCredential("prashant@xyz.com", "pass#word1", "DOMAIN_NAME");
//Get SMTP to authenticate the credentials
smtp.Credentials = netCredit;
//Send the e-mail
smtp.Send(mail);

As I mentioned earlier also I have tested the above code with Exchange server only and it works perfectly. Here is the complete listing of the code :

static void ReadReceipts()
{
 //create the mail message
 MailMessage mail = new MailMessage();
 //set the addresses
 mail.From = new MailAddress("prashantmx@xyz.com");
 mail.To.Add("ankur@abc.com");
 //set the content
 mail.Subject = "This is an email";
 mail.Body = "this is the body content of the email.";
 //This method has been deprecated.
 //mail.Headers.Add("Return-Receipt-To", "prashantmx@xyz.com"); 
 //Use this if you need an delivery notification of an email.             //DeliveryNotificationOption is an enumeration
 //and can be used to set the delivery notification on the following options:
 //1. Delay
 //2. Never
 //3. None
 //4. OnFailure
 //5. OnSuccess
 //You can use also use OnFailure enum with OnSuccess enum. If in case the e-mail
 //fails to delivered you'll get notification for both the cases
 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
 //Add "Disposition-Notification-To" for Read receipt
 mail.Headers.Add("Disposition-Notification-To", "");
 
 //Set the SMTP server. You can also set the hostname instead of IP Address
 SmtpClient smtp = new SmtpClient("192.168.1.5"); 
 //Set the user network/domain credentials
 NetworkCredential netCredit =             new NetworkCredential("prashant@xyz.com", "pass#word1", "DOMAIN_NAME");
         //Get SMTP to authenticate the credentials
 smtp.Credentials = netCredit;
 //Send the e-mail
 smtp.Send(mail);
}
Currently rated 4.2 by 11 people