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();
}
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;
}
}
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");
}
}
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;
}
{
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?')"
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;
}
}
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
'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
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
Tuesday, August 30, 2011
Tuesday, August 23, 2011
Send mail in vb.net ,desktop applicaton
Dim Mail As New MailMessage()
Mail.To.Add(New MailAddress("tomail@gmail.com"))
Mail.From = (New MailAddress("frommail@gmail.com"))
Mail.Subject = "Mail subject"
Mail.Body = "Mail body"
Mail.IsBodyHtml = True
Dim smtpClient As New SmtpClient("smtp.gmail.com")
smtpClient.Host = "smtp.gmail.com"
smtpClient.Port = 587
smtpClient.EnableSsl = True
Dim userpass As New Net.NetworkCredential("frommail@gmail.com", "frommail_password")
smtpClient.Credentials = userpass
smtpClient.Send(Mail)
MessageBox.Show("Mail Send")
Mail.To.Add(New MailAddress("tomail@gmail.com"))
Mail.From = (New MailAddress("frommail@gmail.com"))
Mail.Subject = "Mail subject"
Mail.Body = "Mail body"
Mail.IsBodyHtml = True
Dim smtpClient As New SmtpClient("smtp.gmail.com")
smtpClient.Host = "smtp.gmail.com"
smtpClient.Port = 587
smtpClient.EnableSsl = True
Dim userpass As New Net.NetworkCredential("frommail@gmail.com", "frommail_password")
smtpClient.Credentials = userpass
smtpClient.Send(Mail)
MessageBox.Show("Mail Send")
Friday, August 19, 2011
Thursday, August 18, 2011
get gridview rowindex commandargument
delete a perticular row by rowindex
protected void grdRoomNumber_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
grdRoomNumber.DeleteRow(Convert.ToInt32(e.CommandArgument));
}
}
Sunday, August 7, 2011
RANDOM DATATABLE ROW
static Random _rand = new Random();
public DataView RandomizeDataTable(DataTable dt)
{
// Create array of indices and populate with ordinal values
int[] indices = new int[dt.Rows.Count];
for (int i = 0; i < indices.Length; i++)
indices[i] = i;
// Knuth-Fisher-Yates shuffle indices randomly
for (int i = indices.Length - 1; i > 0; i--)
{
int n = _rand.Next(i + 1);
int tmp = indices[i];
indices[i] = indices[n];
indices[n] = tmp;
}
// Add new column to data table (if it's not there already)
// to store shuffle index
if (dt.Columns["rndSortId"] == null)
dt.Columns.Add(new DataColumn("rndSortId", typeof(int)));
int rndSortColIdx = dt.Columns["rndSortId"].Ordinal;
for (int i = 0; i < dt.Rows.Count; i++)
dt.Rows[i][rndSortColIdx] = indices[i];
DataView dv = new DataView(dt);
dv.Sort = "rndSortId";
return dv;
}
public DataView RandomizeDataTable(DataTable dt)
{
// Create array of indices and populate with ordinal values
int[] indices = new int[dt.Rows.Count];
for (int i = 0; i < indices.Length; i++)
indices[i] = i;
// Knuth-Fisher-Yates shuffle indices randomly
for (int i = indices.Length - 1; i > 0; i--)
{
int n = _rand.Next(i + 1);
int tmp = indices[i];
indices[i] = indices[n];
indices[n] = tmp;
}
// Add new column to data table (if it's not there already)
// to store shuffle index
if (dt.Columns["rndSortId"] == null)
dt.Columns.Add(new DataColumn("rndSortId", typeof(int)));
int rndSortColIdx = dt.Columns["rndSortId"].Ordinal;
for (int i = 0; i < dt.Rows.Count; i++)
dt.Rows[i][rndSortColIdx] = indices[i];
DataView dv = new DataView(dt);
dv.Sort = "rndSortId";
return dv;
}
Tuesday, August 2, 2011
Monday, July 25, 2011
MAIL SENDING CODE IN ASP.NET C#
private void SendMail(string To, string subject, string body)
{
NetworkCredential loginInfo = new NetworkCredential("YOURUSERNAME@gmail.com", "PASSWORD");
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("YOURUSERNAME@gmail.com");
msg.To.Add(new MailAddress(To));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
{
NetworkCredential loginInfo = new NetworkCredential("YOURUSERNAME@gmail.com", "PASSWORD");
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("YOURUSERNAME@gmail.com");
msg.To.Add(new MailAddress(To));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
Tuesday, July 19, 2011
CDataAccess
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
namespace DBManager
{
///
/// Summary description for CDataAccess
///
///
#region "CDataAccess Class"
public class CDataAccess
{
#region "Fields and Enums"
// Fields
private SqlConnection connection;
private string connectionString;
private CDataAccess.DataAccessErrors errorCode;
private string errorMessage;
private bool isBeginTransaction;
private bool keepConnectionOpened;
private SqlDataAdapter daDataAdapter;
private DataTable dtDataTable;
private DataView dvDataView;
private SqlCommandBuilder cbCommandBuilder;
// Nested Types
public enum DataAccessErrors
{
Successful = 0,
Failed = 1,
ConnectionOpenFailure = 2,
ConnectionAlreadyOpened = 3,
DataFetchFailure = 4,
DataInsertFailure = 5,
DataUpdateFailure = 6,
ConcurrencyError = 7,
AddNewFailure = 8,
AllowNewFailure = 9,
RecordMovementfailed = 10
//public int value__;
}
#endregion
#region "Properties"
public string ConnectionString
{
get
{
return this.connectionString;
}
set
{
this.connectionString = value;
}
}
public CDataAccess.DataAccessErrors ErrorCode
{
get
{
return this.errorCode;
}
}
public string ErrorMessage
{
get
{
return this.errorMessage;
}
}
#endregion
#region "Constructors"
public CDataAccess()
{
this.connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["saveconnection"].ToString(); ;
connection = new SqlConnection(this.connectionString);
}
public CDataAccess(string connectionString)
{
this.connectionString = connectionString;
this.errorCode = CDataAccess.DataAccessErrors.Successful;
this.errorMessage = "";
this.connection = null;
this.keepConnectionOpened = false;
this.isBeginTransaction = false;
this.ConnectionString = connectionString;
}
#endregion
#region "Connection Related"
public SqlConnection GetConnection()
{
return new SqlConnection(this.connectionString);
}
public bool OpenConnection()
{
bool flag1;
if ((this.connection != null) && (this.connection.State == ConnectionState.Open))
{
this.errorCode = CDataAccess.DataAccessErrors.ConnectionAlreadyOpened;
return true;
}
try
{
this.connection = new SqlConnection(this.connectionString);
this.connection.Open();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
this.errorMessage = "";
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
public void CloseConnection()
{
if (!this.keepConnectionOpened)
{
if ((this.connection != null) && (this.connection.State == ConnectionState.Open))
{
this.connection.Close();
}
this.connection = null;
}
}
#endregion
#region "Parameter Related"
private void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters != null) && (parameterValues != null))
{
bool flag1 = commandParameters[0].ParameterName == "@RETURN_VALUE";
if (commandParameters.Length != parameterValues.Length)
{
if (!flag1)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
if ((commandParameters.Length - parameterValues.Length) != 1)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
}
if (flag1)
{
int num1 = 1;
int num2 = commandParameters.Length;
while (num1 < num2)
{
commandParameters[num1].Value = parameterValues[num1 - 1];
num1++;
}
}
else
{
int num3 = 0;
int num4 = commandParameters.Length;
while (num3 < num4)
{
commandParameters[num3].Value = parameterValues[num3];
num3++;
}
}
}
}
private void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
foreach (SqlParameter parameter1 in commandParameters)
{
if ((parameter1.Direction == ParameterDirection.InputOutput) && (parameter1.Value == null))
{
parameter1.Value = DBNull.Value;
}
command.Parameters.Add(parameter1);
}
}
#endregion
#region "Transaction Related"
public bool BeginTransaction()
{
bool flag1;
try
{
this.GetCommand("Start Transaction;").ExecuteNonQuery();
this.isBeginTransaction = true;
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
public bool CommitTransaction()
{
bool flag1;
try
{
this.GetCommand("Commit;").ExecuteNonQuery();
this.CloseConnection();
this.isBeginTransaction = false;
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
public bool RollbackTransaction()
{
bool flag1;
try
{
this.GetCommand("Rollback;").ExecuteNonQuery();
this.CloseConnection();
this.isBeginTransaction = false;
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
#endregion
#region "Execute SQL and SP"
public int Execute(string StrTSQL)
{
int num2;
try
{
int num1 = this.GetCommand(StrTSQL).ExecuteNonQuery();
num2 = num1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return num2;
}
public DataSet ExecuteSP(string spName)
{
DataSet set2;
try
{
this.OpenConnection();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
DataSet set1 = this.ExecuteSP(spName, null);
if (!this.isBeginTransaction)
{
this.CloseConnection();
}
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSP(SqlTransaction transaction, string spName)
{
DataSet set2;
try
{
DataSet set1 = this.ExecuteSP(transaction, spName, null);
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSP(string spName, params SqlParameter[] commandParameters)
{
DataSet set2;
try
{
this.OpenConnection();
SqlCommand command1 = new SqlCommand();
this.PrepareCommand(command1, null, spName, commandParameters);
SqlDataAdapter adapter1 = new SqlDataAdapter(command1);
DataSet set1 = new DataSet();
adapter1.Fill(set1);
command1.Parameters.Clear();
set2 = set1;
this.CloseConnection();
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSP(SqlTransaction transaction, string spName, params object[] parameterValues)
{
DataSet set2;
try
{
this.connection = transaction.Connection;
DataSet set1 = null;
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(transaction.Connection, spName, false);
this.AssignParameterValues(parameterArray1, parameterValues);
set1 = this.ExecuteSP(transaction, spName, parameterArray1);
}
else
{
set1 = this.ExecuteSP(transaction, spName);
}
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSPWithDataSet(string spName, params object[] parameterValues)
{
DataSet set1 = null;
if ((parameterValues != null) && (parameterValues.Length > 0))
{
this.OpenConnection();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(this.connection, spName, true);
this.AssignParameterValues(parameterArray1, parameterValues);
return this.ExecuteSP(spName, parameterArray1);
}
this.ExecuteSP(spName);
if (!this.isBeginTransaction)
{
this.CloseConnection();
}
return set1;
}
public int ExecuteSPWithReturn(string spName, params object[] parameterValues)
{
int num1 = 0;
if ((parameterValues != null) && (parameterValues.Length > 0))
{
this.OpenConnection();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(this.connection, spName, true);
this.AssignParameterValues(parameterArray1, parameterValues);
this.ExecuteSP(spName, parameterArray1);
num1 = (int)parameterArray1[0].Value;
}
else
{
this.ExecuteSP(spName);
}
if (!this.isBeginTransaction)
{
this.CloseConnection();
}
return num1;
}
public DataTable ExecuteSPWithReturnDataTable(String spName, params SqlParameter[] CommandParameter)
{
DataTable tmpDataTable = new DataTable();
//try
//{
this.OpenConnection();
SqlCommand sqlCommand = new SqlCommand();
this.PrepareCommand(sqlCommand, null, spName, CommandParameter);
//this.PrepareCommand(sqlCommand, null, spName, CommandParameter);
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter(sqlCommand);
SqlDataAdapter.Fill(tmpDataTable).ToString();
this.CloseConnection();
//}
//catch (SqlException exception1)
//{
// //(exception1.Message);
//}
//Catch exception2 As Exception
// Throw New Exception(exception2.Message)
//End Try
return tmpDataTable;
}
#endregion
#region "Display Message"
public void DisplayMessage(ref Panel pPanel, string sText)
{
Label lblText = new Label();
lblText.Text = sText;
lblText.CssClass = "Red";
lblText.ForeColor = System.Drawing.Color.Red;
lblText.Font.Size = 7;
lblText.Font.Bold = true;
pPanel.Controls.Add(lblText);
}
#endregion
#region "Destructor"
~CDataAccess()
{
if (this.isBeginTransaction)
{
throw new Exception("Begin transaction without Rollback or Commit. Please check your code");
}
}
#endregion
#region "Command Related"
public SqlCommand GetCommand(string StrTSQL)
{
SqlCommand command2;
try
{
SqlCommand command1 = new SqlCommand();
this.OpenConnection();
command1.Connection = this.connection;
command1.CommandText = StrTSQL;
command2 = command1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return command2;
}
public void ExecuteQuery(String strSql)
{
this.OpenConnection();
SqlCommand tmpCommand = new SqlCommand(strSql, this.connection);
tmpCommand.ExecuteNonQuery();
this.CloseConnection();
}
public int ExecuteQuery(String strSql,string dummy)
{
this.OpenConnection();
SqlCommand tmpCommand = new SqlCommand(strSql, this.connection);
int NoofRowsAffected = tmpCommand.ExecuteNonQuery();
this.CloseConnection();
return NoofRowsAffected;
}
private void PrepareCommand(SqlCommand command, SqlTransaction transaction, string commandText, SqlParameter[] commandParameters)
{
//this.PrepareCommand(command1, null, spName, commandParameters);
command.Connection = this.connection;
command.CommandText = commandText;
if (transaction != null)
{
command.Transaction = transaction;
}
command.CommandType = CommandType.StoredProcedure;
if (commandParameters != null)
{
this.AttachParameters(command, commandParameters);
}
}
#endregion
#region "GetDataAdapter"
public SqlDataAdapter GetDataAdapter(string StrSQL)
{
SqlDataAdapter adapter2;
try
{
SqlDataAdapter adapter1 = new SqlDataAdapter(StrSQL, this.connectionString);
adapter2 = adapter1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return adapter2;
}
#endregion
#region "GetDataReader"
public SqlDataReader GetDataReader(string StrSQL)
{
SqlDataReader reader2;
try
{
SqlDataReader reader1 = null;
reader1 = this.GetCommand(StrSQL).ExecuteReader(CommandBehavior.Default);
reader2 = reader1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return reader2;
}
public SqlDataReader GetDataReaderSP(string spName, params SqlParameter[] commandParameters)
{
SqlCommand command1 = new SqlCommand();
this.PrepareCommand(command1, null, spName, commandParameters);
SqlDataAdapter adapter1 = new SqlDataAdapter(command1);
SqlDataReader reader1 = command1.ExecuteReader(CommandBehavior.Default);
command1.Parameters.Clear();
return reader1;
}
public SqlDataReader GetDataReaderSP(string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
this.errorCode = CDataAccess.DataAccessErrors.Successful;
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(this.connection, spName, false);
this.AssignParameterValues(parameterArray1, parameterValues);
return this.GetDataReaderSP(spName, parameterArray1);
}
return this.GetDataReaderSP(spName, null);
}
#endregion
#region "GetDataSet"
public DataSet GetDataSet(string StrSQL, string DateSetName)
{
DataSet set2;
try
{
DataSet set1 = new DataSet();
this.OpenConnection();
new SqlDataAdapter(StrSQL, this.connectionString).Fill(set1, DateSetName);
this.CloseConnection();
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet GetDataSet(string strSQL, string strTable, ref SqlDataAdapter m_DataAdapter, ref DataTable m_DataTable, ref DataView m_DataView)
{
DataSet dsDataSet2 = null;
try
{
this.OpenConnection();
DataSet Set1 = new DataSet();
SqlCommand cmCommand;
cmCommand = new SqlCommand(strSQL, connection);
daDataAdapter = new SqlDataAdapter(cmCommand);
SqlCommandBuilder cbCommandBuilder = new SqlCommandBuilder(daDataAdapter);
//Build the Data Operation SQL if flag is True
cbCommandBuilder.GetUpdateCommand();
DataSet dsDataSet = new DataSet();
m_DataAdapter.Fill(dsDataSet, strTable);
dsDataSet2.Merge(dsDataSet);
dtDataTable = dsDataSet.Tables[0];
dvDataView = dtDataTable.DefaultView;
dvDataView.AllowNew = false;
this.CloseConnection();
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return dsDataSet2;
}
public DataSet GetDataSet(string strSQL, string strTable, ref SqlDataAdapter m_DataAdapter, ref DataSet m_DataSet)
{
this.OpenConnection();
DataSet tmpDataSet = new DataSet();
SqlCommand m_Command;
m_Command = new SqlCommand(strSQL, this.connection);
m_DataAdapter = new SqlDataAdapter(m_Command);
SqlCommandBuilder m_CommandBuilder = new SqlCommandBuilder(m_DataAdapter);
cbCommandBuilder.GetUpdateCommand();
m_DataAdapter.Fill(m_DataSet, strTable);
m_DataSet.Merge(tmpDataSet);
this.CloseConnection();
return m_DataSet;
}
public DataSet GetDataSet(string strSQL, string strTable, ref DataSet m_DataSet)
{
this.OpenConnection();
SqlDataAdapter m_SQL_DataAdapter;
SqlCommand m_SQL_Command;
DataSet tmpDataSet = new DataSet();
m_SQL_Command = new SqlCommand(strSQL, this.connection);
m_SQL_DataAdapter = new SqlDataAdapter(m_SQL_Command);
m_SQL_DataAdapter.Fill(tmpDataSet, strTable);
m_DataSet.Merge(tmpDataSet);
this.CloseConnection();
return m_DataSet;
}
public DataSet GetDataSet(string strSQL, string strTable, ref DataSet m_DataSet, int BuildCommand)
{
this.OpenConnection();
DataSet tmpDataSet = new DataSet();
SqlCommand cmCommand;
cmCommand = new SqlCommand(strSQL, this.connection);
daDataAdapter = new SqlDataAdapter(cmCommand);
cbCommandBuilder = new SqlCommandBuilder(daDataAdapter);
cbCommandBuilder.GetUpdateCommand();
daDataAdapter.Fill(m_DataSet, strTable);
m_DataSet.Merge(tmpDataSet);
this.CloseConnection();
return m_DataSet;
}
#endregion
#region "GetDataTable"
public DataTable GetDataTable(string strSQL)
{
this.OpenConnection();
SqlCommand m_Command;
m_Command = new SqlCommand(strSQL, this.connection);
SqlDataAdapter tmpDataAdapter;
tmpDataAdapter = new SqlDataAdapter(m_Command);
DataTable tmpDataTable = new DataTable();
tmpDataAdapter.Fill(tmpDataTable);
this.CloseConnection();
return tmpDataTable;
}
#endregion
#region "FillCombo"
public void FillCombo(ref DropDownList Combo, string strSQL, bool AddAllOption, bool None)
{
DataTable dtTable = GetDataTable(strSQL);
if ((None))
{
DataRow drDataRow;
drDataRow = dtTable.NewRow();
drDataRow[0] = -1;
drDataRow[1] = "";
dtTable.Rows.Add(drDataRow);
}
if ((AddAllOption))
{
DataRow drDataRow;
drDataRow = dtTable.NewRow();
drDataRow[0] = 0;
drDataRow[1] = "_ALL_";
dtTable.Rows.Add(drDataRow);
}
{
DataView DataView = dtTable.DefaultView;
DataView.Sort = dtTable.Columns[1].ColumnName;
Combo.DataSource = DataView;
Combo.DataTextField = dtTable.Columns[1].ColumnName;
Combo.DataValueField = dtTable.Columns[0].ColumnName;
Combo.DataBind();
}
}
#endregion
#region "SqlParameterCache Class"
public sealed class SqlParameterCache
{
// Methods
static SqlParameterCache()
{
CDataAccess.SqlParameterCache.paramCache = Hashtable.Synchronized(new Hashtable());
}
private SqlParameterCache()
{
}
private static void CacheParameterSet(string connectionString, string spName, params SqlParameter[] commandParameters)
{
string text1 = connectionString + ":" + spName;
CDataAccess.SqlParameterCache.paramCache[text1] = commandParameters;
}
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] parameterArray1 = new SqlParameter[originalParameters.Length];
int num1 = 0;
int num2 = originalParameters.Length;
while (num1 < num2)
{
parameterArray1[num1] = (SqlParameter)((ICloneable)originalParameters[num1]).Clone();
num1++;
}
return parameterArray1;
}
private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
using (SqlCommand command1 = new SqlCommand(spName, connection))
{
command1.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(command1);
if (!includeReturnValueParameter)
{
command1.Parameters.RemoveAt(0);
}
SqlParameter[] parameterArray1 = new SqlParameter[command1.Parameters.Count];
command1.Parameters.CopyTo(parameterArray1, 0);
return parameterArray1;
}
}
private static SqlParameter[] GetCachedParameterSet(string connectionString, string spName)
{
string text1 = connectionString + ":" + spName;
SqlParameter[] parameterArray1 = (SqlParameter[])CDataAccess.SqlParameterCache.paramCache[text1];
if (parameterArray1 == null)
{
return null;
}
return CDataAccess.SqlParameterCache.CloneParameters(parameterArray1);
}
public static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
{
return CDataAccess.SqlParameterCache.GetSpParameterSet(connection, spName, false);
}
public static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
string text1 = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");
SqlParameter[] parameterArray1 = (SqlParameter[])CDataAccess.SqlParameterCache.paramCache[text1];
if (parameterArray1 == null)
{
object obj1;
CDataAccess.SqlParameterCache.paramCache[text1] = obj1 = CDataAccess.SqlParameterCache.DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
parameterArray1 = (SqlParameter[])obj1;
}
return CDataAccess.SqlParameterCache.CloneParameters(parameterArray1);
}
// Fields
private static Hashtable paramCache;
}
#endregion
//Open file into a filestream and
//read data in a byte array.
public byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open,
FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to
//supply number of bytes to read from file.
//In this case we want to read entire file.
//So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
#region "InitializeGrid"
//public void InitializeGrid(ref UltraWebGrid Grid)
//{
// // Grid.JavaScriptFileName = "../../infragistics/scripts/ig_WebGrid.js";
// //Grid.JavaScriptFileNameCommon = "../../infragistics/scripts/ig_csom.js";
// Grid.DisplayLayout.AllowColSizingDefault = AllowSizing.Free;
// Grid.DisplayLayout.AllowColumnMovingDefault = Infragistics.WebUI.UltraWebGrid.AllowColumnMoving.OnServer;
// Grid.DisplayLayout.AllowSortingDefault = AllowSorting.OnClient;
// Grid.DisplayLayout.CellClickActionDefault = CellClickAction.RowSelect;
// Grid.DisplayLayout.CellPaddingDefault = 1;
// Grid.DisplayLayout.ColHeadersVisibleDefault = ShowMarginInfo.Yes;
// Grid.DisplayLayout.HeaderClickActionDefault = HeaderClickAction.SortSingle;
// //Header Style
// Grid.DisplayLayout.HeaderStyleDefault.CssClass = "GridHeader";
// Grid.DisplayLayout.HeaderStyleDefault.Font.Bold = true;
// //Sort
// Grid.DisplayLayout.AllowSortingDefault = Infragistics.WebUI.UltraWebGrid.AllowSorting.OnClient;
// Grid.DisplayLayout.HeaderClickActionDefault = Infragistics.WebUI.UltraWebGrid.HeaderClickAction.SortSingle;
// Grid.DisplayLayout.NoDataMessage = "No Records Found";
// Grid.DisplayLayout.NullTextDefault = "";
// Grid.DisplayLayout.RowStyleDefault.CssClass = "GridRowEven";
// Grid.DisplayLayout.RowAlternateStyleDefault.CssClass = "GridRowOdd";
// //Grid.DisplayLayout.RowAlternateStyleDefault.BackColor = Drawing.Color.FromArgb(255, 255, 215);
// //Grid.DisplayLayout.RowAlternateStyleDefault.BackColor = Gray;
// //Padding
// Grid.DisplayLayout.CellPaddingDefault = 3;
// Grid.DisplayLayout.RowAlternateStyleDefault.TextOverflow = TextOverflow.Ellipsis;
// Grid.DisplayLayout.RowHeightDefault = 25;
// Grid.DisplayLayout.RowSelectorsDefault = RowSelectors.No;
// Grid.DisplayLayout.RowSizingDefault = AllowSizing.Fixed;
// Grid.DisplayLayout.ScrollBar = ScrollBar.Auto;
// Grid.DisplayLayout.ScrollBarView = ScrollBarView.Both;
// Grid.DisplayLayout.SelectedRowStyleDefault.CssClass = "GridSelectedRow";
// Grid.DisplayLayout.SelectTypeCellDefault = SelectType.None;
// Grid.DisplayLayout.SelectTypeColDefault = SelectType.None;
// Grid.DisplayLayout.SelectTypeRowDefault = SelectType.Single;
// Grid.DisplayLayout.StationaryMargins = StationaryMargins.No;
// Grid.DisplayLayout.TabDirection = TabDirection.LeftToRight;
// Grid.DisplayLayout.ViewType = Infragistics.WebUI.UltraWebGrid.ViewType.Flat;
// Grid.CssClass = "Grid";
// Grid.BorderStyle = BorderStyle.Solid;
//}
#endregion
public string VoucherNumber(String strHead)
{
String strSql;
String strCode;
DataTable tmpDataTable;
strSql = "SELECT * FROM tblAutoNumber ";
strSql += "WHERE Head = '" + strHead + "'";
tmpDataTable = GetDataTable(strSql);
strCode = tmpDataTable.Rows[0]["Prefix"] + "/";
strCode += DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "/";
strCode += Convert.ToString(Convert.ToInt32(tmpDataTable.Rows[0]["Number"]) + 1);
if (Convert.ToString(tmpDataTable.Rows[0]["SufixCheck"]) == "True")
{
strCode += "/" + tmpDataTable.Rows[0]["Sufix"];
}
return (strCode);
}
//public void AddValueListItemToGrid(ref Infragistics.WebUI.UltraWebGrid.UltraWebGrid Grid, String strSQL, int ColumnIndex) //int BandIndex = 0
//{
// Int32 iCount;
// Infragistics.WebUI.UltraWebGrid.ValueList vValue = new ValueList();
// DataTable tmpDataTable = GetDataTable(strSQL);
// //vValue = Grid.DisplayLayout.ValueLists.Add
// for (iCount = 0; iCount <= tmpDataTable.Rows.Count - 1; iCount++)
// {
// //vValue.ValueListItems.Add(tmpDataTable.Rows[iCount][0],(tmpDataTable.Rows[iCount][1])=null, "", tmpDataTable.Rows[iCount][1]);
// vValue.ValueListItems.Add(tmpDataTable.Rows[iCount][1]);
// }
// vValue.DisplayStyle = Infragistics.WebUI.UltraWebGrid.ValueListDisplayStyle.DisplayText;
// //vValue.SortStyle = Infragistics.Win.ValueListSortStyle.Ascending
// Grid.DisplayLayout.Bands[0].Columns[ColumnIndex].ValueList = vValue;
//}
}
#endregion
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
namespace DBManager
{
///
/// Summary description for CDataAccess
///
///
#region "CDataAccess Class"
public class CDataAccess
{
#region "Fields and Enums"
// Fields
private SqlConnection connection;
private string connectionString;
private CDataAccess.DataAccessErrors errorCode;
private string errorMessage;
private bool isBeginTransaction;
private bool keepConnectionOpened;
private SqlDataAdapter daDataAdapter;
private DataTable dtDataTable;
private DataView dvDataView;
private SqlCommandBuilder cbCommandBuilder;
// Nested Types
public enum DataAccessErrors
{
Successful = 0,
Failed = 1,
ConnectionOpenFailure = 2,
ConnectionAlreadyOpened = 3,
DataFetchFailure = 4,
DataInsertFailure = 5,
DataUpdateFailure = 6,
ConcurrencyError = 7,
AddNewFailure = 8,
AllowNewFailure = 9,
RecordMovementfailed = 10
//public int value__;
}
#endregion
#region "Properties"
public string ConnectionString
{
get
{
return this.connectionString;
}
set
{
this.connectionString = value;
}
}
public CDataAccess.DataAccessErrors ErrorCode
{
get
{
return this.errorCode;
}
}
public string ErrorMessage
{
get
{
return this.errorMessage;
}
}
#endregion
#region "Constructors"
public CDataAccess()
{
this.connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["saveconnection"].ToString(); ;
connection = new SqlConnection(this.connectionString);
}
public CDataAccess(string connectionString)
{
this.connectionString = connectionString;
this.errorCode = CDataAccess.DataAccessErrors.Successful;
this.errorMessage = "";
this.connection = null;
this.keepConnectionOpened = false;
this.isBeginTransaction = false;
this.ConnectionString = connectionString;
}
#endregion
#region "Connection Related"
public SqlConnection GetConnection()
{
return new SqlConnection(this.connectionString);
}
public bool OpenConnection()
{
bool flag1;
if ((this.connection != null) && (this.connection.State == ConnectionState.Open))
{
this.errorCode = CDataAccess.DataAccessErrors.ConnectionAlreadyOpened;
return true;
}
try
{
this.connection = new SqlConnection(this.connectionString);
this.connection.Open();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
this.errorMessage = "";
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
public void CloseConnection()
{
if (!this.keepConnectionOpened)
{
if ((this.connection != null) && (this.connection.State == ConnectionState.Open))
{
this.connection.Close();
}
this.connection = null;
}
}
#endregion
#region "Parameter Related"
private void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters != null) && (parameterValues != null))
{
bool flag1 = commandParameters[0].ParameterName == "@RETURN_VALUE";
if (commandParameters.Length != parameterValues.Length)
{
if (!flag1)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
if ((commandParameters.Length - parameterValues.Length) != 1)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
}
if (flag1)
{
int num1 = 1;
int num2 = commandParameters.Length;
while (num1 < num2)
{
commandParameters[num1].Value = parameterValues[num1 - 1];
num1++;
}
}
else
{
int num3 = 0;
int num4 = commandParameters.Length;
while (num3 < num4)
{
commandParameters[num3].Value = parameterValues[num3];
num3++;
}
}
}
}
private void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
foreach (SqlParameter parameter1 in commandParameters)
{
if ((parameter1.Direction == ParameterDirection.InputOutput) && (parameter1.Value == null))
{
parameter1.Value = DBNull.Value;
}
command.Parameters.Add(parameter1);
}
}
#endregion
#region "Transaction Related"
public bool BeginTransaction()
{
bool flag1;
try
{
this.GetCommand("Start Transaction;").ExecuteNonQuery();
this.isBeginTransaction = true;
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
public bool CommitTransaction()
{
bool flag1;
try
{
this.GetCommand("Commit;").ExecuteNonQuery();
this.CloseConnection();
this.isBeginTransaction = false;
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
public bool RollbackTransaction()
{
bool flag1;
try
{
this.GetCommand("Rollback;").ExecuteNonQuery();
this.CloseConnection();
this.isBeginTransaction = false;
flag1 = true;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return flag1;
}
#endregion
#region "Execute SQL and SP"
public int Execute(string StrTSQL)
{
int num2;
try
{
int num1 = this.GetCommand(StrTSQL).ExecuteNonQuery();
num2 = num1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return num2;
}
public DataSet ExecuteSP(string spName)
{
DataSet set2;
try
{
this.OpenConnection();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
DataSet set1 = this.ExecuteSP(spName, null);
if (!this.isBeginTransaction)
{
this.CloseConnection();
}
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSP(SqlTransaction transaction, string spName)
{
DataSet set2;
try
{
DataSet set1 = this.ExecuteSP(transaction, spName, null);
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSP(string spName, params SqlParameter[] commandParameters)
{
DataSet set2;
try
{
this.OpenConnection();
SqlCommand command1 = new SqlCommand();
this.PrepareCommand(command1, null, spName, commandParameters);
SqlDataAdapter adapter1 = new SqlDataAdapter(command1);
DataSet set1 = new DataSet();
adapter1.Fill(set1);
command1.Parameters.Clear();
set2 = set1;
this.CloseConnection();
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSP(SqlTransaction transaction, string spName, params object[] parameterValues)
{
DataSet set2;
try
{
this.connection = transaction.Connection;
DataSet set1 = null;
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(transaction.Connection, spName, false);
this.AssignParameterValues(parameterArray1, parameterValues);
set1 = this.ExecuteSP(transaction, spName, parameterArray1);
}
else
{
set1 = this.ExecuteSP(transaction, spName);
}
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet ExecuteSPWithDataSet(string spName, params object[] parameterValues)
{
DataSet set1 = null;
if ((parameterValues != null) && (parameterValues.Length > 0))
{
this.OpenConnection();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(this.connection, spName, true);
this.AssignParameterValues(parameterArray1, parameterValues);
return this.ExecuteSP(spName, parameterArray1);
}
this.ExecuteSP(spName);
if (!this.isBeginTransaction)
{
this.CloseConnection();
}
return set1;
}
public int ExecuteSPWithReturn(string spName, params object[] parameterValues)
{
int num1 = 0;
if ((parameterValues != null) && (parameterValues.Length > 0))
{
this.OpenConnection();
this.errorCode = CDataAccess.DataAccessErrors.Successful;
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(this.connection, spName, true);
this.AssignParameterValues(parameterArray1, parameterValues);
this.ExecuteSP(spName, parameterArray1);
num1 = (int)parameterArray1[0].Value;
}
else
{
this.ExecuteSP(spName);
}
if (!this.isBeginTransaction)
{
this.CloseConnection();
}
return num1;
}
public DataTable ExecuteSPWithReturnDataTable(String spName, params SqlParameter[] CommandParameter)
{
DataTable tmpDataTable = new DataTable();
//try
//{
this.OpenConnection();
SqlCommand sqlCommand = new SqlCommand();
this.PrepareCommand(sqlCommand, null, spName, CommandParameter);
//this.PrepareCommand(sqlCommand, null, spName, CommandParameter);
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter(sqlCommand);
SqlDataAdapter.Fill(tmpDataTable).ToString();
this.CloseConnection();
//}
//catch (SqlException exception1)
//{
// //(exception1.Message);
//}
//Catch exception2 As Exception
// Throw New Exception(exception2.Message)
//End Try
return tmpDataTable;
}
#endregion
#region "Display Message"
public void DisplayMessage(ref Panel pPanel, string sText)
{
Label lblText = new Label();
lblText.Text = sText;
lblText.CssClass = "Red";
lblText.ForeColor = System.Drawing.Color.Red;
lblText.Font.Size = 7;
lblText.Font.Bold = true;
pPanel.Controls.Add(lblText);
}
#endregion
#region "Destructor"
~CDataAccess()
{
if (this.isBeginTransaction)
{
throw new Exception("Begin transaction without Rollback or Commit. Please check your code");
}
}
#endregion
#region "Command Related"
public SqlCommand GetCommand(string StrTSQL)
{
SqlCommand command2;
try
{
SqlCommand command1 = new SqlCommand();
this.OpenConnection();
command1.Connection = this.connection;
command1.CommandText = StrTSQL;
command2 = command1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return command2;
}
public void ExecuteQuery(String strSql)
{
this.OpenConnection();
SqlCommand tmpCommand = new SqlCommand(strSql, this.connection);
tmpCommand.ExecuteNonQuery();
this.CloseConnection();
}
public int ExecuteQuery(String strSql,string dummy)
{
this.OpenConnection();
SqlCommand tmpCommand = new SqlCommand(strSql, this.connection);
int NoofRowsAffected = tmpCommand.ExecuteNonQuery();
this.CloseConnection();
return NoofRowsAffected;
}
private void PrepareCommand(SqlCommand command, SqlTransaction transaction, string commandText, SqlParameter[] commandParameters)
{
//this.PrepareCommand(command1, null, spName, commandParameters);
command.Connection = this.connection;
command.CommandText = commandText;
if (transaction != null)
{
command.Transaction = transaction;
}
command.CommandType = CommandType.StoredProcedure;
if (commandParameters != null)
{
this.AttachParameters(command, commandParameters);
}
}
#endregion
#region "GetDataAdapter"
public SqlDataAdapter GetDataAdapter(string StrSQL)
{
SqlDataAdapter adapter2;
try
{
SqlDataAdapter adapter1 = new SqlDataAdapter(StrSQL, this.connectionString);
adapter2 = adapter1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return adapter2;
}
#endregion
#region "GetDataReader"
public SqlDataReader GetDataReader(string StrSQL)
{
SqlDataReader reader2;
try
{
SqlDataReader reader1 = null;
reader1 = this.GetCommand(StrSQL).ExecuteReader(CommandBehavior.Default);
reader2 = reader1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return reader2;
}
public SqlDataReader GetDataReaderSP(string spName, params SqlParameter[] commandParameters)
{
SqlCommand command1 = new SqlCommand();
this.PrepareCommand(command1, null, spName, commandParameters);
SqlDataAdapter adapter1 = new SqlDataAdapter(command1);
SqlDataReader reader1 = command1.ExecuteReader(CommandBehavior.Default);
command1.Parameters.Clear();
return reader1;
}
public SqlDataReader GetDataReaderSP(string spName, params object[] parameterValues)
{
if ((parameterValues != null) && (parameterValues.Length > 0))
{
this.errorCode = CDataAccess.DataAccessErrors.Successful;
SqlParameter[] parameterArray1 = CDataAccess.SqlParameterCache.GetSpParameterSet(this.connection, spName, false);
this.AssignParameterValues(parameterArray1, parameterValues);
return this.GetDataReaderSP(spName, parameterArray1);
}
return this.GetDataReaderSP(spName, null);
}
#endregion
#region "GetDataSet"
public DataSet GetDataSet(string StrSQL, string DateSetName)
{
DataSet set2;
try
{
DataSet set1 = new DataSet();
this.OpenConnection();
new SqlDataAdapter(StrSQL, this.connectionString).Fill(set1, DateSetName);
this.CloseConnection();
set2 = set1;
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return set2;
}
public DataSet GetDataSet(string strSQL, string strTable, ref SqlDataAdapter m_DataAdapter, ref DataTable m_DataTable, ref DataView m_DataView)
{
DataSet dsDataSet2 = null;
try
{
this.OpenConnection();
DataSet Set1 = new DataSet();
SqlCommand cmCommand;
cmCommand = new SqlCommand(strSQL, connection);
daDataAdapter = new SqlDataAdapter(cmCommand);
SqlCommandBuilder cbCommandBuilder = new SqlCommandBuilder(daDataAdapter);
//Build the Data Operation SQL if flag is True
cbCommandBuilder.GetUpdateCommand();
DataSet dsDataSet = new DataSet();
m_DataAdapter.Fill(dsDataSet, strTable);
dsDataSet2.Merge(dsDataSet);
dtDataTable = dsDataSet.Tables[0];
dvDataView = dtDataTable.DefaultView;
dvDataView.AllowNew = false;
this.CloseConnection();
}
catch (SqlException exception1)
{
throw new Exception(exception1.Message);
}
catch (Exception exception2)
{
throw new Exception(exception2.Message);
}
return dsDataSet2;
}
public DataSet GetDataSet(string strSQL, string strTable, ref SqlDataAdapter m_DataAdapter, ref DataSet m_DataSet)
{
this.OpenConnection();
DataSet tmpDataSet = new DataSet();
SqlCommand m_Command;
m_Command = new SqlCommand(strSQL, this.connection);
m_DataAdapter = new SqlDataAdapter(m_Command);
SqlCommandBuilder m_CommandBuilder = new SqlCommandBuilder(m_DataAdapter);
cbCommandBuilder.GetUpdateCommand();
m_DataAdapter.Fill(m_DataSet, strTable);
m_DataSet.Merge(tmpDataSet);
this.CloseConnection();
return m_DataSet;
}
public DataSet GetDataSet(string strSQL, string strTable, ref DataSet m_DataSet)
{
this.OpenConnection();
SqlDataAdapter m_SQL_DataAdapter;
SqlCommand m_SQL_Command;
DataSet tmpDataSet = new DataSet();
m_SQL_Command = new SqlCommand(strSQL, this.connection);
m_SQL_DataAdapter = new SqlDataAdapter(m_SQL_Command);
m_SQL_DataAdapter.Fill(tmpDataSet, strTable);
m_DataSet.Merge(tmpDataSet);
this.CloseConnection();
return m_DataSet;
}
public DataSet GetDataSet(string strSQL, string strTable, ref DataSet m_DataSet, int BuildCommand)
{
this.OpenConnection();
DataSet tmpDataSet = new DataSet();
SqlCommand cmCommand;
cmCommand = new SqlCommand(strSQL, this.connection);
daDataAdapter = new SqlDataAdapter(cmCommand);
cbCommandBuilder = new SqlCommandBuilder(daDataAdapter);
cbCommandBuilder.GetUpdateCommand();
daDataAdapter.Fill(m_DataSet, strTable);
m_DataSet.Merge(tmpDataSet);
this.CloseConnection();
return m_DataSet;
}
#endregion
#region "GetDataTable"
public DataTable GetDataTable(string strSQL)
{
this.OpenConnection();
SqlCommand m_Command;
m_Command = new SqlCommand(strSQL, this.connection);
SqlDataAdapter tmpDataAdapter;
tmpDataAdapter = new SqlDataAdapter(m_Command);
DataTable tmpDataTable = new DataTable();
tmpDataAdapter.Fill(tmpDataTable);
this.CloseConnection();
return tmpDataTable;
}
#endregion
#region "FillCombo"
public void FillCombo(ref DropDownList Combo, string strSQL, bool AddAllOption, bool None)
{
DataTable dtTable = GetDataTable(strSQL);
if ((None))
{
DataRow drDataRow;
drDataRow = dtTable.NewRow();
drDataRow[0] = -1;
drDataRow[1] = "";
dtTable.Rows.Add(drDataRow);
}
if ((AddAllOption))
{
DataRow drDataRow;
drDataRow = dtTable.NewRow();
drDataRow[0] = 0;
drDataRow[1] = "_ALL_";
dtTable.Rows.Add(drDataRow);
}
{
DataView DataView = dtTable.DefaultView;
DataView.Sort = dtTable.Columns[1].ColumnName;
Combo.DataSource = DataView;
Combo.DataTextField = dtTable.Columns[1].ColumnName;
Combo.DataValueField = dtTable.Columns[0].ColumnName;
Combo.DataBind();
}
}
#endregion
#region "SqlParameterCache Class"
public sealed class SqlParameterCache
{
// Methods
static SqlParameterCache()
{
CDataAccess.SqlParameterCache.paramCache = Hashtable.Synchronized(new Hashtable());
}
private SqlParameterCache()
{
}
private static void CacheParameterSet(string connectionString, string spName, params SqlParameter[] commandParameters)
{
string text1 = connectionString + ":" + spName;
CDataAccess.SqlParameterCache.paramCache[text1] = commandParameters;
}
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] parameterArray1 = new SqlParameter[originalParameters.Length];
int num1 = 0;
int num2 = originalParameters.Length;
while (num1 < num2)
{
parameterArray1[num1] = (SqlParameter)((ICloneable)originalParameters[num1]).Clone();
num1++;
}
return parameterArray1;
}
private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
using (SqlCommand command1 = new SqlCommand(spName, connection))
{
command1.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(command1);
if (!includeReturnValueParameter)
{
command1.Parameters.RemoveAt(0);
}
SqlParameter[] parameterArray1 = new SqlParameter[command1.Parameters.Count];
command1.Parameters.CopyTo(parameterArray1, 0);
return parameterArray1;
}
}
private static SqlParameter[] GetCachedParameterSet(string connectionString, string spName)
{
string text1 = connectionString + ":" + spName;
SqlParameter[] parameterArray1 = (SqlParameter[])CDataAccess.SqlParameterCache.paramCache[text1];
if (parameterArray1 == null)
{
return null;
}
return CDataAccess.SqlParameterCache.CloneParameters(parameterArray1);
}
public static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
{
return CDataAccess.SqlParameterCache.GetSpParameterSet(connection, spName, false);
}
public static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
{
string text1 = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");
SqlParameter[] parameterArray1 = (SqlParameter[])CDataAccess.SqlParameterCache.paramCache[text1];
if (parameterArray1 == null)
{
object obj1;
CDataAccess.SqlParameterCache.paramCache[text1] = obj1 = CDataAccess.SqlParameterCache.DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
parameterArray1 = (SqlParameter[])obj1;
}
return CDataAccess.SqlParameterCache.CloneParameters(parameterArray1);
}
// Fields
private static Hashtable paramCache;
}
#endregion
//Open file into a filestream and
//read data in a byte array.
public byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open,
FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to
//supply number of bytes to read from file.
//In this case we want to read entire file.
//So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
#region "InitializeGrid"
//public void InitializeGrid(ref UltraWebGrid Grid)
//{
// // Grid.JavaScriptFileName = "../../infragistics/scripts/ig_WebGrid.js";
// //Grid.JavaScriptFileNameCommon = "../../infragistics/scripts/ig_csom.js";
// Grid.DisplayLayout.AllowColSizingDefault = AllowSizing.Free;
// Grid.DisplayLayout.AllowColumnMovingDefault = Infragistics.WebUI.UltraWebGrid.AllowColumnMoving.OnServer;
// Grid.DisplayLayout.AllowSortingDefault = AllowSorting.OnClient;
// Grid.DisplayLayout.CellClickActionDefault = CellClickAction.RowSelect;
// Grid.DisplayLayout.CellPaddingDefault = 1;
// Grid.DisplayLayout.ColHeadersVisibleDefault = ShowMarginInfo.Yes;
// Grid.DisplayLayout.HeaderClickActionDefault = HeaderClickAction.SortSingle;
// //Header Style
// Grid.DisplayLayout.HeaderStyleDefault.CssClass = "GridHeader";
// Grid.DisplayLayout.HeaderStyleDefault.Font.Bold = true;
// //Sort
// Grid.DisplayLayout.AllowSortingDefault = Infragistics.WebUI.UltraWebGrid.AllowSorting.OnClient;
// Grid.DisplayLayout.HeaderClickActionDefault = Infragistics.WebUI.UltraWebGrid.HeaderClickAction.SortSingle;
// Grid.DisplayLayout.NoDataMessage = "No Records Found";
// Grid.DisplayLayout.NullTextDefault = "";
// Grid.DisplayLayout.RowStyleDefault.CssClass = "GridRowEven";
// Grid.DisplayLayout.RowAlternateStyleDefault.CssClass = "GridRowOdd";
// //Grid.DisplayLayout.RowAlternateStyleDefault.BackColor = Drawing.Color.FromArgb(255, 255, 215);
// //Grid.DisplayLayout.RowAlternateStyleDefault.BackColor = Gray;
// //Padding
// Grid.DisplayLayout.CellPaddingDefault = 3;
// Grid.DisplayLayout.RowAlternateStyleDefault.TextOverflow = TextOverflow.Ellipsis;
// Grid.DisplayLayout.RowHeightDefault = 25;
// Grid.DisplayLayout.RowSelectorsDefault = RowSelectors.No;
// Grid.DisplayLayout.RowSizingDefault = AllowSizing.Fixed;
// Grid.DisplayLayout.ScrollBar = ScrollBar.Auto;
// Grid.DisplayLayout.ScrollBarView = ScrollBarView.Both;
// Grid.DisplayLayout.SelectedRowStyleDefault.CssClass = "GridSelectedRow";
// Grid.DisplayLayout.SelectTypeCellDefault = SelectType.None;
// Grid.DisplayLayout.SelectTypeColDefault = SelectType.None;
// Grid.DisplayLayout.SelectTypeRowDefault = SelectType.Single;
// Grid.DisplayLayout.StationaryMargins = StationaryMargins.No;
// Grid.DisplayLayout.TabDirection = TabDirection.LeftToRight;
// Grid.DisplayLayout.ViewType = Infragistics.WebUI.UltraWebGrid.ViewType.Flat;
// Grid.CssClass = "Grid";
// Grid.BorderStyle = BorderStyle.Solid;
//}
#endregion
public string VoucherNumber(String strHead)
{
String strSql;
String strCode;
DataTable tmpDataTable;
strSql = "SELECT * FROM tblAutoNumber ";
strSql += "WHERE Head = '" + strHead + "'";
tmpDataTable = GetDataTable(strSql);
strCode = tmpDataTable.Rows[0]["Prefix"] + "/";
strCode += DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "/";
strCode += Convert.ToString(Convert.ToInt32(tmpDataTable.Rows[0]["Number"]) + 1);
if (Convert.ToString(tmpDataTable.Rows[0]["SufixCheck"]) == "True")
{
strCode += "/" + tmpDataTable.Rows[0]["Sufix"];
}
return (strCode);
}
//public void AddValueListItemToGrid(ref Infragistics.WebUI.UltraWebGrid.UltraWebGrid Grid, String strSQL, int ColumnIndex) //int BandIndex = 0
//{
// Int32 iCount;
// Infragistics.WebUI.UltraWebGrid.ValueList vValue = new ValueList();
// DataTable tmpDataTable = GetDataTable(strSQL);
// //vValue = Grid.DisplayLayout.ValueLists.Add
// for (iCount = 0; iCount <= tmpDataTable.Rows.Count - 1; iCount++)
// {
// //vValue.ValueListItems.Add(tmpDataTable.Rows[iCount][0],(tmpDataTable.Rows[iCount][1])=null, "", tmpDataTable.Rows[iCount][1]);
// vValue.ValueListItems.Add(tmpDataTable.Rows[iCount][1]);
// }
// vValue.DisplayStyle = Infragistics.WebUI.UltraWebGrid.ValueListDisplayStyle.DisplayText;
// //vValue.SortStyle = Infragistics.Win.ValueListSortStyle.Ascending
// Grid.DisplayLayout.Bands[0].Columns[ColumnIndex].ValueList = vValue;
//}
}
#endregion
}
EXPORT TO EXCEL
Public Sub ExportToExcel(ByVal objDT As DataTable)
Dim Excel As Object = CreateObject("Excel.Application")
Dim strFilename As String
Dim intCol, intRow As Integer
Dim strPath As String = "c:\"
If Excel Is Nothing Then
MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
Return
End If
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
'.cells(1, 1).value = "Heading" 'Heading of the excel file
.cells(1, 1).EntireRow.Font.Bold = True
Dim intI As Integer = 1
For intCol = 1 To objDT.Columns.Count - 1
.cells(2, intI).value = objDT.Columns(intCol).ColumnName
.cells(2, intI).EntireRow.Font.Bold = True
intI += 1
Next
intI = 3
Dim intK As Integer = 1
For intCol = 1 To objDT.Columns.Count - 1
intI = 3
For intRow = 0 To objDT.Rows.Count - 1
.Cells(intI, intK).Value = objDT.Rows(intRow).ItemArray(intCol)
intI += 1
Next
intK += 1
Next
If Mid$(strPath, strPath.Length, 1) <> "\" Then
strPath = strPath & "\"
End If
Dim filename As String = System.DateTime.Now.ToString("MM/dd/yyyy")
filename = filename.Replace("/", "_") & System.DateTime.Now.Millisecond.ToString()
strFilename = strPath & filename
.ActiveCell.Worksheet.SaveAs(strFilename)
End With
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Excel = Nothing
MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'", MsgBoxStyle.Information)
s = ""
s = strFilename + ".xls"
Catch ex As Exception
'MsgBox(ex.Message)
End Try
' The excel is created and opened for insert value. We most close this excel using this system
Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each i As Process In pro
i.Kill()
Next
End Sub
Dim Excel As Object = CreateObject("Excel.Application")
Dim strFilename As String
Dim intCol, intRow As Integer
Dim strPath As String = "c:\"
If Excel Is Nothing Then
MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
Return
End If
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
'.cells(1, 1).value = "Heading" 'Heading of the excel file
.cells(1, 1).EntireRow.Font.Bold = True
Dim intI As Integer = 1
For intCol = 1 To objDT.Columns.Count - 1
.cells(2, intI).value = objDT.Columns(intCol).ColumnName
.cells(2, intI).EntireRow.Font.Bold = True
intI += 1
Next
intI = 3
Dim intK As Integer = 1
For intCol = 1 To objDT.Columns.Count - 1
intI = 3
For intRow = 0 To objDT.Rows.Count - 1
.Cells(intI, intK).Value = objDT.Rows(intRow).ItemArray(intCol)
intI += 1
Next
intK += 1
Next
If Mid$(strPath, strPath.Length, 1) <> "\" Then
strPath = strPath & "\"
End If
Dim filename As String = System.DateTime.Now.ToString("MM/dd/yyyy")
filename = filename.Replace("/", "_") & System.DateTime.Now.Millisecond.ToString()
strFilename = strPath & filename
.ActiveCell.Worksheet.SaveAs(strFilename)
End With
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Excel = Nothing
MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'", MsgBoxStyle.Information)
s = ""
s = strFilename + ".xls"
Catch ex As Exception
'MsgBox(ex.Message)
End Try
' The excel is created and opened for insert value. We most close this excel using this system
Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each i As Process In pro
i.Kill()
Next
End Sub
Thursday, July 7, 2011
EMAIL VALIDATION IN ASP.NET
<
asp:RegularExpressionValidator
ValidationExpression
=
"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
ID
=
"rxpEmail"
runat
=
"server"
ErrorMessage
=
"Email Address is not valid"
Text
=
"*"
Display
=
"Static"
ControlToValidate
=
"txtEmail"
>asp:RegularExpressionValidator
>
Tuesday, July 5, 2011
GET PROSSESOR ID,MOTHERBOARD ID IN VB.NET
Firts add system.management dll in project
then
Imports System
Imports System.Management
Friend Function GetProcessorId() As String
Dim strProcessorId As String = String.Empty
Dim query As New SelectQuery("Win32_processor")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
For Each info In search.Get()
strProcessorId = info("processorId").ToString()
Next
Return strProcessorId + Format(Int(Rnd() * 10000), "0000")
End Function
===========MOTHER BOARD ID=================
Friend Function GetMotherBoardID() As String
Dim strMotherBoardID As String = String.Empty
Dim query As New SelectQuery("Win32_BaseBoard")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
For Each info In search.Get()
strMotherBoardID = info("SerialNumber").ToString()
Next
Return strMotherBoardID
End Function
then
Imports System
Imports System.Management
Friend Function GetProcessorId() As String
Dim strProcessorId As String = String.Empty
Dim query As New SelectQuery("Win32_processor")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
For Each info In search.Get()
strProcessorId = info("processorId").ToString()
Next
Return strProcessorId + Format(Int(Rnd() * 10000), "0000")
End Function
===========MOTHER BOARD ID=================
Friend Function GetMotherBoardID() As String
Dim strMotherBoardID As String = String.Empty
Dim query As New SelectQuery("Win32_BaseBoard")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
For Each info In search.Get()
strMotherBoardID = info("SerialNumber").ToString()
Next
Return strMotherBoardID
End Function
CHART CONTROL IN VB.NET
Imports System.Windows.Forms.DataVisualization.Charting
Public Class frmChart
Dim dtTest As New DataTable
Dim iRowCount As Integer = 0
Dim iPageCounter As Integer = 0
Dim bIschart As Boolean = False
Private Sub frmChart_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
dtTest.Columns.Clear()
dtTest.Rows.Clear()
dtTest.Columns.Add("Name")
dtTest.Columns.Add("Marks")
'dttest = modCons.dtChart.Copy()
iRowCount = modCons.dtChart.Rows.Count
If (iRowCount > 40) Then
For i As Integer = 0 To 39
dtTest.Rows.Add(modCons.dtChart.Rows(i)("Name").ToString(), modCons.dtChart.Rows(i)("Marks").ToString())
Next
If (bIschart = False) Then
Chart1.Series.Add("Name")
With Chart1.Series(0)
' .Name = "Candidate Graph"
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Magenta
.BackSecondaryColor = Color.Purple
.IsValueShownAsLabel = True
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Purple
.Points.DataBind(dtTest.DefaultView, "Name", "Name", Nothing)
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.Series(1)
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Aqua
.BackSecondaryColor = Color.Blue
.IsValueShownAsLabel = True
.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Box
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Blue
.Points.DataBindY(dtTest.DefaultView, "Marks")
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.ChartAreas(0)
.AxisX.Interval = 1
.AxisX.LabelStyle.Angle = -90
.AxisX.Title = "Name"
.AxisY.Title = "Marks"
End With
Dim strip As New StripLine
strip.BackColor = Color.LightSalmon
strip.IntervalOffset = 50
strip.StripWidth = 2
Chart1.ChartAreas(0).AxisY.StripLines.Add(strip)
' Chart1.Dispose()
bIschart = True
End If
Else
For i As Integer = 0 To modCons.dtChart.Rows.Count - 1
dtTest.Rows.Add(modCons.dtChart.Rows(i)("Name").ToString(), modCons.dtChart.Rows(i)("Marks").ToString())
Next
If (bIschart = False) Then
Chart1.Series.Add("Name")
With Chart1.Series(0)
' .Name = "Candidate Graph"
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Magenta
.BackSecondaryColor = Color.Purple
.IsValueShownAsLabel = True
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Purple
.Points.DataBind(dtTest.DefaultView, "Name", "Name", Nothing)
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.Series(1)
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Aqua
.BackSecondaryColor = Color.Blue
.IsValueShownAsLabel = True
.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Box
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Blue
.Points.DataBindY(dtTest.DefaultView, "Marks")
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.ChartAreas(0)
.AxisX.Interval = 1
.AxisX.LabelStyle.Angle = -90
.AxisX.Title = "Name"
.AxisY.Title = "Marks"
End With
Dim strip As New StripLine
strip.BackColor = Color.LightSalmon
strip.IntervalOffset = 50
strip.StripWidth = 2
Chart1.ChartAreas(0).AxisY.StripLines.Add(strip)
' Chart1.Dispose()
bIschart = True
btnFwd.Enabled = False
btnPrv.Enabled = False
End If
End If
End Sub
Private Sub btnPrv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrv.Click
' Chart1.Dispose()
iPageCounter -= 1
dtTest.Columns.Clear()
dtTest.Rows.Clear()
dtTest.Columns.Add("Name")
dtTest.Columns.Add("Marks")
Dim iEndCounter As Integer = (40 * iPageCounter) + 40
If (iEndCounter > modCons.dtChart.Rows.Count - 1) Then
iEndCounter = modCons.dtChart.Rows.Count - 1
btnFwd.Enabled = False
Else
btnFwd.Enabled = True
End If
Dim j As Integer = iRowCount - 40
For k As Integer = (40 * iPageCounter) + 1 To iEndCounter
dtTest.Rows.Add(modCons.dtChart.Rows(k)("Name").ToString(), modCons.dtChart.Rows(k)("Marks").ToString())
Next
If (bIschart = False) Then
Chart1.Series.Add("Name")
With Chart1.Series(0)
.Name = "Candidate Graph"
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Magenta
.BackSecondaryColor = Color.Purple
.IsValueShownAsLabel = True
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Purple
.Points.DataBind(dtTest.DefaultView, "Name", "Name", Nothing)
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.Series(1)
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Aqua
.BackSecondaryColor = Color.Blue
.IsValueShownAsLabel = True
.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Box
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Blue
.Points.DataBindY(dtTest.DefaultView, "Marks")
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.ChartAreas(0)
.AxisX.Interval = 1
.AxisX.LabelStyle.Angle = -90
.AxisX.Title = "Name"
.AxisY.Title = "Marks"
End With
Dim strip As New StripLine
strip.BackColor = Color.LightSalmon
strip.IntervalOffset = 50
strip.StripWidth = 2
Chart1.ChartAreas(0).AxisY.StripLines.Add(strip)
' Chart1.Dispose()
Else
With Chart1.Series(0)
.Name = "Candidate Graph"
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Magenta
.BackSecondaryColor = Color.Purple
.IsValueShownAsLabel = True
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Purple
.Points.DataBind(dtTest.DefaultView, "Name", "Name", Nothing)
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.Series(1)
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Aqua
.BackSecondaryColor = Color.Blue
.IsValueShownAsLabel = True
.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Box
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Blue
.Points.DataBindY(dtTest.DefaultView, "Marks")
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.ChartAreas(0)
.AxisX.Interval = 1
.AxisX.LabelStyle.Angle = -90
.AxisX.Title = "Name"
.AxisY.Title = "Marks"
End With
Dim strip As New StripLine
strip.BackColor = Color.LightSalmon
strip.IntervalOffset = 50
strip.StripWidth = 2
Chart1.ChartAreas(0).AxisY.StripLines.Add(strip)
If (iPageCounter = 0) Then
btnPrv.Enabled = False
Else
btnPrv.Enabled = True
End If
End If
End Sub
Private Sub btnFwd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFwd.Click
' Chart1.Dispose()
iPageCounter += 1
dtTest.Columns.Clear()
dtTest.Rows.Clear()
dtTest.Columns.Add("Name")
dtTest.Columns.Add("Marks")
Dim iEndCounter As Integer = (40 * iPageCounter) + 40
If (iEndCounter > modCons.dtChart.Rows.Count - 1) Then
iEndCounter = modCons.dtChart.Rows.Count - 1
btnFwd.Enabled = False
Else
btnFwd.Enabled = True
End If
Dim j As Integer = iRowCount - 40
For k As Integer = (40 * iPageCounter) + 1 To iEndCounter
dtTest.Rows.Add(modCons.dtChart.Rows(k)("Name").ToString(), modCons.dtChart.Rows(k)("Marks").ToString())
Next
If (bIschart = False) Then
Chart1.Series.Add("Name")
With Chart1.Series(0)
.Name = "Candidate Graph"
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Magenta
.BackSecondaryColor = Color.Purple
.IsValueShownAsLabel = True
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Purple
.Points.DataBind(dtTest.DefaultView, "Name", "Name", Nothing)
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.Series(1)
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Aqua
.BackSecondaryColor = Color.Blue
.IsValueShownAsLabel = True
.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Box
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Blue
.Points.DataBindY(dtTest.DefaultView, "Marks")
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.ChartAreas(0)
.AxisX.Interval = 1
.AxisX.LabelStyle.Angle = -90
.AxisX.Title = "Name"
.AxisY.Title = "Marks"
End With
Dim strip As New StripLine
strip.BackColor = Color.LightSalmon
strip.IntervalOffset = 50
strip.StripWidth = 2
Chart1.ChartAreas(0).AxisY.StripLines.Add(strip)
' Chart1.Dispose()
Else
With Chart1.Series(0)
.Name = "Candidate Graph"
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Magenta
.BackSecondaryColor = Color.Purple
.IsValueShownAsLabel = True
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Purple
.Points.DataBind(dtTest.DefaultView, "Name", "Name", Nothing)
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.Series(1)
.Font = New Font("Arial", 8, FontStyle.Italic)
.BackGradientStyle = GradientStyle.TopBottom
.Color = Color.Aqua
.BackSecondaryColor = Color.Blue
.IsValueShownAsLabel = True
.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Box
.LabelBackColor = Color.Transparent
.LabelForeColor = Color.Blue
.Points.DataBindY(dtTest.DefaultView, "Marks")
.CustomProperties = "DrawingStyle = Cylinder ,PixelPointWidth = 26"
End With
With Chart1.ChartAreas(0)
.AxisX.Interval = 1
.AxisX.LabelStyle.Angle = -90
.AxisX.Title = "Name"
.AxisY.Title = "Marks"
End With
Dim strip As New StripLine
strip.BackColor = Color.LightSalmon
strip.IntervalOffset = 50
strip.StripWidth = 2
Chart1.ChartAreas(0).AxisY.StripLines.Add(strip)
If (iPageCounter = 0) Then
btnPrv.Enabled = False
Else
btnPrv.Enabled = True
End If
End If
End Sub
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
PrintDocument1.Print()
End Sub
End Class
Thursday, June 16, 2011
Add CheckBox DataGridView Header
Add this class
________________________
Public Class DGVColumnHeader
Inherits DataGridViewColumnHeaderCell
Private CheckBoxRegion As Rectangle
Private m_checkAll As Boolean = False
Protected Overrides Sub Paint(ByVal graphics As Graphics, ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, ByVal rowIndex As Integer, ByVal dataGridViewElementState As DataGridViewElementStates, ByVal value As Object, _
ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As DataGridViewCellStyle, ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, ByVal paintParts As DataGridViewPaintParts)
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, _
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
graphics.FillRectangle(New SolidBrush(cellStyle.BackColor), cellBounds)
CheckBoxRegion = New Rectangle(cellBounds.Location.X + 1, cellBounds.Location.Y + 2, 25, cellBounds.Size.Height - 4)
If Me.m_checkAll Then
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked)
Else
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal)
End If
Dim normalRegion As New Rectangle(cellBounds.Location.X + 1 + 25, cellBounds.Location.Y, cellBounds.Size.Width - 26, cellBounds.Size.Height)
graphics.DrawString(value.ToString(), cellStyle.Font, New SolidBrush(cellStyle.ForeColor), normalRegion)
End Sub
Protected Overrides Sub OnMouseClick(ByVal e As DataGridViewCellMouseEventArgs)
'Convert the CheckBoxRegion
Dim rec As New Rectangle(New Point(0, 0), Me.CheckBoxRegion.Size)
Me.m_checkAll = Not Me.m_checkAll
If rec.Contains(e.Location) Then
Me.DataGridView.Invalidate()
End If
MyBase.OnMouseClick(e)
End Sub
Public Property CheckAll() As Boolean
Get
Return Me.m_checkAll
End Get
Set(ByVal value As Boolean)
Me.m_checkAll = value
End Set
End Property
End Class
_____________________
On Your code write
_________________
For i As Integer = 0 To grdViev.Columns.Count - 1
Dim DGV As New DGVColumnHeader
grdViev.Columns(i).HeaderCell = DGV
Next
________________________
Public Class DGVColumnHeader
Inherits DataGridViewColumnHeaderCell
Private CheckBoxRegion As Rectangle
Private m_checkAll As Boolean = False
Protected Overrides Sub Paint(ByVal graphics As Graphics, ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, ByVal rowIndex As Integer, ByVal dataGridViewElementState As DataGridViewElementStates, ByVal value As Object, _
ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As DataGridViewCellStyle, ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, ByVal paintParts As DataGridViewPaintParts)
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, _
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
graphics.FillRectangle(New SolidBrush(cellStyle.BackColor), cellBounds)
CheckBoxRegion = New Rectangle(cellBounds.Location.X + 1, cellBounds.Location.Y + 2, 25, cellBounds.Size.Height - 4)
If Me.m_checkAll Then
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked)
Else
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal)
End If
Dim normalRegion As New Rectangle(cellBounds.Location.X + 1 + 25, cellBounds.Location.Y, cellBounds.Size.Width - 26, cellBounds.Size.Height)
graphics.DrawString(value.ToString(), cellStyle.Font, New SolidBrush(cellStyle.ForeColor), normalRegion)
End Sub
Protected Overrides Sub OnMouseClick(ByVal e As DataGridViewCellMouseEventArgs)
'Convert the CheckBoxRegion
Dim rec As New Rectangle(New Point(0, 0), Me.CheckBoxRegion.Size)
Me.m_checkAll = Not Me.m_checkAll
If rec.Contains(e.Location) Then
Me.DataGridView.Invalidate()
End If
MyBase.OnMouseClick(e)
End Sub
Public Property CheckAll() As Boolean
Get
Return Me.m_checkAll
End Get
Set(ByVal value As Boolean)
Me.m_checkAll = value
End Set
End Property
End Class
_____________________
On Your code write
_________________
For i As Integer = 0 To grdViev.Columns.Count - 1
Dim DGV As New DGVColumnHeader
grdViev.Columns(i).HeaderCell = DGV
Next
Wednesday, June 15, 2011
Open Word document in vb.net( desktop application )
Place your doc file under bin/debug/
Paste the following code
Dim objword As Object
objword = CreateObject("Word.Application")
objword.Visible = True
objword.Documents.Open(Application.StartupPath + "/help.doc")
Paste the following code
Dim objword As Object
objword = CreateObject("Word.Application")
objword.Visible = True
objword.Documents.Open(Application.StartupPath + "/help.doc")
Saturday, June 11, 2011
Maintaining State of CheckBoxes While Paging in a GridView Control
CREATE THIS AS GLOBAL
public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex";
private void RePopulateCheckBoxes()
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;
IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
if (SelectedCustomersIndex != null)
{
if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
{
chkBox.Checked = true;
}
}
}
}
private List SelectedCustomersIndex
{
get
{
if (ViewState[SELECTED_CUSTOMERS_INDEX] == null)
{
ViewState[SELECTED_CUSTOMERS_INDEX] = new List();
}
return (List)ViewState[SELECTED_CUSTOMERS_INDEX];
}
}
private void RemoveRowIndex(int index)
{
SelectedCustomersIndex.Remove(index);
}
private void PersistRowIndex(int index)
{
if (!SelectedCustomersIndex.Exists(i => i == index))
{
SelectedCustomersIndex.Add(index);
}
}
WRITE THIS IN GRIDVIEW PAGEINDEXCHANGING
protected void grdInvitee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;
IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
if (chkBox.Checked)
{
PersistRowIndex(container.DataItemIndex);
}
else
{
RemoveRowIndex(container.DataItemIndex);
}
}
grdInvitee.PageIndex = e.NewPageIndex;
PopulateInviteeGrid();
RePopulateCheckBoxes();
}
public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex";
private void RePopulateCheckBoxes()
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;
IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
if (SelectedCustomersIndex != null)
{
if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
{
chkBox.Checked = true;
}
}
}
}
private List
{
get
{
if (ViewState[SELECTED_CUSTOMERS_INDEX] == null)
{
ViewState[SELECTED_CUSTOMERS_INDEX] = new List
}
return (List
}
}
private void RemoveRowIndex(int index)
{
SelectedCustomersIndex.Remove(index);
}
private void PersistRowIndex(int index)
{
if (!SelectedCustomersIndex.Exists(i => i == index))
{
SelectedCustomersIndex.Add(index);
}
}
WRITE THIS IN GRIDVIEW PAGEINDEXCHANGING
protected void grdInvitee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;
IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
if (chkBox.Checked)
{
PersistRowIndex(container.DataItemIndex);
}
else
{
RemoveRowIndex(container.DataItemIndex);
}
}
grdInvitee.PageIndex = e.NewPageIndex;
PopulateInviteeGrid();
RePopulateCheckBoxes();
}
Tuesday, June 7, 2011
Split Words With Coma and sapace
Dim s As String = txtsearch.Text.ToString()
Dim s1 As String = s
' Split string based on spaces
Dim words As String() = s.Split(New Char() {","c})
s1 = s1.Replace(",", " ")
Dim words1 As String() = s1.Split(New Char() {" "c})
' Use For Each loop over words and display them
Dim word As String
For Each word In words
Console.WriteLine(word)
arrSTR.Add(word)
Next
For Each word In words1
Console.WriteLine(word)
arrSTR.Add(word)
Next
Dim s1 As String = s
' Split string based on spaces
Dim words As String() = s.Split(New Char() {","c})
s1 = s1.Replace(",", " ")
Dim words1 As String() = s1.Split(New Char() {" "c})
' Use For Each loop over words and display them
Dim word As String
For Each word In words
Console.WriteLine(word)
arrSTR.Add(word)
Next
For Each word In words1
Console.WriteLine(word)
arrSTR.Add(word)
Next
Saturday, June 4, 2011
Java Script Alert in C#
ADD A CLASS IN APP_CODE AND REPLACE WITH FOLLOWING CODE.RENAME THE CLASS FILE WITH Alert.cs
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);
}
}
}
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);
}
}
}
Get Browser Version in C# Asp.Net
if (!(IsPostBack))
{
if (Request.Browser.Browser == "IE")
{
if (Request.Browser.MajorVersion <= 6)
{
/ /Your Code
}
}
}
{
if (Request.Browser.Browser == "IE")
{
if (Request.Browser.MajorVersion <= 6)
{
/ /Your Code
}
}
}
Friday, June 3, 2011
Wednesday, June 1, 2011
How to Print in ASP.NET 3.5
One of the most common functionality in any ASP.NET application is to print forms and controls. There are a lot of options to print forms using client scripts. In the article, we will see how to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
public class PrintHelper
{
public PrintHelper()
{
}
public void PrintWebControl(Control ctrl)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.End();
}
Subscribe to:
Posts (Atom)