Tuesday, February 14, 2012

Only digit in text box in vb.net

Public Function TrapKey(ByVal KCode As String) As Boolean

If (KCode >= 48 And KCode <= 57) Or KCode = 8 Or KCode = 46 Then

'The AsCII values for numbers are between 48 to 57 and ASCII value 8 is for BackSpace.

TrapKey = False

Else

TrapKey = True

End If

End Function

Monday, January 23, 2012

Populate Tree view in vb.net from data base(parent child realation)

Private Sub Filltree()
Dim DSNWind As DataSet


Dim oRead As System.IO.StreamReader
Dim EntireFile As String
oRead = IO.File.OpenText(Application.StartupPath() + "/connection.txt")
EntireFile = oRead.ReadToEnd()
'end soumen
Dim connectionString As String = EntireFile
Dim conn As New SqlConnection(connectionString)
Dim dadagdetails As New SqlDataAdapter("select dd.dagdeatilsid,'Land type--'+l.landtype+',Satak--'+cast(dd.quantity as varchar) as [Details]from tblDagdetails as dd inner join tbllandtype as l on dd.landtype=l.landtypeid where dd.dagid='" + cmbDag.SelectedValue.ToString() + "'", conn)
Dim daowner As New SqlDataAdapter("select * from tblowner ", conn)
Dim daownerrealation As New SqlDataAdapter("select * from tblOwner", conn)
DSNWind = New DataSet

dadagdetails.Fill(DSNWind, "dagdetails")
daowner.Fill(DSNWind, "owner")
daownerrealation.Fill(DSNWind, "ownerrealation")


'DSNWind = New DataSet()
' DSNWind = db.GetDataSet("select dd.dagdeatilsid,'Land type--'+l.landtype+',Satak--'+cast(dd.quantity as varchar) as [Details]from tblDagdetails as dd inner join tbllandtype as l on dd.landtype=l.landtypeid where dd.dagid='" + cmbDag.SelectedValue.ToString() + "'", "dagdetails")
' DSNWind = db.GetDataSet("select * from tblowner ", "owner") 'where dagdetailsid=
' DSNWind = db.GetDataSet("select * from tblOwner ", "ownerrealation") 'where


'Create a data relation object to facilitate the relationship between the Customers and Orders data tables.
DSNWind.Relations.Add("tblDagdetails", DSNWind.Tables("dagdetails").Columns("dagdeatilsid"), DSNWind.Tables("owner").Columns("dagdetailsid"))
DSNWind.Relations.Add("tblOwner", DSNWind.Tables("owner").Columns("ownerid"), DSNWind.Tables("ownerrealation").Columns("parentid"), False)
'''''''''''''''''''''''


TreeView1.Nodes.Clear()
Dim i, n As Integer
Dim parentrow As DataRow
Dim ParentTable As DataTable
ParentTable = DSNWind.Tables("dagdetails")

For Each parentrow In ParentTable.Rows
Dim parentnode As TreeNode
parentnode = New TreeNode(parentrow.Item(1))
TreeView1.Nodes.Add(parentnode)
''''populate child'''''
'''''''''''''''''''''''
Dim childrow As DataRow
Dim childnode As TreeNode
childnode = New TreeNode()
For Each childrow In parentrow.GetChildRows("tblDagdetails")
childnode = parentnode.Nodes.Add(childrow(3)) ' & " " & childrow(1) & " " & childrow(2))
childnode.Tag = childrow("dagdetailsid")
''''populate child2''''
''''''''''''''''''''''''''
Dim childrow2 As DataRow
Dim childnode2 As TreeNode
childnode2 = New TreeNode()
For Each childrow2 In childrow.GetChildRows("tblOwner")
childnode2 = childnode.Nodes.Add(childrow2(3))

Next childrow2
''''''''''''''''''''''''

Next childrow
'''''''''''''''
Next parentrow

End Sub

Monday, December 26, 2011

call javascript function from grid link button

Link Button OnClientClick
OnClientClick='<%# Eval("unt_id", "GetAllForEdit(\"{0}\"); return false;") %>'

JAVA Script function
function GetAllForEdit(iid) {

document.getElementById("ContentPlaceHolder1_hdfUnitID").value = iid;
document.getElementById("ContentPlaceHolder1_btntemp").click();
}

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?')"