Sunday, July 5, 2009

Encrypt and Decrypt a String in C# using Cryptography

I am going to explain how to encrypt and decrypt a string in C# using Cryptography and by generating an MD5 hash from the password.

First of all we need to add System.Security.Cryptography; namespace in our code, I am going to create a class with two Methods

1) Encrypter
2) Decrypter

Encrypter used to encrypt a string and Decrypter used to descrypt the string encrypted by Encrypter.

Here is this beautiful class. Its a competetely implemented Class, what all you need to do is just Copy and Paste.

public class EncryptDecrypt
{
public EncryptDecrypt()
{
//
// TODO: Add constructor logic here
//
}

public string Encrypter(string strStringToEncrypt)
{
string strOriginal, strEncryptedString, password;
TripleDESCryptoServiceProvider des;
MD5CryptoServiceProvider hashmd5;
byte[] pwdhash, buff;

//create a secret password. the password is used to encrypt and decrypt
//strings. Without the password, the encrypted string cannot be
//decrypted and is just garbage. You must use the same password to
//decrypt an encrypted string as the string was originally encrypted with.

password = "manojjoshi";

//create a string to encrypt
//original = "String to encrypt";

strOriginal = strStringToEncrypt;

//generate an MD5 hash from the password.a hash is a one way
//encryption meaning once you generate the hash, you cant derive the
//password back from it.

hashmd5 = new MD5CryptoServiceProvider();
pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
hashmd5 = null;

//implement DES3 encryption
des = new TripleDESCryptoServiceProvider();

//the key is the secret password hash.
des.Key = pwdhash;

//the mode is the block cipher mode which is basically the details of how
//the encryption will work. There are several kinds of ciphers available in
//DES3 and they all have benefits and drawbacks. Here the Electronic
//Codebook cipher is used which means that it encrypt each
//block individually and a given bit of text is always encrypted exactly the
// same when the same password is used.

des.Mode = CipherMode.ECB; //CBC, CFB


//----- encrypt an un-encrypted string ------------
//the original string, which needs encrypted, must be in byte array
//form to work with the des3 class. everything will because most encryption
//works at the byte level so you'll find that the class takes in byte
//arrays and returns byte arrays and you'll be converting
//those arrays to strings.

buff = ASCIIEncoding.ASCII.GetBytes(strOriginal);

//encrypt the byte buffer representation of the original string and base64
//encode the encrypted string. The reason the encrypted bytes are being
//base64 encoded as string is the encryption will have created some weird
//characters in there. Base64 encoding provides a platform independent view
//of the encrypted string and can be sent as a plain text string to wherever.

strEncryptedString = Convert.ToBase64String(
des.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length)
);

return strEncryptedString;
}

public string Decrypter(string StrEncryptedString)
{
string decrypted, password;
TripleDESCryptoServiceProvider des;
MD5CryptoServiceProvider hashmd5;
byte[] pwdhash, buff;

//create a secret password. the password is used to encrypt
//and decrypt strings. Without the password, the encrypted
//string cannot be decrypted and is just garbage. You must
//use the same password to decrypt an encrypted string as the
//string was originally encrypted with.
password = "manojjoshi

//generate an MD5 hash from the password.
//a hash is a one way encryption meaning once you generate
//the hash, you cant derive the password back from it.
hashmd5 = new MD5CryptoServiceProvider();
pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
hashmd5 = null;

//implement DES3 encryption
des = new TripleDESCryptoServiceProvider();

//the key is the secret password hash.
des.Key = pwdhash;

//the mode is the block cipher mode which is basically the
//details of how the encryption will work. There are several
//kinds of ciphers available in DES3 and they all have benefits
//and drawbacks. Here the Electronic Codebook cipher is used
//which means that a given bit of text is always encrypted
//exactly the same when the same password is used.
des.Mode = CipherMode.ECB; //CBC, CFB


//----- decrypt an encrypted string ------------
//whenever you decrypt a string, you must do everything you
//did to encrypt the string, but in reverse order. To encrypt,
//first a normal string was des3 encrypted into a byte array
//and then base64 encoded for reliable transmission. So, to
//decrypt this string, first the base64 encoded string must be
//decoded so that just the encrypted byte array remains.
buff = Convert.FromBase64String(StrEncryptedString);

//decrypt DES 3 encrypted byte buffer and return ASCII string
decrypted = ASCIIEncoding.ASCII.GetString(
des.CreateDecryptor().TransformFinalBlock(buff, 0, buff.Length)
);

return decrypted;
}


}

And we are done with this. Now play with encryption and decryption Cheers..

How to Send mail through C# using SMTP

If you need to send mails through your code here is the simple Example in
C#

1) Add the System.Net.Mail; namespace to your code.

2) Wirte this code or modify it according to your need.

SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
string sHostName = "mail.test.com";
string strEmailFrom = "Manoj@mailtest.com";
string sFromName = "Manoj";
string strToEmail = "manojjoshi@gmail.com";
string strSubject = "Test Mail From Manoj";
string strBody = "< table >< tr >< td >This is just a test mail< /td >
< /tr >< /table >"; // Format your massage body here

MailAddress fromAddress = new MailAddress(strEmailFrom, sFromName);

// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost in this case it is mail.test.com
smtpClient.Host = sHostName;
//Default port will be 25
smtpClient.Port = 25;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(strToEmail);
message.Subject = strSubject;
string ccMailIDs = "MyCC1@gmail.com";

///this line of code is for adding more Recipients in cc of your mail

message.CC.Add(new MailAddress(ccMailIDs));
ccMailIDs = "MyCC2@gmail.com";
message.CC.Add(new MailAddress(ccMailIDs));
ccMailIDs = "MyCC3@gmail.com";
message.CC.Add(new MailAddress(ccMailIDs));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = true;
// Message body content
message.Body = strBody;

// Send SMTP mail
smtpClient.Send(message);

}
catch (Exception ex)
{
string s = ex.Message;
}


And you are done. Cheers

Wednesday, July 1, 2009

View State Versus Control State

View State Versus Control State

ViewState is a mechanism through which Asp.Net preserve state of the controls during postback and preserve data in hidden fields. Whenever any request goes to the server the whole value that is in hidden fields decrypt using BASE64 encoding and further incrypt after server response. We can set enable viewstate property to false if we dont want viewstate.

And Control State work in the same manner as ViewState but with a big difference, we can't disable controlstate.Control state is used for storing a control's essential data that is needed on postback to enable the control to function even when view state has been disabled.

Mostly Use the Control State property when you are going to implement Custom Control by overriding the SaveControlState method to save the data in Control State

Cheers

Thursday, June 4, 2009

Rounding a Number in Javascript

function roundToWhatever()

{

var numberToRound = document.getElementById("idOfTheInputProvider").value

var numberToRound = new Number(numberToRound );

var result =numberToRound.toFixed(10);

document.getElementById("idOfTheInputProvider").value = result ;

}

Monday, April 20, 2009

Boxing and Unboxing

Whenever we convert an Value type to a Reference type this process is called Boxing and opposite of that is UnBoxing

for ex :

class BoxingUnBoxing
{
static void Main()
{
int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing
}
}

In this example we are assigning a value type to a reference type (eg. object o = i) , Object o is of reference type and i is of value type. and after that we assign an reference type to a value type (eg. int j = (int) o)

Thursday, April 16, 2009

Cool Rendering of a page like animation Effect :) I Love it

Hi

If you dont like the page loading while page is postback and the page refereshes.
Then try it really very nice feature and make your page loading amazing, really i do that with one of my website. And it loads with fabulous effects. No need to write nasty of codes just put that tag on your master page. and see your site :)

< meta http-equiv="Page-Exit" content="progid:DXImageTransform.Microsoft.Fade(duration=.5)"/>

Keep Smiling :)

Wednesday, April 15, 2009

Add Favicon to your site (Icon that dispays at the start of the url)

Want to add a beautiful icon at the start point of your URL (Called Favicon). Just add this tag to your master Page in the < head> section and before the < /head> Section :

< link rel="shortcut icon" type="image/x-icon" href="favicon.ico">

and place an icon named favicon.ico on the Root directory.

When you add this site to add to favorites it will display the icon along with url. For doing that just add the following code also:

< a href="javascript:window.external.AddFavorite('http://www.test.com', 'Test Site')">
Click here to add Test Site to your favorites < /a>

it's a cool Feature..

Error Handling in Asp.Net

Asp.Net provide there way of handling errors. We can handle error at
1) Page Level
2) Application Level
3) Through Web.Confing


1) Page Level Error Handling :

We can handle error at page level so that if any error comes under the page scope it will handle through the OnError Method of page, But its only at page level not outside that scope. Whenever we create a web form its class drive from System.Web.UI.Page and that why page object help us to invoke page level error. What we do we override OnError method of the page. Like

protected override void OnError(EventArgs e)
{
Exception objException = Server.GetLastError (); // Return Current Exception

string errorDescription =
"Source of Error:" + objException.Source +
"Message : " + objException.Message +
"Stack trace: " + objException.StackTrace;

Response.Write (errorDescription); // Or you can log the Error or redirect to somewhere else/

}

2) Application Level Error Handling :

Another approach for error handling is at application level. Whenever any Error comes Application_Error sub called. Its a good place for handling error because no need to write it on every page. It Works something like that:

void Application_Error(object sender, EventArgs e)
{
Exception objException = Server.GetLastError (); // Return Current Exception

string errorDescription =
"Source of Error: " + objException.Source +
"Message : " + objException.Message +
"Stack trace: " + objException.StackTrace;

// After that use that Error errorDescription as you want eithr make log or redirect to somewhere else/

}
3) Web.Config Custom Errors

Third place is Web.Config, it enables us to configure html error pages to be displayed in place of a error stack trace Yellow page(really developer hate this). Through it we can handle error on specific code or we can create a single page for handling all the Error.

When we create a new website it looks like
Here we have mode attribute which can be "On|Off|RemoteOnly"

"RemoteOnly" options is the default option. Specifies that custom errors are shown only to remote clients, and ASP.NET errors are shown to the local host
"On" option shows custom errors are enabled.

"Off" Specifies custom errors are disabled.

We can handle errors based on specific code like that:

< customErrors mode="On" >
< error statusCode="403" redirect="NoAccess.htm" />
< error statusCode="404" redirect="FileNotFound.aspx" />
< error statusCode="500" redirect="GenericErrorPage.htm"/>


or We can use a single page redirect for all the Errors

< customErrors mode="On" defaultRedirect="ForAllError.htm" />

Stay away from Errors now
Keep Happy and Programming:)

Tuesday, April 14, 2009

Identify Mobile Browser or Iphone using c# Code

Recently i created a mobile browser compatible website for our existing Website.
So as we already marketed our website well for desktop browser but not for Iphone or other Mobile device so we started doing that. Now what client want that whenever any person open our website on mobile device it will redirect to Iphone compatible website
So what, I Just write these lines of code:

if (HttpContext.Current.Request.Browser.IsMobileDevice || HttpContext.Current.Request.UserAgent.ToLower().Contains("iphone"))
{
Response.Redirect("http://iphone.domain.com");
}


on the above code Line
HttpContext.Current.Request.Browser.IsMobileDevice detects the mobile devices but as our Iphone not detected through that so thats why i add one more line :
HttpContext.Current.Request.UserAgent.ToLower().Contains("iphone")
Which detects the Iphone you can use this one for other mobile device not supported by .NET

Import data from Excel to SQl Server

Facing problem while importing table data from Excel to Sql Server.
Some time we have some fields on Excel which contain data which is not supported by
Sql Server like single qote('). I take it just as a example. So i write a program
in c# which collects data from excel table read it make changes on data if we need and insert it to SQL. Problem is basically
that if we have lakhs of record its not possible to edit them manually and then import to sql.

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourExcelDataSource(like D:\\Detail.xls);Extended Properties=""Excel 8.0;HDR=YES;""";
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Data$]", connection);

connection.Open();
DataSet ds = new DataSet();

OleDbDataAdapter oda = new OleDbDataAdapter(command);
oda.Fill(ds);

string sqlConnectionString = "Data Source= SqlDataSource; Initial Catalog=DataBaseName;uid=Userid; Password=pwd";

SqlConnection con = new SqlConnection(sqlConnectionString);
con.Open();

for (int c = 0;c < ds.Tables[0].Rows.Count;c++)
{
try
{
DataRow dro = ds.Tables[0].Rows[c];

object[] array = ds.Tables[0].Rows[c].ItemArray; //Break Table to array

string str = "insert into tableName values(";

for (int k = 1; k < array.Length; k++)
{
if (array[k].ToString().Contains("'"))
{
array[k] = array[k].ToString().Replace("'", "''");
}

str = str+"'"+ array[k] + "',";
}


str = str.Substring(0, str.Length - 1);
str = str + ")";
SqlCommand com = new SqlCommand(str);
com.Connection = con;
com.ExecuteNonQuery();
}
catch(Exception ex)
{
continue;
}
}
//}
}
}
}

Validation of viewstate MAC failed / The state information is invalid for this page and might be corrupted Problem

facing a new problem
Validation of viewstate MAC failed / The state information is invalid for this page and might be corrupted

I face this problem long time ago. My websites woriking well at my end in India office and on my client system also. But problem was that it was not working on some system (another office) and they told me that they face some problem (Site through errors) as i use custom error so the error will not display but site was not working. The error we got was
Validation of viewstate MAC failed / The state information is invalid for this page and might be corrupted

So i worked on that and got the answer (after googling). Just add it to your webconfig file: -
pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never" enableViewStateMac="false" />

and problem resolved

IE8 Compatibility Problem

Hi,
Have u in trouble due to not working of your site on IE8 (but Working well on IE7). Here is the
solution (I faced in one of my project).
Just add a HTTP-EQUIV meta tag on your master page if you have or place it on your page
meta equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
and see your website working on IE8 .
Keep Smiling and Programming :)

Its all about .Net (Share your Knowldge here)

Hi,
Share your views, Knowldge and problems here

Thanks