Monday, December 26, 2011

encryption and decryption in asp.net c#

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.IO;
using System.Text;

///
/// Summary description for crypto
///

public class Crypto
{
private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

///
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
///

/// The text to encrypt.
/// A password used to generate a key for encryption.
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");

string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.

try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{

//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}

// Return the encrypted bytes from the memory stream.
return outStr;
}

///
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
///

/// The text to decrypt.
/// A password used to generate a key for decryption.
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");

// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;

// Declare the string used to hold
// the decrypted text.
string plaintext = null;

try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))

// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}

return plaintext;
}
}

Sunday, November 27, 2011

JavaScript: Alert.Show(”message”) from ASP.NET code-behind

using System.Web;
using System.Text;
using System.Web.UI;

///
/// A JavaScript alert
///

public static class Alert
{

///
/// Shows a client-side JavaScript alert in the browser.
///

/// The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "";

// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;

// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
Demonstration

That class of only 30 lines of code enables us to add a JavaScript alert to any page at any time. Here is an example of a Button.Click event handler that uses the method for displaying status messages.

void btnSave_Click(object sender, EventArgs e)
{
try
{
SaveSomething();
Alert.Show("You document has been saved");
}
catch (ReadOnlyException)
{
Alert.Show("You do not have write permission to this file");
}
}

Tuesday, November 22, 2011

Upload file in asp.net

public string UploadImage(FileUpload image, int height, int width)
{
string strProfilePicture = "";

if (image.HasFile == true)
{
string ext = System.IO.Path.GetExtension(image.FileName).ToLower();

string[] allowedtypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".JPEG", ".jpg", ".bmp" };

if (allowedtypes.Contains(ext))
{
System.Drawing.Image userimage = System.Drawing.Image.FromStream(image.PostedFile.InputStream);

if (userimage.Height <= height || userimage.Width <= width)
{
if (image.PostedFile.ContentLength <= 512000)
{
string[] mimetypes = new string[] { "image/png", "image/jpeg", "image/pjpeg", "image/gif", "image/bmp" };
string filetype = image.PostedFile.ContentType;
if (mimetypes.Contains(filetype) == false)
{
//lblMassage.Text = "Image is not in the correct format, Please ensure the image is either a JPEG, GIF or PNG";
// return;
}
else
{
string filename = Path.GetFileName(image.FileName);
filename = "PP" + DateTime.Now + ext.ToString();
filename = filename.Replace(":", "");
filename = filename.Replace(" ", "");
filename = filename.Replace("/", "");

image.SaveAs(Server.MapPath("~/UserProfileImage/") + filename);



string strpath = "~/UserProfileImage/" + filename;
strProfilePicture = strpath;

}
}
else
{
//lblMassage.Text = "File is larger than 250kb. Please reduce the Size";
// return;
}
}
else
{
//lblMassage.Text = "The Image is larger than " + width + "x" + height + "px. Please Resize it";
//return;
}




userimage.Dispose();
//
}

}

else if (image.HasFile == false)
{

}

else
{
// error = "Image is not in the correct format, Please ensure the image is either a JPEG, GIF or PNG";
//return;
}


//txtError.Text = error;
//txtSuccessMessage.Text = success;
return strProfilePicture;

}

Warning message in asp.net gridview

write this code block within a span
onclick="return confirm('Are you sure to Delete?')"

Sunday, October 9, 2011

Data Encription and Decription in C#.Net

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.IO;
using System.Text;

///
/// Summary description for crypto
///

public class Crypto
{
private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

///
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
///

/// The text to encrypt.
/// A password used to generate a key for encryption.
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");

string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.

try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{

//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}

// Return the encrypted bytes from the memory stream.
return outStr;
}

///
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
///

/// The text to decrypt.
/// A password used to generate a key for decryption.
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");

// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;

// Declare the string used to hold
// the decrypted text.
string plaintext = null;

try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))

// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}

return plaintext;
}
}

Thursday, September 8, 2011

Multiple Item Drag and Drop Between Tow ListBox

Private Sub lbAll_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lbAll.MouseDown
'If lbAll.Items.Count = 0 Then
' Return
'End If
'Dim s As String = lbAll.Items(lbAll.IndexFromPoint(e.X, e.Y)).ToString()
'Dim dde1 As DragDropEffects = DoDragDrop(s, DragDropEffects.All)

'If dde1 = DragDropEffects.All Then
' 'lbAll.Items.RemoveAt(lbAll.IndexFromPoint(e.X, e.Y))
'End If
lbAll.DoDragDrop(lbAll.SelectedItems, DragDropEffects.Move)
End Sub

Private Sub lbSelected_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lbSelected.DragDrop
'If e.Data.GetDataPresent(DataFormats.StringFormat) Then
' Dim str As String = DirectCast(e.Data.GetData(DataFormats.StringFormat), String)
' lbSelected.Items.Add(str)
'End If

For Each item As Object In (e.Data.GetData(GetType(ListBox.SelectedObjectCollection)))
lbSelected.Items.Add(item)
Next
End Sub

Private Sub lbSelected_DragOver(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lbSelected.DragOver
' e.Effect = DragDropEffects.All
If (e.Data.GetDataPresent(GetType(ListBox.SelectedObjectCollection))) Then
e.Effect = DragDropEffects.Move
Else
e.Effect = DragDropEffects.None
End If
End Sub

Monday, September 5, 2011

Connection String for .xls and .xlsx

MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & G_FilePath & "'; Extended Properties=Excel 8.0;")
Else
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & G_FilePath & "';Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2""")
End If