Archive for the ‘C#’ Category

How to Encrypt a Section in Web.Config?

January 20, 2009

It is often required to encrypt usernames, passwords or even connection string in the web.config file. The usual method to do is using any of the encryption algorithm and saving the encryption Key in the config file. .NET has provided with a classic feature of encrypting an entire section in the web.config file. Using this feature .NET saves the key in the Machine.key file. User ONLY needs to encrypt the section in the web.config file, the decryption of the section is taken care by the .NET framework. Here is a step by step procedure on encrypting a section:

Section in Web.config


<!-- User Credentials -->
<ImpersonateUser>
<add key ="domain" value ="domain_name"/>
<add key ="username" value ="user_name"/>
<add key ="password" value ="password"/>
</ImpersonateUser>

Step 1:
Open the Visual Studio Command Prompt in Administrative Mode
Go to Start –> Programs –> Visual Studio 2008 –> Visual Studio Tools –> Visual Studio Command Prompt right click and say “Run as Administrator

Step 2:
Type the following command:
aspnet_regiis -pef “ImpersonateUser” “D:\SourceCode\RootFolder” -prov “RsaProtectedConfigurationProvider
The web.config file should be present at the path “D:\SourceCode\RootFolder”. The actual command looks like:
aspnet_regiis -pef “SECTION_NAME” “PATH_TILL_WEB.CONFIG” -prov “ENCRYPTION_PROVIDER”

Step 3:
Run the above command.
The above command will encrypt the ImpersonateUser section in the web.config file and will save the web.config file at the given location. The encrypted section will look like:


<ImpersonateUser configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>nQGcFhli6gRmNXD1vjJG+fQw8nN80NwaXjKsVDsSbcoLqAmbKPDhZZvXw1E81uY6+3AhmUzp1SQSTavIVKjj8RvQI21LzaSSc8UUwo7Q7ZRHeBCpyQE+xRs9BlvsXjyn0oX/q5Ns4uoRU3OEkJlcYmFizrGG7YuHdvogh8+wFLE=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>YJODT4I4FKNuUqG3o3QEn8UGXS3jSeFjkVsE2r+jQuBy6fqh4Uc/psu49Rr0SgsDlx7RDm+yIzztRki7ETgNCaSwkkX0h3TXsnJv8jA+FuRmOqIXU8sfjF/5p1KNRkj8l1yzFueom2llRpjprclTvxlTVUQopOTXuodBV3dFnqnqTe/gu70GOqdNooNyWgn02hvG5GjL4mXdb8iMGDMJSrgin6E3nYMrkV71nMkPXi8+MeenWfRWQ1BH8BNblC9R</CipherValue>
</CipherData>
</EncryptedData>
</ImpersonateUser>

Most important thing is, while using the web.config key’s in the C# code we DO NOT have to decrypt the section. .NET automatically does it and provides us with the decrypted values.

Hope this helps. Your comments will help us improve 🙂

Advertisements

How to convert DataTable to XML in C#?

January 18, 2009

Following code illustrates about converting a DataTable to XML format. This is often required when passing a DataTable to a stored procedure. We can pass an XML directly to the procedure and process it.


/// <summary>
/// This method is used to convert the DataTable into string XML format.
/// </summary>
/// <param name="dtBuildSQL">DataTable to be converted.</param>
/// <returns>(string) XML form of the DataTable.</returns>
private static string ConvertDataTableToXML(DataTable dtBuildSQL)
{
DataSet dsBuildSQL = new DataSet();
StringBuilder sbSQL;
StringWriter swSQL;
string XMLformat;

sbSQL = new StringBuilder();
swSQL = new StringWriter(sbSQL);
dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
dsBuildSQL.Tables[0].TableName = "Table";
foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
{
col.ColumnMapping = MappingType.Attribute;
}
dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
XMLformat = sbSQL.ToString();
return XMLformat;
}

Your comments are welcome!

How to dynamically add Update Panel to asp.net page?

December 25, 2008

Here is a simple code to dynamically add update panel to asp.net page:


UpdatePanel upannel = new UpdatePanel();
upannel.ChildrenAsTriggers = true;
upannel.UpdateMode = UpdatePanelUpdateMode.Conditional;
upannel.ID = "updatePannel_1";
upannel.ContentTemplateContainer.Controls.Add("Control_TO_Add_In_Update_Panel");
Page.Form.Controls.Add(upannel);

Hope this helps you 🙂

How to parse mails in Microsoft Outlook using C#?

December 25, 2008

We often get hundreds of mails in our Outlook Inbox and want to do some processing with these mails. This scenario arises mainly with the customer support people who wanted to act depending on the mail subject line. Here is a simple code to parse the Microsoft Outlook Inbox:


static void ReadMail()
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;

try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);

inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
// subFolder = inboxFolder.Folders["Inbox"]; //folder.Folders[1]; also works
Console.WriteLine("Folder Name: {0}, EntryId: {1}", inboxFolder.Name, inboxFolder.EntryID);
Console.WriteLine("Num Items: {0}", inboxFolder.Items.Count.ToString());

System.IO.StreamWriter strm = new System.IO.StreamWriter(@"d:\Test\Inbox.txt");
for (int counter = 1; counter <= inboxFolder.Items.Count; counter++)
{
item = (Microsoft.Office.Interop.Outlook.MailItem)inboxFolder.Items[counter];
Console.WriteLine("Item: {0}", counter.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Sendername: {0}", item.SenderName);
strm.WriteLine(counter.ToString() + "," + item.Subject + "," + item.SentOn.ToShortDateString() + "," + item.SenderName);
}
strm.Close();
}
catch (System.Runtime.InteropServices.COMException comException)
{
Console.WriteLine(comException.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}

}

Hope this helps you 🙂

Download Month Calendar User Control!

December 25, 2008

We get many advance Calendar controls on the internet and in controls library, but I was struggling to find the Month Calendar control. A control that will only display months in a year with a hyperlink(event). Finally here is one that I have developed.

Usage:

Code in ASPX Page:

<%@ Register Src=”~/UserControls/MonthSelectControl.ascx” TagName=”MonthSelectControl” TagPrefix=”uc1″ %>

<div>

<uc1:MonthSelectControl ID=”TestControl” runat=”server” />

</div>

Code in .aspx.cs (CodeBehind) Class:

In Page_Load event register the Month Calendar control DateChanged event as shown below:

TestControl.DateChanged += new EventHandler(Control_DateChanged);

Code for the DateChanged Event:

void DateChanged(object sender, EventArgs e)

{

MonthCalendar.MonthCalendarControlEventArgs arg = (MonthCalendar.MonthCalendarControlEventArgs) e;

string month = arg.Month;

string year = arg.Year;

}

Download the control here.

Your comments are welcome 🙂

Why I cannot access classes in .aspx codebehind from the classes in app_code in asp.net?

December 25, 2008

This is a fantastic problem that I faced. I was having a user control in my asp.net application as MSDD.ascx. I wanted to dynamically display this user control from the code written in the Dynamic.cs file in app_code folder of my applicaiton. But at this movement, I was unable to access the MSDD class written in codebehind file from my class in app_code. How can we proceed now???

Solution:

The best solution is to write an Interface. Place this interface in the app_code folder of you application. The aspx codebehind class should implment this particular interface. Now via interface you can access the codebehind class from you class in app_code folder. See the scenario below:

I have following files:

ASPX: A user control/class named MSDD.

app_code: A call named Dynamic, in which I want to access the above user control class MSDD.

Now write an interface IMSDD and make the codebehind class MSDD to implement this IMSDD interface. So you MSDD class will look like:

public class MSDD : IMSDD

{

// Code here…

}

And your Dynamic class which uses the Interface will look like:

public class Dynamic

{

IMSDDctrl = (IMSDD) Page.LoadControl(“../MSDD.ascx”);

// Now using this interface you can invoke any method/property of the MSDD class this is exposed via the interface.

ctrl.Invoke();

}

Hope this helps you…

How to prevent sending an email without subject from Microsoft Outlook?

December 25, 2008

We often feel horrible when we send email messages to our bosses without any subject line. Here is a simple way to avoid such mistakes…

Steps: –
1. Open your Outlook,
2. Press Alt+F11. This opens the Visual Basic Editor and then Press Ctrl+R which in turn open Project-Project 1 (left side)
3. On the Left Pane, one can see “Microsoft Outlook Objects” or “Project1”, expand this. Now one can see the “ThisOutLookSession”.
4. Double click on “ThisOutLookSession”. It will open up a Code Pane on the right hand side.
5. Copy and Paste the following code in the right pane (Code Pane) and save it

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim strSubject As String
strSubject = Item.Subject
If Len(Trim(strSubject)) = 0 Then
Prompt$ = "Subject is Empty. Are you sure you want to send the Mail?"
If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check for Subject") = vbNo Then
Cancel = True
End If
End If
End Sub
6. Save the Project and exit.

Now whenever you try to send a mail without subject, a pop-up is raised to remind you of the blank subject.

How to Bulk Insert records to T-SQL Table from a DataTable in C#?

December 25, 2008

This article will tell you two method of inserting bulk records into a T-SQL table from a DataTable in C#:

1. Bulk insert using the SqlBulkCopy class

2. Bulk insert by passing XML data table to the stored procedure

The first method is used ONLY to insert the data to the database and is simple as compared to the second method. The second method can be used to do some complex processing while inserting/updating the data in the SQL table.

In the first method we will make use of the SqlBulkCopy class provided in .NET. Following code illustrates the use of the SqlBulkCopy class for bulk insert:

#region references
using System.Data;
using System.Data.SqlClient;
#endregion references

namespace SQLBulkInsert
{
class Program
{
static void Main(string[] args)
{
// T-SQL Connection
string connection = "Data source=.; Initial Catalog= MyDatabase; SSPI=true";
DataTable dtData = new DataTable();

// Get the data into the DataTable
//dtData = GetData(...);

// Create an object of SqlBulkCopy
SqlBulkCopy objSBC = new SqlBulkCopy(connection);
// Specify the destination table
objSBC.DestinationTableName = "Table_Name";
// Write the data to the SQL Server
objSBC.WriteToServer(dtData);
}
}
}

You can find the implementation of the second method in my article on CodeProject.com

Hope this helps you!

How to convert int Month to String Month Name in C#?

December 25, 2008

Often we get month as integer from external source and want to display it as “Oct” or “October” i.e. string. Following is a code to convert the int month to string month 🙂

 
/// <summary>
/// Converts the given month int to month name
/// </summary>
/// <param name="month">month int </param>
/// <param name="abbrev">return abbreviated or not</param>
/// <returns>Short or long month name as string </returns>
private static string GetMonthName(int month, bool abbrev)
{
DateTime date = new DateTime(2000, month, 1);
if (abbrev) return date.ToString("MMM");
return date.ToString("MMMM");
}

Hope this helps 🙂

How to program Read,Write parallel port in C#?

August 17, 2008

Introduction

The Parallel Port is the most commonly used port for interfacing homemade projects. Parallel ports are easy to program and faster compared to the serial ports. But main disadvantage is it needs more number of transmission lines. Because of this reason parallel ports are not used in long distance communications. This port allows the input of up to 9 bits or the output of 12 bits at any one given time, thus requiring minimal external circuitry to implement many simpler tasks. The port is composed of 4 control lines, 5 status lines and 8 data lines. It’s found commonly on the back of your PC as a D-Type 25 Pin female connector.


What is a parallel port?

A port contains a set of signal lines that the CPU sends or receives data with other components. We use ports to communicate via modem, printer, keyboard, mouse and other such devices. In signaling, open signals are “1” and close signals are “0” so it is like binary system. A parallel port sends 8 bits and receives 5 bits at a time.
The parallel port comprises of 3 different ports the Data Port, the Status Port and the Control Port. These ports are distributed among the 25 PIN of the port. The data port ranges from PIN 2 to PIN 9 i.e. 8 PIN indicating a byte. The Status port ranges from PIN 10 to PIN 13 and the PIN 15 is also a part of the status port. The Control port comprises of PINs 1, 14, 16 and 17. The detail of these PINs and their functions is given below:
* Pins with * symbol in this table are hardware inverted. That means, If a pin has a ‘low’ ie. 0V, Corresponding bit in the register will have value 1.
Signals with prefix ‘n’ are active low. Normally these pins will have low value. When it needs to send some indication, it will become high. For example, normally nStrobe will be high, when the data is placed in the port, computer makes that pin low.
Normally, data, control and status registers will have following addresses. We need these addresses in programming later.

By default, data port is output port. To enable the bidirectional property of the port, we need to set the bit 5 of control register.
To know the details of parallel ports available in your computer, follow this procedure:
1. Right click on My Computer, go to “Properties”.
2. Select the tab Hardware, Click Device manager.
3. You will get a tree structure of devices; in that Expand “Ports (Com1 &LPT)”.
4. Double Click on the ECP Printer Port (LPT1) or any other LPT port if available.
5. You will get details of LPT port. Make sure that “Use this Port (enable)” is selected.
6. Select tab recourses. In that you will get the address range of port.

Parallel Port Interface Projects
1. Running LED lights.
2. Controlling a remote Car using the computer.
3. Controlling home appliances such as lights, fan, TV etc.
4. Any other gadget that you want to control.

Programming Parallel Port in C#
Till today we use to control the Parallel port using the “Turbo C”, which is easy to code and at the same time powerful to control the parallel port. C lacks the fancy user interface that most of the users are attracted towards. Even in this article we will be using the Console application, you can use the code and create a Windows Forms application for a fancy UI.

I have used an assembly inpout32.dll for interfacing with parallel port. This assembly provides easy access to the interfacing API’s. You can download the assembly from here.

If you are coding in Turbo C, you will end up using the functions outportb() and inportb() from the Stdio.h and IO.h library files.

Create a Console application project using Visual Studio. Add a file PortAccessAPI.cs and add the following code to this file:

// References
using System;
using System.Runtime.InteropServices;

/// <summary>
/// Class to access the Port API's from the inpout32.dll.
/// </summary>
public class PortAccessAPI
{
/// <summary>
/// This method will be used to send the data out to the parallel port.
/// </summary>
/// <param name="adress">Address of the port to which the data needs to be sent.</param>
/// <param name="value">Data that need to send out.</param>
[DllImport("inpout32.dll", EntryPoint="Out32")]
public static extern void Output(int address, int value);

/// <summary>
/// This method will be used to receive any data from the parallel port.
/// </summary>
/// <param name="address">Address of the port from which the data should be received.</param>
/// <returns>Returns Integer read from the given port.</returns>
[DllImport("inpout32.dll", EntryPoint = "Inp32")]
public static extern int Input(int address);
}

The Output function used in the above class will send the data out to the required port. The first parameter i.e. address, indicates the address of the port on which the data needs to be sent. The second parameter i.e. value, indicated the value (as integer) that needs to be sent to the port. In actual the value will be sent as binary on the port and hence an equivalent integer value needs to be computed before invoking this method.

Now in the Program.cs which is the entry point for the Console application, the following code will go in the Main method:

int address = 888;
int value = 24;
PortAccessAPI.Output(adress, value);

Here the address 888 as int is actually 0x378 as Hex, which is the data port of the parallel port.
To reset the data that is sent on the data port, you need to invoke the Output method with a value 0x00 i.e.0 as shown below:

int address = 888;
PortAccessAPI.Output(adress, 0);

This was all about writing data to the parallel port; now let’s see how we can read data from the parallel port. In the file PortAccessAPI.cs we have declared a function “Input”, this will be used to read the parallel port. This function takes a parameter “address”, this is the address of the parallel port that we want to read. This method will return an integer as the data that is read from the requested port. The code will look like:

int address = 888;
int value;
value = PortAccessAPI.Input(adress);

The variable “value” will contain the data that is read from the parallel port 0x378.

References
1. How Inpout32.dll works?
2. Inpout32.dll for Windows 98/NT/2000/XP.

Conclusion
Using this simple technique of read/write we can create innovative gadgets that can be controlled using the computer…

Hope this helps you !
Your comments are always welcome!