///Where you use Post Method in page u have to set inside the web.cofig
and inside the system.web>--- pages enableViewStateMac="false">
//aspx Source page
form id="form1" method="post" action="http://localhost:1984/Test/get-posted-data.aspx" runat="server">
User : asp:TextBox ID="txtName" runat="server">/asp:TextBox>
Password : asp:TextBox ID="txtPassword" runat="server">/asp:TextBox>
asp:Button ID="btnSend" runat="server" Text="Send"/>
/form>
//Retrive value through Post Mehtod
// string[]s= Request.Form.AllKeys;//through this u can find all the value of post....
Response.Write("User : " + Request.Form["txtName"] + "
");
Response.Write("Password : " + Request.Form["txtPassword"] + "
");
Wednesday, December 29, 2010
Tuesday, December 28, 2010
Zip and Unzip the File(Through Ionic .Dll)
Download ionic.Dll from(http://dotnetzip.codeplex.com/releases/view/27890)
and Add the Dll through Add reference and Add the NameSpaces (using Ionic.Zip;)
ZipFile zip = new ZipFile();
// add this map file into the "images" directory in the zip archive
DirectoryInfo f = new DirectoryInfo("c:\\images");
FileInfo[] a = f.GetFiles();
for (int i = 0; i < a.Length; i++)
{
zip.AddFile("c:\\images\\" + a[i].Name, "images");
}
zip.Save("c:\\MyZipFile.zip");
String TargetDirectory = "c:\\MyZipFile.zip";
using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(TargetDirectory))
{
zip1.ExtractAll("c:\\UnZip",
Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
}
and Add the Dll through Add reference and Add the NameSpaces (using Ionic.Zip;)
ZipFile zip = new ZipFile();
// add this map file into the "images" directory in the zip archive
DirectoryInfo f = new DirectoryInfo("c:\\images");
FileInfo[] a = f.GetFiles();
for (int i = 0; i < a.Length; i++)
{
zip.AddFile("c:\\images\\" + a[i].Name, "images");
}
zip.Save("c:\\MyZipFile.zip");
String TargetDirectory = "c:\\MyZipFile.zip";
using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(TargetDirectory))
{
zip1.ExtractAll("c:\\UnZip",
Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
}
Monday, December 27, 2010
Create Directory when not Exist
string tempFolder = Request.PhysicalApplicationPath + "Assets\\temp";
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
Labels:
Create Directory when not Exist
Design Pattern
//Design Pattern Link
http://www.dofactory.com/Patterns/Patterns.aspx
Design Patterns
Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.
The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.
To give you a head start, the C# source code is provided in 2 forms: 'structural' and 'real-world'. Structural code uses type names as defined in the pattern definition and UML diagrams. Real-world code provides real-world programming situations where you may use these patterns.
A third form, '.NET optimized' demonstrates design patterns that exploit built-in .NET 4.0 features, such as, generics, attributes, delegates, object and collection initializers, automatic properties, and reflection. These and much more are available in our Design Pattern Framework 4.0TM. See our Singleton page for a .NET 4.0 Optimized code sample.
Creational Patterns:
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Patterns:
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Facade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Patterns:
Chain of Resp. A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Capture and restore an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behavior when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
http://www.dofactory.com/Patterns/Patterns.aspx
Design Patterns
Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.
The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.
To give you a head start, the C# source code is provided in 2 forms: 'structural' and 'real-world'. Structural code uses type names as defined in the pattern definition and UML diagrams. Real-world code provides real-world programming situations where you may use these patterns.
A third form, '.NET optimized' demonstrates design patterns that exploit built-in .NET 4.0 features, such as, generics, attributes, delegates, object and collection initializers, automatic properties, and reflection. These and much more are available in our Design Pattern Framework 4.0TM. See our Singleton page for a .NET 4.0 Optimized code sample.
Creational Patterns:
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Patterns:
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Facade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Patterns:
Chain of Resp. A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Capture and restore an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behavior when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
Labels:
Design Pattern
Encrypt and Decrypt Xml and Text File
using System.Security.Cryptography;
/* System.Security.Cryptography namespace
Microsoft provides cryptographic services, including secure encoding and decoding of data.
*/
//hash algorithm are applied to encrpt the string and store in un-readable format..
public XmlDocument OpenXmlDocument(String filePath)//Decrypt Xml File
{
bool useHashing = true;
string Key = "Subhash";
byte[] keyArray;
StreamReader sr = new StreamReader(filePath);//here we read the file of given Path
String str = sr.ReadToEnd();
sr.Close();
byte[] toEncryptArray = Convert.FromBase64String(str);//convert string into ByteArray
if (useHashing){
//All Hash function take input of type Byte[]
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();//Data Encryption/Decpription Standard
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();//for Decrypting Data
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
string xmlData = UTF8Encoding.UTF8.GetString(resultArray);
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlData);
return xDoc;
}
public void SaveXmlDocument(XmlDocument xmldocument, string FilePath, bool EncryptXmlFile)//EncryptXmlFile will be true
{
// bool useHashing = true;
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(xmldocument.OuterXml);//convert Xml file into ByteArray
string Key = "Subhash"; //set the key here for encrypting
if (EncryptXmlFile)
{
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);//convert into ByteArray
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;//Gets or sets the mode for operation of the symmetric algorithm
tdes.Padding = PaddingMode.PKCS7;//Gets or sets the padding mode used in the symmetric algorithm.
ICryptoTransform cTransform = tdes.CreateEncryptor();//for Encrypting Data.
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
StreamWriter _sw = new StreamWriter(FilePath);//For write Encrypted file into given Path
_sw.WriteLine(Convert.ToBase64String(resultArray, 0, resultArray.Length));
_sw.Flush();
_sw.Close();
_sw.Dispose();
}
public void SaveTextDocument(string Textdocument, string FilePath, bool EncryptTextFile)//EncryptTextFile will be true
{
// bool useHashing = true;
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(Textdocument);//convert Text file into ByteArray
string Key = "Subhash"; //set the key here for encrypting
if (EncryptTextFile)
{
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);//convert into ByteArray
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;//Gets or sets the mode for operation of the symmetric algorithm
tdes.Padding = PaddingMode.PKCS7;//Gets or sets the padding mode used in the symmetric algorithm.
ICryptoTransform cTransform = tdes.CreateEncryptor();//for Encrypting Data.
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
StreamWriter _sw = new StreamWriter(FilePath);//For write Encrypted file into given Path
_sw.WriteLine(Convert.ToBase64String(resultArray, 0, resultArray.Length));
_sw.Flush();
_sw.Close();
_sw.Dispose();
}
protected void btnGenerateXml_Click(object sender, EventArgs e)
{
string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "QueryMaster.xml");
//........for check if xml file before Encryption
StreamReader sr = new StreamReader(FilePath);
String str = sr.ReadToEnd();
sr.Close();
string[] k = str.Split(' ');
string s = k[0];
if (str.Contains("<"))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath);
SaveXmlDocument(xmlDoc, FilePath, true);
}
//...........................
//if (s == " // {
// }
}
protected void Read_Click(object sender, EventArgs e)
{
string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "QueryMaster.xml");
XmlDocument xResultDoc = OpenXmlDocument(FilePath);
}
protected void btnGenerateText_Click(object sender, EventArgs e)
{
string FilePath1 = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "a.txt");
StreamReader streamReader = new StreamReader(FilePath1);
string text = streamReader.ReadToEnd();
streamReader.Close();
SaveTextDocument(text, FilePath1, true);
}
protected void btnReadText_Click(object sender, EventArgs e)
{
string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "a.txt");
string xResultDoc = OpenTextDocument(FilePath);
}
public string OpenTextDocument(String filePath) //Decrypt text File
{
bool useHashing = true;
string Key = "Subhash";
byte[] keyArray;
StreamReader sr = new StreamReader(filePath);//here we read the file of given Path
String str = sr.ReadToEnd();
sr.Close();
byte[] toEncryptArray = Convert.FromBase64String(str);//convert string into ByteArray
if (useHashing)
{
//All Hash function take input of type Byte[]
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();//Data Encryption/Decpription Standard
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();//for Decrypting Data
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
string s= UTF8Encoding.UTF8.GetString(resultArray);
return s;
//string xmlData = UTF8Encoding.UTF8.GetString(resultArray);
//XmlDocument xDoc = new XmlDocument();
//xDoc.LoadXml(xmlData);
//return xDoc;
}
/* System.Security.Cryptography namespace
Microsoft provides cryptographic services, including secure encoding and decoding of data.
*/
//hash algorithm are applied to encrpt the string and store in un-readable format..
public XmlDocument OpenXmlDocument(String filePath)//Decrypt Xml File
{
bool useHashing = true;
string Key = "Subhash";
byte[] keyArray;
StreamReader sr = new StreamReader(filePath);//here we read the file of given Path
String str = sr.ReadToEnd();
sr.Close();
byte[] toEncryptArray = Convert.FromBase64String(str);//convert string into ByteArray
if (useHashing){
//All Hash function take input of type Byte[]
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();//Data Encryption/Decpription Standard
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();//for Decrypting Data
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
string xmlData = UTF8Encoding.UTF8.GetString(resultArray);
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlData);
return xDoc;
}
public void SaveXmlDocument(XmlDocument xmldocument, string FilePath, bool EncryptXmlFile)//EncryptXmlFile will be true
{
// bool useHashing = true;
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(xmldocument.OuterXml);//convert Xml file into ByteArray
string Key = "Subhash"; //set the key here for encrypting
if (EncryptXmlFile)
{
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);//convert into ByteArray
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;//Gets or sets the mode for operation of the symmetric algorithm
tdes.Padding = PaddingMode.PKCS7;//Gets or sets the padding mode used in the symmetric algorithm.
ICryptoTransform cTransform = tdes.CreateEncryptor();//for Encrypting Data.
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
StreamWriter _sw = new StreamWriter(FilePath);//For write Encrypted file into given Path
_sw.WriteLine(Convert.ToBase64String(resultArray, 0, resultArray.Length));
_sw.Flush();
_sw.Close();
_sw.Dispose();
}
public void SaveTextDocument(string Textdocument, string FilePath, bool EncryptTextFile)//EncryptTextFile will be true
{
// bool useHashing = true;
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(Textdocument);//convert Text file into ByteArray
string Key = "Subhash"; //set the key here for encrypting
if (EncryptTextFile)
{
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);//convert into ByteArray
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;//Gets or sets the mode for operation of the symmetric algorithm
tdes.Padding = PaddingMode.PKCS7;//Gets or sets the padding mode used in the symmetric algorithm.
ICryptoTransform cTransform = tdes.CreateEncryptor();//for Encrypting Data.
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
StreamWriter _sw = new StreamWriter(FilePath);//For write Encrypted file into given Path
_sw.WriteLine(Convert.ToBase64String(resultArray, 0, resultArray.Length));
_sw.Flush();
_sw.Close();
_sw.Dispose();
}
protected void btnGenerateXml_Click(object sender, EventArgs e)
{
string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "QueryMaster.xml");
//........for check if xml file before Encryption
StreamReader sr = new StreamReader(FilePath);
String str = sr.ReadToEnd();
sr.Close();
string[] k = str.Split(' ');
string s = k[0];
if (str.Contains("<"))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath);
SaveXmlDocument(xmlDoc, FilePath, true);
}
//...........................
//if (s == " // {
// }
}
protected void Read_Click(object sender, EventArgs e)
{
string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "QueryMaster.xml");
XmlDocument xResultDoc = OpenXmlDocument(FilePath);
}
protected void btnGenerateText_Click(object sender, EventArgs e)
{
string FilePath1 = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "a.txt");
StreamReader streamReader = new StreamReader(FilePath1);
string text = streamReader.ReadToEnd();
streamReader.Close();
SaveTextDocument(text, FilePath1, true);
}
protected void btnReadText_Click(object sender, EventArgs e)
{
string FilePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Configuration"), "a.txt");
string xResultDoc = OpenTextDocument(FilePath);
}
public string OpenTextDocument(String filePath) //Decrypt text File
{
bool useHashing = true;
string Key = "Subhash";
byte[] keyArray;
StreamReader sr = new StreamReader(filePath);//here we read the file of given Path
String str = sr.ReadToEnd();
sr.Close();
byte[] toEncryptArray = Convert.FromBase64String(str);//convert string into ByteArray
if (useHashing)
{
//All Hash function take input of type Byte[]
//To generate a hash value, create an instance of a hash algorithm and call ComputeHash() on it.
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//The ComputeHash method accepts only an array of bytes or a stream..
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));//key also convert into ByteArray
hashmd5.Clear();//Releases all resources used by the HashAlgorithm class
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(Key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();//Data Encryption/Decpription Standard
tdes.Key = keyArray;//Gets or sets the secret key for the TripleDES algorithm.
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();//for Decrypting Data
//TransformFinalBlock:Transforms(Change) the specified region of the specified byte array.
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
string s= UTF8Encoding.UTF8.GetString(resultArray);
return s;
//string xmlData = UTF8Encoding.UTF8.GetString(resultArray);
//XmlDocument xDoc = new XmlDocument();
//xDoc.LoadXml(xmlData);
//return xDoc;
}
Tuesday, December 21, 2010
Add Update through Linq
Create one .dbml file and make DataBase connection there and drag and drop the table inside the Dbml window. and right clcik on the field which field u want primary key and select the property option and give there True as primary key.
protected void btnUpdate_Click(object sender, EventArgs e)
{
linqStudent linObj = new linqStudent();
var obj = linObj.Students.SingleOrDefault(o => o.Roll == txtRoll.Text);
if (obj != null)
{
obj.Name = txtName.Text;
linObj.SubmitChanges();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
linqStudent linObj = new linqStudent();
Student objStdebt = new Student();
objStdebt.Name = txtName.Text;
objStdebt.Roll = txtRoll.Text;
linObj.Students.InsertOnSubmit(objStdebt);
linObj.SubmitChanges();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
linqStudent linObj = new linqStudent();
var obj = linObj.Students.SingleOrDefault(o => o.Roll == txtRoll.Text);
if (obj != null)
{
obj.Name = txtName.Text;
linObj.SubmitChanges();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
linqStudent linObj = new linqStudent();
Student objStdebt = new Student();
objStdebt.Name = txtName.Text;
objStdebt.Roll = txtRoll.Text;
linObj.Students.InsertOnSubmit(objStdebt);
linObj.SubmitChanges();
}
Labels:
Add Update through Linq
Friday, December 17, 2010
Data Relation Through DataSet
SqlConnection con=new SqlConnection (ConfigurationManager.ConnectionStrings["kumarConnectionString"].ConnectionString);
protected void Button1_Click1(object sender, EventArgs e)
{
DataSet ds = new DataSet();
string firstSql = null;
//connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
firstSql = "select * from emp;";
firstSql += "select * from dep";
try
{
SqlCommand cmd = new SqlCommand(firstSql, con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
//creating data relations
DataRelation relation;
DataColumn table1Column;
DataColumn table2Column;
//retrieve column
table1Column = ds.Tables[0].Columns[0];
table2Column = ds.Tables[1].Columns[0];
//relating tables
relation = new DataRelation("relation", table1Column, table2Column);
//assign relation to dataset
ds.Relations.Add(relation);
Response.Write("Data relation completed");
}
catch (Exception ex)
{
Response.Write("Can not open con ! ");
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
DataSet ds = new DataSet();
string firstSql = null;
//connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
firstSql = "select * from emp;";
firstSql += "select * from dep";
try
{
SqlCommand cmd = new SqlCommand(firstSql, con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
//creating data relations
DataRelation relation;
DataColumn table1Column;
DataColumn table2Column;
//retrieve column
table1Column = ds.Tables[0].Columns[0];
table2Column = ds.Tables[1].Columns[0];
//relating tables
relation = new DataRelation("relation", table1Column, table2Column);
//assign relation to dataset
ds.Relations.Add(relation);
Response.Write("Data relation completed");
}
catch (Exception ex)
{
Response.Write("Can not open con ! ");
}
}
Labels:
Data Relation Through DataSet
Reading Xml file and fill dropdown....
XmlNode eleDestNodeLists;
string FilePath = Request.PhysicalApplicationPath + @"Configuration\" + "UserInfo.xml";
XmlDocument docSource = new XmlDocument();
docSource.Load(FilePath);
Int32 assetid = Convert.ToInt32(Session["assetid"].ToString());
string sbookCode = Session["bookCode"].ToString();
eleDestNodeLists = docSource.SelectSingleNode("/UserInfo/Asset[@assetid='" + assetid + "' and @BookCode='" + sbookCode.ToString() + "']");
foreach (XmlNode xn in eleDestNodeLists.ChildNodes)
{
string abbreviation = xn.Attributes.GetNamedItem("abbreviation").Value;
string id = xn.Attributes["id"].Value;
ddlRole.Items.Add(new ListItem(abbreviation, id));
Page.ClientScript.RegisterStartupScript(typeof(Page), "FillUserName", "setTimeout(\"FillUserName()\",1000);", true);
}
string FilePath = Request.PhysicalApplicationPath + @"Configuration\" + "UserInfo.xml";
XmlDocument docSource = new XmlDocument();
docSource.Load(FilePath);
Int32 assetid = Convert.ToInt32(Session["assetid"].ToString());
string sbookCode = Session["bookCode"].ToString();
eleDestNodeLists = docSource.SelectSingleNode("/UserInfo/Asset[@assetid='" + assetid + "' and @BookCode='" + sbookCode.ToString() + "']");
foreach (XmlNode xn in eleDestNodeLists.ChildNodes)
{
string abbreviation = xn.Attributes.GetNamedItem("abbreviation").Value;
string id = xn.Attributes["id"].Value;
ddlRole.Items.Add(new ListItem(abbreviation, id));
Page.ClientScript.RegisterStartupScript(typeof(Page), "FillUserName", "setTimeout(\"FillUserName()\",1000);", true);
}
Thursday, December 16, 2010
Importanat Question
What is Application Blocks?
What are the processes to implement the strong name in the assembly?
How to use Memory management in .Net?
What is serialization in .NET? What are the ways to control serialization?
if there are two version of assembly is installed in computer the how we decide that which is using ?
Ans-- Assembly information is stored in manifest, there are 4 version of assembly (major, minor, build and revision) so we can decide the version through major and minor minor like 2.0.--.—
What is the difference between the application and caching?
what is assembly placement?
What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
What are possible implementations of distributed applications in .NET?
What is the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
Inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.
What namespace does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
What are the processes to implement the strong name in the assembly?
How to use Memory management in .Net?
What is serialization in .NET? What are the ways to control serialization?
if there are two version of assembly is installed in computer the how we decide that which is using ?
Ans-- Assembly information is stored in manifest, there are 4 version of assembly (major, minor, build and revision) so we can decide the version through major and minor minor like 2.0.--.—
What is the difference between the application and caching?
what is assembly placement?
What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
What are possible implementations of distributed applications in .NET?
What is the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
Inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.
What namespace does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
Labels:
Importanat Question
Friday, December 10, 2010
Update Existing Xml and If Xml is not created it will create and then update the Existing Xml...
static public void MoveUserInfo(string destFolder)
{
string _sourcePath = "";
string _configurationPath = "";
_sourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "UserInfo.xml");
_configurationPath = Path.Combine(Path.Combine(destFolder, "Configuration"), "UserInfo.xml");
if (!Directory.Exists(Path.Combine(destFolder, "Configuration")))
Directory.CreateDirectory(Path.Combine(destFolder, "Configuration"));
if (File.Exists(_configurationPath) == true)
{
updateUserInfoXML(_sourcePath, _configurationPath);
}
else //Create UserInfo.Xml file into Directory if not Exist in the Destination Path..
{
File.Copy(_sourcePath, _configurationPath, true);
}
}
static public void updateUserInfoXML(string pathSource, string pathDestination)
{
try
{
XmlDocument docSource = new XmlDocument();
XmlDocument docDestination = new XmlDocument();
string xmlMmessage = "";
docSource.Load(pathSource);
docDestination.Load(pathDestination);
XmlNodeList elemList = docSource.GetElementsByTagName("Asset");
//XmlNodeList elemListRoll = docSource.GetElementsByTagName("role");
//XmlNodeList elemListUser = docSource.GetElementsByTagName("User");
string attrAssetID;
XmlNodeList eleDestNodeList;
XmlNode eleDestinationNode = docDestination.DocumentElement;
foreach (XmlNode eleSourceNode in elemList)
{
attrAssetID = eleSourceNode.Attributes["assetid"].Value;
// attrRollID = eleSourceNode.Attributes["rollid"].Value;
//attrUserID = eleSourceNode.Attributes["Userid"].Value;
eleDestNodeList = docDestination.SelectNodes("/UserInfo/Asset[@assetid='" + attrAssetID.ToString() + "']");
if (eleDestNodeList.Count > 0)
{
eleDestinationNode = docDestination.SelectSingleNode("/UserInfo/Asset[@assetid='" + attrAssetID.ToString() + "']");
//docSource.AppendChild()
//---IF NODE EXISTS THEN REPLACE THE SOURCE NODE WITH TARGET NODE
XmlDocumentFragment fragment = docDestination.CreateDocumentFragment();
fragment.InnerXml = eleSourceNode.OuterXml;
eleDestinationNode.ParentNode.ReplaceChild(fragment, eleDestinationNode);
xmlMmessage = "Sucessfully replaced";
}
else
{
//---IF NODE IS NOT EXISTS THEN APPEND THE SOURCE NODE WITH TARGET NODE
XmlDocumentFragment fragment = docDestination.CreateDocumentFragment();
fragment.InnerXml = eleSourceNode.OuterXml;
eleDestinationNode.AppendChild(fragment);
xmlMmessage = "Sucessfully Append";
}
}
docDestination.PreserveWhitespace = true;
docDestination.Save(pathDestination);
Console.WriteLine(xmlMmessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
Console.ReadLine();
}
}
{
string _sourcePath = "";
string _configurationPath = "";
_sourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "UserInfo.xml");
_configurationPath = Path.Combine(Path.Combine(destFolder, "Configuration"), "UserInfo.xml");
if (!Directory.Exists(Path.Combine(destFolder, "Configuration")))
Directory.CreateDirectory(Path.Combine(destFolder, "Configuration"));
if (File.Exists(_configurationPath) == true)
{
updateUserInfoXML(_sourcePath, _configurationPath);
}
else //Create UserInfo.Xml file into Directory if not Exist in the Destination Path..
{
File.Copy(_sourcePath, _configurationPath, true);
}
}
static public void updateUserInfoXML(string pathSource, string pathDestination)
{
try
{
XmlDocument docSource = new XmlDocument();
XmlDocument docDestination = new XmlDocument();
string xmlMmessage = "";
docSource.Load(pathSource);
docDestination.Load(pathDestination);
XmlNodeList elemList = docSource.GetElementsByTagName("Asset");
//XmlNodeList elemListRoll = docSource.GetElementsByTagName("role");
//XmlNodeList elemListUser = docSource.GetElementsByTagName("User");
string attrAssetID;
XmlNodeList eleDestNodeList;
XmlNode eleDestinationNode = docDestination.DocumentElement;
foreach (XmlNode eleSourceNode in elemList)
{
attrAssetID = eleSourceNode.Attributes["assetid"].Value;
// attrRollID = eleSourceNode.Attributes["rollid"].Value;
//attrUserID = eleSourceNode.Attributes["Userid"].Value;
eleDestNodeList = docDestination.SelectNodes("/UserInfo/Asset[@assetid='" + attrAssetID.ToString() + "']");
if (eleDestNodeList.Count > 0)
{
eleDestinationNode = docDestination.SelectSingleNode("/UserInfo/Asset[@assetid='" + attrAssetID.ToString() + "']");
//docSource.AppendChild()
//---IF NODE EXISTS THEN REPLACE THE SOURCE NODE WITH TARGET NODE
XmlDocumentFragment fragment = docDestination.CreateDocumentFragment();
fragment.InnerXml = eleSourceNode.OuterXml;
eleDestinationNode.ParentNode.ReplaceChild(fragment, eleDestinationNode);
xmlMmessage = "Sucessfully replaced";
}
else
{
//---IF NODE IS NOT EXISTS THEN APPEND THE SOURCE NODE WITH TARGET NODE
XmlDocumentFragment fragment = docDestination.CreateDocumentFragment();
fragment.InnerXml = eleSourceNode.OuterXml;
eleDestinationNode.AppendChild(fragment);
xmlMmessage = "Sucessfully Append";
}
}
docDestination.PreserveWhitespace = true;
docDestination.Save(pathDestination);
Console.WriteLine(xmlMmessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
Console.ReadLine();
}
}
Create Xml File (using dataset)
StringBuilder _UserInfo = new StringBuilder();
dataset infoDS=new DataSet();
DataSet infoDS = PXE.Facade.PXEFacade.GetUserRoleOnAsset(bookId, nAssetId);
_UserInfo.Append("");
_UserInfo.Append("");
_UserInfo.Append("");
for (int i = 0; i < infoDS.Tables[0].Rows.Count; i++) { if (infoDS.Tables[0].Rows.Count > 0)
{
string _RoleId = infoDS.Tables[0].Rows[i]["roleid"].ToString();
string _UserId = infoDS.Tables[0].Rows[i]["userid"].ToString();
string _RoleName = infoDS.Tables[0].Rows[i]["roleName"].ToString();
string _Abbreviation = infoDS.Tables[0].Rows[i]["abbreviation"].ToString();
string _DisplayName = infoDS.Tables[0].Rows[i]["displayName"].ToString();
_UserInfo.Append("");
_UserInfo.Append(" ");
_UserInfo.Append(" ");
//_UserInfo.Append(" ");
if (File.Exists(tempFolder + "\\UserInfo.xml"))
{
File.SetAttributes(tempFolder + "\\UserInfo.xml", FileAttributes.Normal);
}
StreamWriter _sw1 = new StreamWriter(tempFolder + "\\UserInfo.xml");
_sw1.WriteLine(_UserInfo.ToString());
_sw1.Flush();
_sw1.Close();
_sw1.Dispose();
}
}
StreamWriter _sw = new StreamWriter(tempFolder + "\\UserInfo.xml");
_UserInfo.Append("");
_UserInfo.Append(" ");
_sw.WriteLine(_UserInfo.ToString());
_sw.Flush();
_sw.Close();
_sw.Dispose();
/**/
dataset infoDS=new DataSet();
DataSet infoDS = PXE.Facade.PXEFacade.GetUserRoleOnAsset(bookId, nAssetId);
_UserInfo.Append("");
_UserInfo.Append("
_UserInfo.Append("
for (int i = 0; i < infoDS.Tables[0].Rows.Count; i++) { if (infoDS.Tables[0].Rows.Count > 0)
{
string _RoleId = infoDS.Tables[0].Rows[i]["roleid"].ToString();
string _UserId = infoDS.Tables[0].Rows[i]["userid"].ToString();
string _RoleName = infoDS.Tables[0].Rows[i]["roleName"].ToString();
string _Abbreviation = infoDS.Tables[0].Rows[i]["abbreviation"].ToString();
string _DisplayName = infoDS.Tables[0].Rows[i]["displayName"].ToString();
_UserInfo.Append("
_UserInfo.Append("
_UserInfo.Append("
//_UserInfo.Append("
if (File.Exists(tempFolder + "\\UserInfo.xml"))
{
File.SetAttributes(tempFolder + "\\UserInfo.xml", FileAttributes.Normal);
}
StreamWriter _sw1 = new StreamWriter(tempFolder + "\\UserInfo.xml");
_sw1.WriteLine(_UserInfo.ToString());
_sw1.Flush();
_sw1.Close();
_sw1.Dispose();
}
}
StreamWriter _sw = new StreamWriter(tempFolder + "\\UserInfo.xml");
_UserInfo.Append("");
_UserInfo.Append("
_sw.WriteLine(_UserInfo.ToString());
_sw.Flush();
_sw.Close();
_sw.Dispose();
/**/
Labels:
Create Xml File (using dataset)
Sunday, November 14, 2010
Distinct Value from two array
string[] a1 = { "A", "B", "A", "C", "C" };
string[] a2 = { "A", "E", "C", "D", "C" };
// var unique = a1.Union(a2);
string[] a3 = new string[a1.Length + a2.Length];
a1.CopyTo(a3, 0);
a2.CopyTo(a3, a1.Length);
ArrayList arr = new ArrayList();
for (int k = 0; k < a3.Length; k++)
{
arr.Add(a3[k].ToString());
}
for (int i = 0; i < arr.Count - 1; i++)
{
for (int j = i + 1; j < arr.Count; j++)
{
if (arr[i].Equals(arr[j]))
{
arr.RemoveAt(j);
}
}
}
for (int i = 0; i < arr.Count; i++)
{
arr.Sort();
Console.WriteLine(arr[i]);
}
Console.ReadLine();
string[] a2 = { "A", "E", "C", "D", "C" };
// var unique = a1.Union(a2);
string[] a3 = new string[a1.Length + a2.Length];
a1.CopyTo(a3, 0);
a2.CopyTo(a3, a1.Length);
ArrayList arr = new ArrayList();
for (int k = 0; k < a3.Length; k++)
{
arr.Add(a3[k].ToString());
}
for (int i = 0; i < arr.Count - 1; i++)
{
for (int j = i + 1; j < arr.Count; j++)
{
if (arr[i].Equals(arr[j]))
{
arr.RemoveAt(j);
}
}
}
for (int i = 0; i < arr.Count; i++)
{
arr.Sort();
Console.WriteLine(arr[i]);
}
Console.ReadLine();
Labels:
Distinct Value from two array
Distinct Value from two array(Linq)
string[] a1 = { "A", "B", "A", "C", "C" };
string[] a2 = { "A", "E", "C", "D", "C" };
var unique = a1.Union(a2);
string[] a2 = { "A", "E", "C", "D", "C" };
var unique = a1.Union(a2);
Wednesday, November 10, 2010
AutoIncremented Number
public string NewRequestID()
{
string NewID = "";
SqlDataAdapter da = default(SqlDataAdapter);
DataTable dt = null;
da = new SqlDataAdapter("select top 1 code from EmpMaster order by code desc", con);
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count != 0)
{
string str = dt.Rows[0]["Code"].ToString();
int i = Convert.ToInt32(str.Substring(1));
NewID = (i + 1).ToString();
int start = NewID.Length + 1;
//Position from where 0 has to be inserted to the RequestID.
for (int j = start; j <= (str.Length - 1); j++)
{
NewID = "0" + NewID;
}
NewID = "A" + NewID;
}
else
{
NewID = "A000001";
}
return NewID;
}
{
string NewID = "";
SqlDataAdapter da = default(SqlDataAdapter);
DataTable dt = null;
da = new SqlDataAdapter("select top 1 code from EmpMaster order by code desc", con);
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count != 0)
{
string str = dt.Rows[0]["Code"].ToString();
int i = Convert.ToInt32(str.Substring(1));
NewID = (i + 1).ToString();
int start = NewID.Length + 1;
//Position from where 0 has to be inserted to the RequestID.
for (int j = start; j <= (str.Length - 1); j++)
{
NewID = "0" + NewID;
}
NewID = "A" + NewID;
}
else
{
NewID = "A000001";
}
return NewID;
}
Labels:
AutoIncremented Number
Sunday, October 31, 2010
Transaction In sql server(Maintaining Relationship)
Create procedure sp_InsertRelation(@Code varchar(50),@Name Varchar(100),@Organisation varchar(100))
as
begin set nocount On
begin transaction
begin try
insert into empMaster(Code,Name) values(@Code,@Name)
insert into empDetails(Code,Organisation) values(@Code,@Organisation)
Commit Tran
end try
begin catch
rollback tran
end catch
End
as
begin set nocount On
begin transaction
begin try
insert into empMaster(Code,Name) values(@Code,@Name)
insert into empDetails(Code,Organisation) values(@Code,@Organisation)
Commit Tran
end try
begin catch
rollback tran
end catch
End
Thursday, October 28, 2010
Genric Function For clearing TextBox Only
function chkGrid()
{
var Inputs = document.getElementsByTagName("input");
for(i = 0; i < Inputs.length; i++)
{
if(Inputs[i].type == 'text' )
{Inputs[i].value = ""; }
}
}
{
var Inputs = document.getElementsByTagName("input");
for(i = 0; i < Inputs.length; i++)
{
if(Inputs[i].type == 'text' )
{Inputs[i].value = ""; }
}
}
Tuesday, October 19, 2010
DropDown inside Gridview and insert the value(primary foreign key relationship)
//.aspx page grid view Design, Blog not accepted HTmL TEXT so I remove starting HTML braces so please Add this tag when u use.....
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
Columns>
asp:TemplateField HeaderText="Id" Visible="false">
ItemTemplate>
asp:Label ID="lblid" runat="server" Text='<%#Bind("Id") %>'>/asp:Label>/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="Name" SortExpression="Name">
EditItemTemplate>
asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'>/asp:TextBox>
/EditItemTemplate>
ItemTemplate>
asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'>/asp:Label>
/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="City">
EditItemTemplate>
asp:DropDownList ID="cmbCity" runat="server">
asp:ListItem Text="--Select--" Value="--Select--">/asp:ListItem>
/asp:DropDownList>
/EditItemTemplate>
ItemTemplate>
asp:Label ID="Label3" runat="server" Text='<%# Eval("City") %>'>/asp:Label>
/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="Edit" ShowHeader="False">
EditItemTemplate>
asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update">/asp:LinkButton>
asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel">
/EditItemTemplate>
ItemTemplate>
asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit">
/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="Delete" ShowHeader="false">
ItemTemplate>
asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete">/asp:LinkButton>
/ItemTemplate>
/asp:TemplateField>
/Columns>
/asp:GridView>
//////.cs file
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["masterConnectionString"].ConnectionString);
SqlCommand cmd = null;
SqlDataAdapter adp = null;
DataSet ds = null;
public void dropdow(DropDownList drp)
{
adp = new SqlDataAdapter("Select cityid,city from city", con);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
drp.Items.Add(ds.Tables[0].Rows[i]["City"].ToString());
drp.Items[i + 1].Value = ds.Tables[0].Rows[i]["cityId"].ToString();
}
}
}
public void Bind()
{
try
{
adp = new SqlDataAdapter("Select a.id,a.name,b.city from person a left outer join city b on a.cityid=b.cityid ", con);
ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch { }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbCity");
if (cmbType != null )
{
dropdow(cmbType);
//cmbType.DataSource = customer.FetchCustomerType();
//cmbType.DataBind();
//cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
TextBox txtname1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
DropDownList cmbType1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbCity");
string Name = txtname1.Text;
string city = cmbType1.SelectedValue.ToString();
string id1 = id.Text;
con.Open();
//cmd = new SqlCommand("insert into name values()", con);
//cmd.ExecuteNonQuery();
//con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
Bind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
Bind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
Columns>
asp:TemplateField HeaderText="Id" Visible="false">
ItemTemplate>
asp:Label ID="lblid" runat="server" Text='<%#Bind("Id") %>'>/asp:Label>/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="Name" SortExpression="Name">
EditItemTemplate>
asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'>/asp:TextBox>
/EditItemTemplate>
ItemTemplate>
asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'>/asp:Label>
/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="City">
EditItemTemplate>
asp:DropDownList ID="cmbCity" runat="server">
asp:ListItem Text="--Select--" Value="--Select--">/asp:ListItem>
/asp:DropDownList>
/EditItemTemplate>
ItemTemplate>
asp:Label ID="Label3" runat="server" Text='<%# Eval("City") %>'>/asp:Label>
/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="Edit" ShowHeader="False">
EditItemTemplate>
asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update">/asp:LinkButton>
asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel">
/EditItemTemplate>
ItemTemplate>
asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit">
/ItemTemplate>
/asp:TemplateField>
asp:TemplateField HeaderText="Delete" ShowHeader="false">
ItemTemplate>
asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete">/asp:LinkButton>
/ItemTemplate>
/asp:TemplateField>
/Columns>
/asp:GridView>
//////.cs file
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["masterConnectionString"].ConnectionString);
SqlCommand cmd = null;
SqlDataAdapter adp = null;
DataSet ds = null;
public void dropdow(DropDownList drp)
{
adp = new SqlDataAdapter("Select cityid,city from city", con);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
drp.Items.Add(ds.Tables[0].Rows[i]["City"].ToString());
drp.Items[i + 1].Value = ds.Tables[0].Rows[i]["cityId"].ToString();
}
}
}
public void Bind()
{
try
{
adp = new SqlDataAdapter("Select a.id,a.name,b.city from person a left outer join city b on a.cityid=b.cityid ", con);
ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch { }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbCity");
if (cmbType != null )
{
dropdow(cmbType);
//cmbType.DataSource = customer.FetchCustomerType();
//cmbType.DataBind();
//cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
TextBox txtname1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
DropDownList cmbType1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbCity");
string Name = txtname1.Text;
string city = cmbType1.SelectedValue.ToString();
string id1 = id.Text;
con.Open();
//cmd = new SqlCommand("insert into name values()", con);
//cmd.ExecuteNonQuery();
//con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
Bind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
Bind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
Why sql Injection problem occur
SQL injection occurs when user input is not filtered for escape characters and is then passed into an SQL statement
////Through this you can remove sqlinjection problem
Example
String name = txtUserId.Text.Trim().Replace("'", "''");
String Password = txtPassword.Text.Trim().Replace("'", "''");
////Through this you can remove sqlinjection problem
Example
String name = txtUserId.Text.Trim().Replace("'", "''");
String Password = txtPassword.Text.Trim().Replace("'", "''");
Labels:
Why sql Injection problem occur
Backup and Restore DataBase
//Backup Databse
backup database subhash to disk='f:\subhash1234.bak'
//Restore DataBase
Retrive the Logical file name of the database from backup.
RESTORE FILELISTONLY
FROM DISK = 'f:\subhash1234.bak' after this query run You find out .MDF AND .Ldf file.
MDF = Primary Data File.
LDF = Log File.
RESTORE DATABASE YourDB
FROM DISK = 'f:\subhash1234.bak'
WITH MOVE 'YourMDFLogicalName' TO 'F:\DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'F:\DataYourLDFFile.ldf'
Example-----
RESTORE DATABASE Deepak1
FROM DISK = 'f:\subhash1234.bak'
WITH MOVE 'subhash' TO 'F:\subhash.mdf',
MOVE 'subhash_log' TO 'F:\subhash_log.LDF'
backup database subhash to disk='f:\subhash1234.bak'
//Restore DataBase
Retrive the Logical file name of the database from backup.
RESTORE FILELISTONLY
FROM DISK = 'f:\subhash1234.bak' after this query run You find out .MDF AND .Ldf file.
MDF = Primary Data File.
LDF = Log File.
RESTORE DATABASE YourDB
FROM DISK = 'f:\subhash1234.bak'
WITH MOVE 'YourMDFLogicalName' TO 'F:\DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'F:\DataYourLDFFile.ldf'
Example-----
RESTORE DATABASE Deepak1
FROM DISK = 'f:\subhash1234.bak'
WITH MOVE 'subhash' TO 'F:\subhash.mdf',
MOVE 'subhash_log' TO 'F:\subhash_log.LDF'
Labels:
Backup and Restore DataBase
Monday, October 18, 2010
Check value Numeric is not(validation control server side)
asp:TextBox ID="TextBox1" runat="server" CausesValidation="True">/asp:TextBox>
asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Pless Enter textbox1 value" ControlToValidate="TextBox1">*/asp:RequiredFieldValidator>
asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="textbox1"
ErrorMessage="Enter numeric value" Operator="DataTypeCheck" SetFocusOnError="True"
Type="Integer">/asp:CompareValidator>
asp:ValidationSummary ID="ValidationSummary1" runat="server" />
asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Pless Enter textbox1 value" ControlToValidate="TextBox1">*/asp:RequiredFieldValidator>
asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="textbox1"
ErrorMessage="Enter numeric value" Operator="DataTypeCheck" SetFocusOnError="True"
Type="Integer">/asp:CompareValidator>
asp:ValidationSummary ID="ValidationSummary1" runat="server" />
Wednesday, September 15, 2010
Abstract Class and Interface differences with example
An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.
What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.
Both Together
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined
Using the Code
Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.
I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.
In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.
Abstract Class Employee
Collapse
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for Employee.
///
public abstract class Employee
{
//we can have fields and properties
//in the Abstract class
protected String id;
protected String lname;
protected String fname;
//properties
public abstract String ID
{
get;
set;
}
public abstract String FirstName
{
get;
set;
}
public abstract String LastName
{
get;
set;
}
//completed methods
public String Update()
{
return "Employee " + id + " " +
lname + " " + fname +
" updated";
}
//completed methods
public String Add()
{
return "Employee " + id + " " +
lname + " " + fname +
" added";
}
//completed methods
public String Delete()
{
return "Employee " + id + " " +
lname + " " + fname +
" deleted";
}
//completed methods
public String Search()
{
return "Employee " + id + " " +
lname + " " + fname +
" found";
}
//abstract method that is different
//from Fulltime and Contractor
//therefore i keep it uncompleted and
//let each implementation
//complete it the way they calculate the wage.
public abstract String CalculateWage();
}
}
Interface Employee
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for IEmployee.
///
public interface IEmployee
{
//cannot have fields. uncommenting
//will raise error!
// protected String id;
// protected String lname;
// protected String fname;
//just signature of the properties
//and methods.
//setting a rule or contract to be
//followed by implementations.
String ID
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
// cannot have implementation
// cannot have modifiers public
// etc all are assumed public
// cannot have virtual
String Update();
String Add();
String Delete();
String Search();
String CalculateWage();
}
}
Inherited Objects
Emp_Fulltime:
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for Emp_Fulltime.
///
//Inheriting from the Abstract class
public class Emp_Fulltime : Employee
{
//uses all the properties of the
//Abstract class therefore no
//properties or fields here!
public Emp_Fulltime()
{
}
public override String ID
{
get
{
return id;
}
set
{
id = value;
}
}
public override String FirstName
{
get
{
return fname;
}
set
{
fname = value;
}
}
public override String LastName
{
get
{
return lname;
}
set
{
lname = value;
}
}
//common methods that are
//implemented in the abstract class
public new String Add()
{
return base.Add();
}
//common methods that are implemented
//in the abstract class
public new String Delete()
{
return base.Delete();
}
//common methods that are implemented
//in the abstract class
public new String Search()
{
return base.Search();
}
//common methods that are implemented
//in the abstract class
public new String Update()
{
return base.Update();
}
//abstract method that is different
//from Fulltime and Contractor
//therefore I override it here.
public override String CalculateWage()
{
return "Full time employee " +
base.fname + " is calculated " +
"using the Abstract class...";
}
}
}
Emp_Fulltime2:
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for Emp_fulltime2.
///
//Implementing the interface
public class Emp_fulltime2 : IEmployee
{
//All the properties and
//fields are defined here!
protected String id;
protected String lname;
protected String fname;
public Emp_fulltime2()
{
//
// TODO: Add constructor logic here
//
}
public String ID
{
get
{
return id;
}
set
{
id = value;
}
}
public String FirstName
{
get
{
return fname;
}
set
{
fname = value;
}
}
public String LastName
{
get
{
return lname;
}
set
{
lname = value;
}
}
//all the manipulations including Add,Delete,
//Search, Update, Calculate are done
//within the object as there are not
//implementation in the Interface entity.
public String Add()
{
return "Fulltime Employee " +
fname + " added.";
}
public String Delete()
{
return "Fulltime Employee " +
fname + " deleted.";
}
public String Search()
{
return "Fulltime Employee " +
fname + " searched.";
}
public String Update()
{
return "Fulltime Employee " +
fname + " updated.";
}
//if you change to Calculatewage().
//Just small 'w' it will raise
//error as in interface
//it is CalculateWage() with capital 'W'.
public String CalculateWage()
{
return "Full time employee " +
fname + " caluculated using " +
"Interface.";
}
}
}
Code for Testing
Collapse
//This is the sub that tests both
//implementations using Interface and Abstract
private void InterfaceExample_Click(object sender,
System.EventArgs e)
{
try
{
IEmployee emp;
Emp_fulltime2 emp1 = new Emp_fulltime2();
emp = emp1;
emp.ID = "2234";
emp.FirstName= "Rahman" ;
emp.LastName = "Mahmoodi" ;
//call add method od the object
MessageBox.Show(emp.Add().ToString());
//call the CalculateWage method
MessageBox.Show(emp.CalculateWage().ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void cmdAbstractExample_Click(object sender,
System.EventArgs e)
{
Employee emp;
emp = new Emp_Fulltime();
emp.ID = "2244";
emp.FirstName= "Maria" ;
emp.LastName = "Robinlius" ;
MessageBox.Show(emp.Add().ToString());
//call the CalculateWage method
MessageBox.Show(emp.CalculateWage().ToString());
}
Conclusion
In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.
What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.
Both Together
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined
Using the Code
Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.
I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.
In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.
Abstract Class Employee
Collapse
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for Employee.
///
public abstract class Employee
{
//we can have fields and properties
//in the Abstract class
protected String id;
protected String lname;
protected String fname;
//properties
public abstract String ID
{
get;
set;
}
public abstract String FirstName
{
get;
set;
}
public abstract String LastName
{
get;
set;
}
//completed methods
public String Update()
{
return "Employee " + id + " " +
lname + " " + fname +
" updated";
}
//completed methods
public String Add()
{
return "Employee " + id + " " +
lname + " " + fname +
" added";
}
//completed methods
public String Delete()
{
return "Employee " + id + " " +
lname + " " + fname +
" deleted";
}
//completed methods
public String Search()
{
return "Employee " + id + " " +
lname + " " + fname +
" found";
}
//abstract method that is different
//from Fulltime and Contractor
//therefore i keep it uncompleted and
//let each implementation
//complete it the way they calculate the wage.
public abstract String CalculateWage();
}
}
Interface Employee
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for IEmployee.
///
public interface IEmployee
{
//cannot have fields. uncommenting
//will raise error!
// protected String id;
// protected String lname;
// protected String fname;
//just signature of the properties
//and methods.
//setting a rule or contract to be
//followed by implementations.
String ID
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
// cannot have implementation
// cannot have modifiers public
// etc all are assumed public
// cannot have virtual
String Update();
String Add();
String Delete();
String Search();
String CalculateWage();
}
}
Inherited Objects
Emp_Fulltime:
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for Emp_Fulltime.
///
//Inheriting from the Abstract class
public class Emp_Fulltime : Employee
{
//uses all the properties of the
//Abstract class therefore no
//properties or fields here!
public Emp_Fulltime()
{
}
public override String ID
{
get
{
return id;
}
set
{
id = value;
}
}
public override String FirstName
{
get
{
return fname;
}
set
{
fname = value;
}
}
public override String LastName
{
get
{
return lname;
}
set
{
lname = value;
}
}
//common methods that are
//implemented in the abstract class
public new String Add()
{
return base.Add();
}
//common methods that are implemented
//in the abstract class
public new String Delete()
{
return base.Delete();
}
//common methods that are implemented
//in the abstract class
public new String Search()
{
return base.Search();
}
//common methods that are implemented
//in the abstract class
public new String Update()
{
return base.Update();
}
//abstract method that is different
//from Fulltime and Contractor
//therefore I override it here.
public override String CalculateWage()
{
return "Full time employee " +
base.fname + " is calculated " +
"using the Abstract class...";
}
}
}
Emp_Fulltime2:
using System;
namespace AbstractsANDInterfaces
{
///
/// Summary description for Emp_fulltime2.
///
//Implementing the interface
public class Emp_fulltime2 : IEmployee
{
//All the properties and
//fields are defined here!
protected String id;
protected String lname;
protected String fname;
public Emp_fulltime2()
{
//
// TODO: Add constructor logic here
//
}
public String ID
{
get
{
return id;
}
set
{
id = value;
}
}
public String FirstName
{
get
{
return fname;
}
set
{
fname = value;
}
}
public String LastName
{
get
{
return lname;
}
set
{
lname = value;
}
}
//all the manipulations including Add,Delete,
//Search, Update, Calculate are done
//within the object as there are not
//implementation in the Interface entity.
public String Add()
{
return "Fulltime Employee " +
fname + " added.";
}
public String Delete()
{
return "Fulltime Employee " +
fname + " deleted.";
}
public String Search()
{
return "Fulltime Employee " +
fname + " searched.";
}
public String Update()
{
return "Fulltime Employee " +
fname + " updated.";
}
//if you change to Calculatewage().
//Just small 'w' it will raise
//error as in interface
//it is CalculateWage() with capital 'W'.
public String CalculateWage()
{
return "Full time employee " +
fname + " caluculated using " +
"Interface.";
}
}
}
Code for Testing
Collapse
//This is the sub that tests both
//implementations using Interface and Abstract
private void InterfaceExample_Click(object sender,
System.EventArgs e)
{
try
{
IEmployee emp;
Emp_fulltime2 emp1 = new Emp_fulltime2();
emp = emp1;
emp.ID = "2234";
emp.FirstName= "Rahman" ;
emp.LastName = "Mahmoodi" ;
//call add method od the object
MessageBox.Show(emp.Add().ToString());
//call the CalculateWage method
MessageBox.Show(emp.CalculateWage().ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void cmdAbstractExample_Click(object sender,
System.EventArgs e)
{
Employee emp;
emp = new Emp_Fulltime();
emp.ID = "2244";
emp.FirstName= "Maria" ;
emp.LastName = "Robinlius" ;
MessageBox.Show(emp.Add().ToString());
//call the CalculateWage method
MessageBox.Show(emp.CalculateWage().ToString());
}
Conclusion
In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.
Monday, September 13, 2010
Bind Data Through Linq
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master2"].ConnectionString);
DataClassesDataContext db = new DataClassesDataContext(con);
var q = from empname in db.GetTable()
select empname.empid ;
GridView1.DataSource = q;
GridView1.DataBind();
DataClassesDataContext db = new DataClassesDataContext(con);
var q = from empname in db.GetTable
select empname.empid ;
GridView1.DataSource = q;
GridView1.DataBind();
Labels:
Bind Data Through Linq
Thursday, September 9, 2010
Transaction Isolation Level
I want to tell you about Transaction Isolation Level in SQL Server 6.5 and SQL Server 7.0, what kinds of Transaction Isolation Level exist, and how you can set the appropriate Transaction Isolation Level.
There are four isolation levels:
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE
SQL Server 6.5 supports all of these Transaction Isolation Levels, but has only three different behaviors, because in SQL Server 6.5 REPEATABLE READ and SERIALIZABLE are synonyms. It because SQL Server 6.5 supports only page locking (the row level locking does not fully supported as in SQL Server 7.0) and if REPEATABLE READ isolation level was set, the another transaction cannot insert the row before the first transaction was finished, because page will be locked. So, there are no phantoms in SQL Server 6.5, if REPEATABLE READ isolation level was set.
SQL Server 7.0 supports all of these Transaction Isolation Levels and can separate REPEATABLE READ and SERIALIZABLE.
Let me to describe each isolation level.
read uncommitted
When it's used, SQL Server not issue shared locks while reading data. So, you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level. It ensures only that a physically corrupt data will not be read.
read committed
This is the default isolation level in SQL Server. When it's used, SQL Server will use shared locks while reading data. It ensures that a physically corrupt data will not be read and will never read data that another application has changed and not yet committed, but it does not ensure that the data will not be changed before the end of the transaction.
repeatable read
When it's used, the dirty reads and nonrepeatable reads cannot occur. It means that locks will be placed on all data that is used in a query, and another transactions cannot update the data.
This is the definition of nonrepeatable read from SQL Server Books Online:
nonrepeatable read
When a transaction reads the same row more than one time, and between the
two (or more) reads, a separate transaction modifies that row. Because the
row was modified between reads within the same transaction, each read
produces different values, which introduces inconsistency.
serializable
Most restrictive isolation level. When it's used, then phantom values cannot occur. It prevents other users from updating or inserting rows into the data set until the transaction is complete.
This is the definition of phantom from SQL Server Books Online:
phantom
Phantom behavior occurs when a transaction attempts to select a row that
does not exist and a second transaction inserts the row before the first
transaction finishes. If the row is inserted, the row appears as a phantom
to the first transaction, inconsistently appearing and disappearing.
You can set the appropriate isolation level for an entire SQL Server session by using the SET TRANSACTION ISOLATION LEVEL statement. This is the syntax from SQL Server Books Online:
SET TRANSACTION ISOLATION LEVEL
{
READ COMMITTED
| READ UNCOMMITTED
| REPEATABLE READ
| SERIALIZABLE
}
You can use DBCC USEROPTIONS command to determine the Transaction Isolation Level currently set. This command returns the set options that are active for the current connection. This is the example:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
GO
DBCC USEROPTIONS
GO
This is the result:
Set Option Value
------------------------------ ------------------------------------
textsize 64512
language us_english
dateformat mdy
datefirst 7
isolation level read uncommitted
There are four isolation levels:
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE
SQL Server 6.5 supports all of these Transaction Isolation Levels, but has only three different behaviors, because in SQL Server 6.5 REPEATABLE READ and SERIALIZABLE are synonyms. It because SQL Server 6.5 supports only page locking (the row level locking does not fully supported as in SQL Server 7.0) and if REPEATABLE READ isolation level was set, the another transaction cannot insert the row before the first transaction was finished, because page will be locked. So, there are no phantoms in SQL Server 6.5, if REPEATABLE READ isolation level was set.
SQL Server 7.0 supports all of these Transaction Isolation Levels and can separate REPEATABLE READ and SERIALIZABLE.
Let me to describe each isolation level.
read uncommitted
When it's used, SQL Server not issue shared locks while reading data. So, you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level. It ensures only that a physically corrupt data will not be read.
read committed
This is the default isolation level in SQL Server. When it's used, SQL Server will use shared locks while reading data. It ensures that a physically corrupt data will not be read and will never read data that another application has changed and not yet committed, but it does not ensure that the data will not be changed before the end of the transaction.
repeatable read
When it's used, the dirty reads and nonrepeatable reads cannot occur. It means that locks will be placed on all data that is used in a query, and another transactions cannot update the data.
This is the definition of nonrepeatable read from SQL Server Books Online:
nonrepeatable read
When a transaction reads the same row more than one time, and between the
two (or more) reads, a separate transaction modifies that row. Because the
row was modified between reads within the same transaction, each read
produces different values, which introduces inconsistency.
serializable
Most restrictive isolation level. When it's used, then phantom values cannot occur. It prevents other users from updating or inserting rows into the data set until the transaction is complete.
This is the definition of phantom from SQL Server Books Online:
phantom
Phantom behavior occurs when a transaction attempts to select a row that
does not exist and a second transaction inserts the row before the first
transaction finishes. If the row is inserted, the row appears as a phantom
to the first transaction, inconsistently appearing and disappearing.
You can set the appropriate isolation level for an entire SQL Server session by using the SET TRANSACTION ISOLATION LEVEL statement. This is the syntax from SQL Server Books Online:
SET TRANSACTION ISOLATION LEVEL
{
READ COMMITTED
| READ UNCOMMITTED
| REPEATABLE READ
| SERIALIZABLE
}
You can use DBCC USEROPTIONS command to determine the Transaction Isolation Level currently set. This command returns the set options that are active for the current connection. This is the example:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
GO
DBCC USEROPTIONS
GO
This is the result:
Set Option Value
------------------------------ ------------------------------------
textsize 64512
language us_english
dateformat mdy
datefirst 7
isolation level read uncommitted
Labels:
Transaction Isolation Level
Wednesday, September 8, 2010
textbox value should not be more than 14 character and take only integer value
//textbox onblur Event
asp:TextBox ID="TextBox1" runat="server" onblur="Checktextboxlenth(this);">/asp:TextBox>
//.js file
function ValidateCCNum(ccNum)
{
var ccno = ccNum.value;
if(ccno == "")
{
return true;
}
if(isNaN(ccno))
{
alert("Credit card number should be numeric");
ccNum.value="";
ccNum.focus();
return false;
}
if(ccno.length < 14 || ccno.length >18)
{
alert("Credit card number should have 14-18 digits length");
ccNum.value="";
ccNum.focus();
return false;
}
return true;
}
asp:TextBox ID="TextBox1" runat="server" onblur="Checktextboxlenth(this);">/asp:TextBox>
//.js file
function ValidateCCNum(ccNum)
{
var ccno = ccNum.value;
if(ccno == "")
{
return true;
}
if(isNaN(ccno))
{
alert("Credit card number should be numeric");
ccNum.value="";
ccNum.focus();
return false;
}
if(ccno.length < 14 || ccno.length >18)
{
alert("Credit card number should have 14-18 digits length");
ccNum.value="";
ccNum.focus();
return false;
}
return true;
}
text box will not take more than 5 character
//.js file
function Checktextboxlenth(ccNum)
{
var ccno = ccNum.value;
if(ccno.length < 0 || ccno.length >5)
{
alert("length cant acces 5 character");
return false ;
}
return true;
}
////onpageload
btnId1.Attributes.Add("onclick", "Checktextboxlenth(TextBox1)");
function Checktextboxlenth(ccNum)
{
var ccno = ccNum.value;
if(ccno.length < 0 || ccno.length >5)
{
alert("length cant acces 5 character");
return false ;
}
return true;
}
////onpageload
btnId1.Attributes.Add("onclick", "Checktextboxlenth(TextBox1)");
Thursday, September 2, 2010
Tuesday, August 17, 2010
Find number of columns in a table in sql server 2000 and 2005 also
select count(*) NoOfColumns from SYSCOLUMNS
WHERE id= (Select id from SYSOBJECTS where name = 'emp')
WHERE id= (Select id from SYSOBJECTS where name = 'emp')
What is live lock and deadlock? what is Lock escalation?
In SQL Server Live Lock occurs when read transactions are
applied on table which prevents write transaction to wait
indefinitely and Deadlocking occurs when two user processes
have locks on separate objects and each process is trying to
acquire a lock on the object that the other process has.
Lock escalation is the process of converting a lot of low
level locks (like row locks, page locks) into higher level
locks (like table locks).
applied on table which prevents write transaction to wait
indefinitely and Deadlocking occurs when two user processes
have locks on separate objects and each process is trying to
acquire a lock on the object that the other process has.
Lock escalation is the process of converting a lot of low
level locks (like row locks, page locks) into higher level
locks (like table locks).
What is OPENXML in SQL Server?
OPENXML can parse the xml data in SQL server very efficiently in SQL Server. OpenXML primarily gives the ability to insert XML data to the relational database, however we can query the data too using OpenXML. We need to specify the path of the xml element using xpath.
Labels:
What is OPENXML in SQL Server?
Monday, August 16, 2010
What is SQL Profiler what is the use of it?
SQl Profiler is a tool provided by SQL Server, which can
capture the queries, procedures executed on the database.
It also capture all the details like user, m/c, input
parameters, time of execution etc. This is very helpful
while bebugging any query / procedure
capture the queries, procedures executed on the database.
It also capture all the details like user, m/c, input
parameters, time of execution etc. This is very helpful
while bebugging any query / procedure
here id col have primary key and identity id name 1 a 2 b 3 c 4 d delete 2nd row then o/p will be id name 1 a 3 c 4 d next inssert 2nd row and i want o/p will be id name 1 a 2 e 3 c 4 d
set identity_insert order1 on
insert into order1(id,name) values(2,'insertedat2')
insert into order1(id,name) values(2,'insertedat2')
Monday, August 9, 2010
Session Expire and Redirect to Login Page
The basic idea for this is to have your authentication cookie + session expire at the same time. The automatic behaviour of asp.net would be to take you back to the defined login page. The "slidingExpiration" attribute on the auth cookie would need to be 'true' to keep extending it's life while the session is active.
system.web>
sessionstate mode="InProc" cookieless="false" timeout="20" />
authentication mode="Forms">
forms name=".SAMPLESITEAUTH" loginUrl="~/Login.aspx" protection="All" timeout="20" slidingExpiration="true" path="/" cookieless="UseCookies">
/authentication>
/system.web>
The slidingExpiration on your cookie doesn't work the way you hope. ASP.NET won't refresh the expiry on the cookie with every request; rather it does that only once every half-the-value-of-timeout minutes. I.e. if you set timeout="20", it only refreshes the cookie every ten minutes.
system.web>
sessionstate mode="InProc" cookieless="false" timeout="20" />
authentication mode="Forms">
forms name=".SAMPLESITEAUTH" loginUrl="~/Login.aspx" protection="All" timeout="20" slidingExpiration="true" path="/" cookieless="UseCookies">
/authentication>
/system.web>
The slidingExpiration on your cookie doesn't work the way you hope. ASP.NET won't refresh the expiry on the cookie with every request; rather it does that only once every half-the-value-of-timeout minutes. I.e. if you set timeout="20", it only refreshes the cookie every ten minutes.
Wednesday, August 4, 2010
Transpose In sql server(Its uses for convert Column to Rows and Rows to column)
As known SQL Server 2000 need some dynamic sqls to convert rows to columns or vice versa. PIVOT and UNPIVOT relational operator did the job of converting rows to columns and columns to rows respectively.we can transpose values from rows to columns in sql server 2005 using PIVOT relational operator,
Ex Of Transpose:
create table #t (
id int identity(1,1),
AJAN int,
AFEB int,
AMAR int,
FJAN int,
FFEB int,
FMAR int
)
insert into #t (AJAN,AFEB,AMAR,FJAN,FFEB,FMAR) values (1,2,3,4,5,6)
insert into #t (AJAN,AFEB,AMAR,FJAN,FFEB,FMAR) values (11,12,13,14,15,16)
select * from #t
select
id,
'A'+c as amonth,
sum(case when c1='A' then val else 0 end) as aval,
'F'+c as fmonth,
sum(case when c1='F' then val else 0 end) as fval
from (
select id, val, substring(col,1,1) as c1, substring(col,2,3) as c
from #t
unpivot (val for col in (AJAN,AFEB,AMAR,FJAN,FFEB,FMAR)) up
) t
group by id,c
order by id,c
Ex Of Transpose:
create table #t (
id int identity(1,1),
AJAN int,
AFEB int,
AMAR int,
FJAN int,
FFEB int,
FMAR int
)
insert into #t (AJAN,AFEB,AMAR,FJAN,FFEB,FMAR) values (1,2,3,4,5,6)
insert into #t (AJAN,AFEB,AMAR,FJAN,FFEB,FMAR) values (11,12,13,14,15,16)
select * from #t
select
id,
'A'+c as amonth,
sum(case when c1='A' then val else 0 end) as aval,
'F'+c as fmonth,
sum(case when c1='F' then val else 0 end) as fval
from (
select id, val, substring(col,1,1) as c1, substring(col,2,3) as c
from #t
unpivot (val for col in (AJAN,AFEB,AMAR,FJAN,FFEB,FMAR)) up
) t
group by id,c
order by id,c
SQL Server Data Transformation Services (DTS)
INTRODUCTION:
Microsoft released Data Transformation Services (DTS) along with SQL Server 7.0. A very powerful, easy to use, graphical tool for importing, exporting and transforming data, which is only available as a costly add-on in other RDBMS products like Oracle. Prior to SQL Server 7.0, all we had was BCP, which is powerful indeed, but not as friendly and functionally rich as DTS. DTS was made robust and dramatically improved with the release of SQL Server 2000, as more and more DBAs and developers started using DTS for building various data loading and transformation solutions. It wouldn't be an exaggeration to say that DTS is one of the most popular ETL (Extract, Transform and Load) tools currently in use. Not bad for a tool that's been around for just about four years.
INTRODUCTION:
If you need to get data into or out of SQL Server, either as a one-off or on a regular basis, there are several ways to achieve this. However in many situations the best solution is to use the excellent DTS (Data Transformation Services) application included with SQL Server 2000 or the replacement SQL Server Integration Services (SSIS) in SQL Server 2005.
DTS/SSIS are large and complex applications, however they are also extremely powerful and consequently we use them for most data conversion tasks, even when neither the source nor the destination is SQL Server!
In addition to transferring data they can also be used to transform or modify the data during the import process. For example a single import file may be used to update multiple tables within the database.
Examples
Examples of some of the tasks that can be undertaken using DTS/SSIS include....
Importing .csv data files from a separate computer.
Importing data from existing Access database.
Exporting SQL data to an Excel spreadsheet.
Exporting data to csv files.
Copy data from one SQL Server to another.
Specific Example
One use to which we have employed DTS for was for importing new and updated works orders from a third party computer system. Data from the other computer was placed in .csv files at a predefined location on the network. We wrote a DTS system that :
Validated the folder structure to ensure that the expected directories were present.
Checked the validated folder to see if any new files were ready for importing.
Located the first csv file of Address data to import.
Validated the incoming raw Address data and imported it into a temporary table.
Processed all address updates, modifying existing data in the main Address table.
Processed all additions, adding new records to the same Address table.
Located the first csv file of Works Order data to import.
Validated the incoming raw Works Order data and imported it into a temporary table.
Process all works order updates, modifying existing data in the main Works Order table.
Process all additions, adding new records to the same Works Order table.
Re-named the processed files to include the date that they were processed on.
Moved the re-named csv files to a separate archive directory.
Cycle back to stage 2 to see if there are any other files to import.
Create a csv file of updated Works Orders with their revised statuses.
Create a csv file of Invoices for completed Works Orders.
Transferred the created csv files using FTP to the client's UNIX server.
Microsoft released Data Transformation Services (DTS) along with SQL Server 7.0. A very powerful, easy to use, graphical tool for importing, exporting and transforming data, which is only available as a costly add-on in other RDBMS products like Oracle. Prior to SQL Server 7.0, all we had was BCP, which is powerful indeed, but not as friendly and functionally rich as DTS. DTS was made robust and dramatically improved with the release of SQL Server 2000, as more and more DBAs and developers started using DTS for building various data loading and transformation solutions. It wouldn't be an exaggeration to say that DTS is one of the most popular ETL (Extract, Transform and Load) tools currently in use. Not bad for a tool that's been around for just about four years.
INTRODUCTION:
If you need to get data into or out of SQL Server, either as a one-off or on a regular basis, there are several ways to achieve this. However in many situations the best solution is to use the excellent DTS (Data Transformation Services) application included with SQL Server 2000 or the replacement SQL Server Integration Services (SSIS) in SQL Server 2005.
DTS/SSIS are large and complex applications, however they are also extremely powerful and consequently we use them for most data conversion tasks, even when neither the source nor the destination is SQL Server!
In addition to transferring data they can also be used to transform or modify the data during the import process. For example a single import file may be used to update multiple tables within the database.
Examples
Examples of some of the tasks that can be undertaken using DTS/SSIS include....
Importing .csv data files from a separate computer.
Importing data from existing Access database.
Exporting SQL data to an Excel spreadsheet.
Exporting data to csv files.
Copy data from one SQL Server to another.
Specific Example
One use to which we have employed DTS for was for importing new and updated works orders from a third party computer system. Data from the other computer was placed in .csv files at a predefined location on the network. We wrote a DTS system that :
Validated the folder structure to ensure that the expected directories were present.
Checked the validated folder to see if any new files were ready for importing.
Located the first csv file of Address data to import.
Validated the incoming raw Address data and imported it into a temporary table.
Processed all address updates, modifying existing data in the main Address table.
Processed all additions, adding new records to the same Address table.
Located the first csv file of Works Order data to import.
Validated the incoming raw Works Order data and imported it into a temporary table.
Process all works order updates, modifying existing data in the main Works Order table.
Process all additions, adding new records to the same Works Order table.
Re-named the processed files to include the date that they were processed on.
Moved the re-named csv files to a separate archive directory.
Cycle back to stage 2 to see if there are any other files to import.
Create a csv file of updated Works Orders with their revised statuses.
Create a csv file of Invoices for completed Works Orders.
Transferred the created csv files using FTP to the client's UNIX server.
Session Expire and Redirect to login Page specify after Some Time Period
Context.Response.AppendHeader("Refresh",
Convert.ToString(Session.Timeout = 10) + "; URL=Login.aspx" );
Convert.ToString(Session.Timeout = 10) + "; URL=Login.aspx" );
Wednesday, July 28, 2010
Fetch Master Page value
Page mypage = (Page)this.Page;
MasterPage mp = (MasterPage)mypage.Master;
Label lab = (Label)mp.FindControl("lblVersionHeader");
MasterPage mp = (MasterPage)mypage.Master;
Label lab = (Label)mp.FindControl("lblVersionHeader");
Labels:
Fetch Master Page value
Update Query with join
// Without condition
UPDATE C INNER JOIN A ON C.Empid = A.Empid SET A.Empname =C.Empname
//With Condition
UPDATE C INNER JOIN A ON C.Empid = A.Empid SET A.Empname = C.Empname
WHERE (((A.Empname)="w"));
UPDATE C INNER JOIN A ON C.Empid = A.Empid SET A.Empname =C.Empname
//With Condition
UPDATE C INNER JOIN A ON C.Empid = A.Empid SET A.Empname = C.Empname
WHERE (((A.Empname)="w"));
Labels:
Update Query with join
Bind Combo Through XML
XmlDocument xml = new XmlDocument();
// xml.LoadXml(@"c:\abc.xml"); // suppose that myXmlString contains "..."
xml.Load(@"c:\abc.xml");
XmlNodeList xnList = xml.SelectNodes("/NewDataSet/Table");
foreach (XmlNode xn in xnList)
{
string firstName = xn["Sno"].InnerText;
string lastName = xn["CustomerName"].InnerText;
DropDownList1.Items.Add(lastName);
DropDownList1.Items[0].Value = firstName;
}
// xml.LoadXml(@"c:\abc.xml"); // suppose that myXmlString contains "..."
xml.Load(@"c:\abc.xml");
XmlNodeList xnList = xml.SelectNodes("/NewDataSet/Table");
foreach (XmlNode xn in xnList)
{
string firstName = xn["Sno"].InnerText;
string lastName = xn["CustomerName"].InnerText;
DropDownList1.Items.Add(lastName);
DropDownList1.Items[0].Value = firstName;
}
Labels:
Bind Combo Through XML
Fetch Value Through UserControl (.ascx file)
//ADC is a user controlName wich we will add in @response directive
//Ex:(Inline Code) %@ Register TagName ="ABC" TagPrefix ="ABC" Src="~/WebUserControl.ascx"%>
after that you can add where u want......
ABC:ABC ID="ADC" runat="server" />
.cs (Code Behind)
WebUserControl we;
we = (WebUserControl)this.FindControl("ADC");
TextBox txtuser = (TextBox)we.FindControl("txtname");
TextBox txtpassword = (TextBox)we.FindControl("txtPassword");
//Ex:(Inline Code) %@ Register TagName ="ABC" TagPrefix ="ABC" Src="~/WebUserControl.ascx"%>
after that you can add where u want......
ABC:ABC ID="ADC" runat="server" />
.cs (Code Behind)
WebUserControl we;
we = (WebUserControl)this.FindControl("ADC");
TextBox txtuser = (TextBox)we.FindControl("txtname");
TextBox txtpassword = (TextBox)we.FindControl("txtPassword");
Transaction in .Net(Insert Data through Stored Procedure)
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
SqlTransaction tran=null ;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
try
{
con.Open();
tran=con.BeginTransaction();
cmd = new SqlCommand("InserData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Name", txtName.Text.Trim().Replace("'", "''"));
cmd.Parameters.AddWithValue("dept_id", ddldept.SelectedValue);
cmd.Parameters.AddWithValue("Contact", txtContact.Text.Trim().Replace("'", "''"));
cmd.Transaction = tran;
cmd.ExecuteNonQuery();
tran.Commit();
}
catch
{
tran.Rollback();
con.Close();
}
finally { con.Close(); }
SqlTransaction tran=null ;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
try
{
con.Open();
tran=con.BeginTransaction();
cmd = new SqlCommand("InserData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Name", txtName.Text.Trim().Replace("'", "''"));
cmd.Parameters.AddWithValue("dept_id", ddldept.SelectedValue);
cmd.Parameters.AddWithValue("Contact", txtContact.Text.Trim().Replace("'", "''"));
cmd.Transaction = tran;
cmd.ExecuteNonQuery();
tran.Commit();
}
catch
{
tran.Rollback();
con.Close();
}
finally { con.Close(); }
Bind GridView Common Function
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
SqlTransaction tran=null ;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
public void BindGridview(GridView gr, string table, string sorting)
{
adp = new SqlDataAdapter("Select * from " + table + " order by " + sorting ,con );
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
gr.DataSource = ds.Tables[0];
gr.DataBind();
}
else
{ //Empty grid view
}
}
SqlTransaction tran=null ;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
public void BindGridview(GridView gr, string table, string sorting)
{
adp = new SqlDataAdapter("Select * from " + table + " order by " + sorting ,con );
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
gr.DataSource = ds.Tables[0];
gr.DataBind();
}
else
{ //Empty grid view
}
}
Labels:
Bind GridView Common Function
Bind DropDown Common Function
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
SqlTransaction tran=null ;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
public void filldropdown(DropDownList ddl, string table, string DataTextField, string DataValueField)
{
adp = new SqlDataAdapter("Select " + DataValueField + "," + DataTextField + " from " + table + " order by '" + DataTextField + "' ", con);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
ddl.Items.Add(ds.Tables[0].Rows[i][DataTextField].ToString());
ddl.Items[i + 1].Value = ds.Tables[0].Rows[i][DataValueField].ToString();
}
}
}
SqlTransaction tran=null ;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
public void filldropdown(DropDownList ddl, string table, string DataTextField, string DataValueField)
{
adp = new SqlDataAdapter("Select " + DataValueField + "," + DataTextField + " from " + table + " order by '" + DataTextField + "' ", con);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
ddl.Items.Add(ds.Tables[0].Rows[i][DataTextField].ToString());
ddl.Items[i + 1].Value = ds.Tables[0].Rows[i][DataValueField].ToString();
}
}
}
Labels:
Bind DropDown Common Function
Saturday, July 3, 2010
Sum Amt and Max date of each employer
SELECT tblCustomer.Name, tblCustomer.Address, tblCustomer.Email, TblInvoice.Amt,Dateofpurchase
FROM tblCustomer INNER JOIN
TblInvoice ON tblCustomer.Cid = TblInvoice.Cid
order by TblInvoice.Cid
compute max(TblInvoice.DateOfpurchase),sum(TblInvoice.Amt) by TblInvoice.Cid
FROM tblCustomer INNER JOIN
TblInvoice ON tblCustomer.Cid = TblInvoice.Cid
order by TblInvoice.Cid
compute max(TblInvoice.DateOfpurchase),sum(TblInvoice.Amt) by TblInvoice.Cid
Friday, June 25, 2010
Wednesday, June 16, 2010
What is .Net Web Service?
Web service is the way to publish application's function on web that can be accessible to the rest of the world.
Web services are the components that can be used by other applications
ASP.NET offers easy way to develop web services, just precede the functions with a special WebMethod ()> attribute in order them to work as Web Service.
Web services are discovered using UDDI directory services.
Web services are built on XML standard and use SOAP protocol that allows them to communicate across different platforms and programming languages.
Web services easily manage to work across corporate firewalls as they use HTTP protocol which is firewall friendly.
Web services platform elements are
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)
The web services are built on internet standards that are not platform or language specific.
The .Net framework provides in-built classes to build and consume web services.
The components offered by web services are reusable.
The examples of web service components can be shipment tracking, translation utility, weather forecasting, sports scores etc.
Web services are the components that can be used by other applications
ASP.NET offers easy way to develop web services, just precede the functions with a special WebMethod ()> attribute in order them to work as Web Service.
Web services are discovered using UDDI directory services.
Web services are built on XML standard and use SOAP protocol that allows them to communicate across different platforms and programming languages.
Web services easily manage to work across corporate firewalls as they use HTTP protocol which is firewall friendly.
Web services platform elements are
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)
The web services are built on internet standards that are not platform or language specific.
The .Net framework provides in-built classes to build and consume web services.
The components offered by web services are reusable.
The examples of web service components can be shipment tracking, translation utility, weather forecasting, sports scores etc.
Labels:
What is .Net Web Service?
Thursday, June 10, 2010
Delete Duplicate Data through single select query.
with t as
(
select * , row_number() over (partition by empid order by empid) as rank from emp
)
delete from t where rank>1
(
select * , row_number() over (partition by empid order by empid) as rank from emp
)
delete from t where rank>1
Wednesday, June 2, 2010
XML Nodes by Name
//Xml
Names>
name>
firstname>John
lastname>Smith
/Name>
name>
firstname>James
lastname>White
/Name>
/Names>
//C#
XmlDocument xml = new XmlDocument();
xml.Load(myXmlString); // suppose that myXmlString contains "... "
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
Names>
name>
firstname>John
lastname>Smith
/Name>
name>
firstname>James
lastname>White
/Name>
/Names>
//C#
XmlDocument xml = new XmlDocument();
xml.Load(myXmlString); // suppose that myXmlString contains "
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
Labels:
Select XML Nodes by Name
Wednesday, April 28, 2010
Transaction in sqlserver
begin tran
begin try
insert into a(id) values('a')
insert into a1 values('sdf','adsf1212121',10012121)
commit tran
print'commit'
end try
begin catch
print'rollback'
rollback tran
end catch
begin try
insert into a(id) values('a')
insert into a1 values('sdf','adsf1212121',10012121)
commit tran
print'commit'
end try
begin catch
print'rollback'
rollback tran
end catch
Labels:
Transaction in sqlserver
Monday, April 26, 2010
Static Classes
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.
Labels:
Static Classes
STUFF vs REPLACE in Asp.net
STUFF - Deletes a specified length of characters and inserts another set of characters at a specified starting point.
SELECT STUFF('abcdef', 2, 3, 'ijklmn')
GO
Here is the result set:
---------
aijklmnef
REPLACE - Replaces all occurrences of the second given string expression in the first string expression with a third expression.
SELECT REPLACE('abcdefghicde','cde','xxx')
GO
Here is the result set:
------------
abxxxfghixxx
SELECT STUFF('abcdef', 2, 3, 'ijklmn')
GO
Here is the result set:
---------
aijklmnef
REPLACE - Replaces all occurrences of the second given string expression in the first string expression with a third expression.
SELECT REPLACE('abcdefghicde','cde','xxx')
GO
Here is the result set:
------------
abxxxfghixxx
Labels:
STUFF vs REPLACE in Asp.net
DDL, DML, DCL and TCL Commands
DML
DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.
SELECT – Retrieves data from a table
INSERT - Inserts data into a table
UPDATE – Updates existing data into a table
DELETE – Deletes all records from a table
DDL
DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.
CREATE – Creates objects in the database
ALTER – Alters objects of the database
DROP – Deletes objects of the database
TRUNCATE – Deletes all records from a table and resets table identity to initial value.
DCL
DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.
GRANT – Gives user’s access privileges to database
REVOKE – Withdraws user’s access privileges to database given with the GRANT command
TCL
TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.
COMMIT – Saves work done in transactions
ROLLBACK – Restores database to original state since the last COMMIT command in transactions
SAVE TRANSACTION – Sets a savepoint within a transaction
DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.
SELECT – Retrieves data from a table
INSERT - Inserts data into a table
UPDATE – Updates existing data into a table
DELETE – Deletes all records from a table
DDL
DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.
CREATE – Creates objects in the database
ALTER – Alters objects of the database
DROP – Deletes objects of the database
TRUNCATE – Deletes all records from a table and resets table identity to initial value.
DCL
DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.
GRANT – Gives user’s access privileges to database
REVOKE – Withdraws user’s access privileges to database given with the GRANT command
TCL
TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.
COMMIT – Saves work done in transactions
ROLLBACK – Restores database to original state since the last COMMIT command in transactions
SAVE TRANSACTION – Sets a savepoint within a transaction
Labels:
DCL and TCL Commands,
DDL,
DML
Saturday, April 24, 2010
Get Vs Post Method
Get Vs Post Method to send data to the server
Get and Post are methods used to send data to the server:
With the Get method, the browser appends the data onto
the URL. With the Post method, the data is sent
as "standard input."
Use GET:
- during development for debugging purposes (although in ASP.NET it's
also easy to see what has been sent through POST).
- if you want your visitors to be able to bookmark the submitted pages
- if you want to refer to submitted pages using hyperlinks
Use POST:
- for forms with password fields
- for large forms or forms with large text fields
Please note that web forms in ASP.NET use POST by default.
It can be changed into GET, but only for small forms. Web forms can post a lot
of data, especially when ViewState is involved.
Get and Post are methods used to send data to the server:
With the Get method, the browser appends the data onto
the URL. With the Post method, the data is sent
as "standard input."
Use GET:
- during development for debugging purposes (although in ASP.NET it's
also easy to see what has been sent through POST).
- if you want your visitors to be able to bookmark the submitted pages
- if you want to refer to submitted pages using hyperlinks
Use POST:
- for forms with password fields
- for large forms or forms with large text fields
Please note that web forms in ASP.NET use POST by default.
It can be changed into GET, but only for small forms. Web forms can post a lot
of data, especially when ViewState is involved.
Labels:
Get Vs Post Method
Monday, April 19, 2010
Jquery Events
Events Jquery
.bind()
Event Handler Attachment
Attach a handler to an event for the elements.
.blur()
Form Events, Forms
Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
.change()
Form Events, Forms
Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
.click()
Mouse Events
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
.dblclick()
Mouse Events
Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
.delegate()
Event Handler Attachment
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
.die()
Event Handler Attachment
Remove all event handlers previously attached using .live() from the elements.
.error()
Browser Events
Bind an event handler to the "error" JavaScript event.
event.currentTarget
Event Object
The current DOM element within the event bubbling phase.
event.data
Event Object
Contains the optional data passed to jQuery.fn.bind when the current executing handler was bound.
event.isDefaultPrevented()
Event Object
Returns whether event.preventDefault() was ever called on this event object.
event.isImmediatePropagationStopped()
Event Object
Returns whether event.stopImmediatePropagation() was ever called on this event object.
event.isPropagationStopped()
Event Object
Returns whether event.stopPropagation() was ever called on this event object.
event.pageX
Event Object
The mouse position relative to the left edge of the document.
event.pageY
Event Object
The mouse position relative to the top edge of the document.
event.preventDefault()
Event Object
If this method is called, the default action of the event will not be triggered.
event.relatedTarget
Event Object
The other DOM element involved in the event, if any.
event.result
Event Object
This attribute contains the last value returned by an event handler that was triggered by this event, unless the value was undefined.
event.stopImmediatePropagation()
Event Object
Prevents other event handlers from being called.
event.stopPropagation()
Event Object
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
event.target
Event Object
The DOM element that initiated the event.
event.timeStamp
Event Object
This attribute returns the number of milliseconds since January 1, 1970, when the event is triggered.
event.type
Event Object
Describes the nature of the event.
event.which
Event Object
For key or button events, this attribute indicates the specific button or key that was pressed.
.focus()
Form Events, Forms
Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
.focusin()
Keyboard Events, Mouse Events
Bind an event handler to the "focusin" JavaScript event.
.focusout()
Keyboard Events, Mouse Events
Bind an event handler to the "focusout" JavaScript event.
.hover()
Mouse Events
Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
.keydown()
Keyboard Events
Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
.keypress()
Keyboard Events
Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
.keyup()
Keyboard Events
Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
.live()
Event Handler Attachment
Attach a handler to the event for all elements which match the current selector, now or in the future.
.load()
Document Loading
Bind an event handler to the "load" JavaScript event.
.mousedown()
Mouse Events
Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
.mouseenter()
Mouse Events
Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
.mouseleave()
Mouse Events
Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
.mousemove()
Mouse Events
Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
.mouseout()
Mouse Events
Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
.mouseover()
Mouse Events
Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
.mouseup()
Mouse Events
Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
.one()
Event Handler Attachment
Attach a handler to an event for the elements. The handler is executed at most once per element.
jQuery.proxy()
Event Handler Attachment, Utilities
Takes a function and returns a new one that will always have a particular context.
.ready()
Document Loading
Specify a function to execute when the DOM is fully loaded.
.resize()
Browser Events
Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
.scroll()
Browser Events
Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
.select()
Form Events, Forms
Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
.submit()
Form Events, Forms
Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
.toggle()
Basics, Mouse Events
Bind two or more handlers to the matched elements, to be executed on alternate clicks.
.trigger()
Event Handler Attachment
Execute all handlers and behaviors attached to the matched elements for the given event type.
.triggerHandler()
Event Handler Attachment
Execute all handlers attached to an element for an event.
.unbind()
Event Handler Attachment
Remove a previously-attached event handler from the elements.
.undelegate()
Event Handler Attachment
Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.
.unload()
Document Loading
Bind an event handler to the "unload" JavaScript e
.bind()
Event Handler Attachment
Attach a handler to an event for the elements.
.blur()
Form Events, Forms
Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
.change()
Form Events, Forms
Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
.click()
Mouse Events
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
.dblclick()
Mouse Events
Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.
.delegate()
Event Handler Attachment
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
.die()
Event Handler Attachment
Remove all event handlers previously attached using .live() from the elements.
.error()
Browser Events
Bind an event handler to the "error" JavaScript event.
event.currentTarget
Event Object
The current DOM element within the event bubbling phase.
event.data
Event Object
Contains the optional data passed to jQuery.fn.bind when the current executing handler was bound.
event.isDefaultPrevented()
Event Object
Returns whether event.preventDefault() was ever called on this event object.
event.isImmediatePropagationStopped()
Event Object
Returns whether event.stopImmediatePropagation() was ever called on this event object.
event.isPropagationStopped()
Event Object
Returns whether event.stopPropagation() was ever called on this event object.
event.pageX
Event Object
The mouse position relative to the left edge of the document.
event.pageY
Event Object
The mouse position relative to the top edge of the document.
event.preventDefault()
Event Object
If this method is called, the default action of the event will not be triggered.
event.relatedTarget
Event Object
The other DOM element involved in the event, if any.
event.result
Event Object
This attribute contains the last value returned by an event handler that was triggered by this event, unless the value was undefined.
event.stopImmediatePropagation()
Event Object
Prevents other event handlers from being called.
event.stopPropagation()
Event Object
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
event.target
Event Object
The DOM element that initiated the event.
event.timeStamp
Event Object
This attribute returns the number of milliseconds since January 1, 1970, when the event is triggered.
event.type
Event Object
Describes the nature of the event.
event.which
Event Object
For key or button events, this attribute indicates the specific button or key that was pressed.
.focus()
Form Events, Forms
Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.
.focusin()
Keyboard Events, Mouse Events
Bind an event handler to the "focusin" JavaScript event.
.focusout()
Keyboard Events, Mouse Events
Bind an event handler to the "focusout" JavaScript event.
.hover()
Mouse Events
Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
.keydown()
Keyboard Events
Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
.keypress()
Keyboard Events
Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
.keyup()
Keyboard Events
Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
.live()
Event Handler Attachment
Attach a handler to the event for all elements which match the current selector, now or in the future.
.load()
Document Loading
Bind an event handler to the "load" JavaScript event.
.mousedown()
Mouse Events
Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
.mouseenter()
Mouse Events
Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
.mouseleave()
Mouse Events
Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
.mousemove()
Mouse Events
Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.
.mouseout()
Mouse Events
Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.
.mouseover()
Mouse Events
Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.
.mouseup()
Mouse Events
Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.
.one()
Event Handler Attachment
Attach a handler to an event for the elements. The handler is executed at most once per element.
jQuery.proxy()
Event Handler Attachment, Utilities
Takes a function and returns a new one that will always have a particular context.
.ready()
Document Loading
Specify a function to execute when the DOM is fully loaded.
.resize()
Browser Events
Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.
.scroll()
Browser Events
Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.
.select()
Form Events, Forms
Bind an event handler to the "select" JavaScript event, or trigger that event on an element.
.submit()
Form Events, Forms
Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
.toggle()
Basics, Mouse Events
Bind two or more handlers to the matched elements, to be executed on alternate clicks.
.trigger()
Event Handler Attachment
Execute all handlers and behaviors attached to the matched elements for the given event type.
.triggerHandler()
Event Handler Attachment
Execute all handlers attached to an element for an event.
.unbind()
Event Handler Attachment
Remove a previously-attached event handler from the elements.
.undelegate()
Event Handler Attachment
Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.
.unload()
Document Loading
Bind an event handler to the "unload" JavaScript e
Labels:
Jquery Events
What is the difference between JavaScript and jQuery?
What is the difference between JavaScript and jQuery?
JavaScript is a language whereas jQuery is a library written using JavaScript.
What does dollar Sign ($) means in JQuery?
Dollar Sign is nothing but it's an alias for JQuery.
Over here $ sign can be replaced with jQuery...
JavaScript is a language whereas jQuery is a library written using JavaScript.
What does dollar Sign ($) means in JQuery?
Dollar Sign is nothing but it's an alias for JQuery.
Over here $ sign can be replaced with jQuery...
LINQ :: Language Integrated Query
you can find several descriptions of Language Integrated Query (LINQ), such as these:
LINQ is a uniform programming model for any kind of data. LINQ enables you to query and manipulate data with a consistent model that is independent from data sources.
LINQ is just another tool for embedding SQL queries into code.
LINQ is yet another data abstraction layer.
All of these descriptions are somewhat correct, but they each focus on just a single aspect. LINQ can do a lot more than just embed SQL queries, it is much easier to use than a “uniform programming model,” and it is far from being just another set of rules for modeling data.
LINQ is a methodology that simplifies and unifies the implementation of any kind of data access. LINQ does not force you to use a specific architecture; it facilitates the implementation of several existing architectures for accessing data. As with every tool, it can be used in both good and in bad ways. To get the most out of LINQ, you will have to master it.
Today, data managed by a program can belong to different data domains: an array, an object graph, an XML document, a database, a text file, a registry key, an e-mail message, Simple Object Access Protocol (SOAP) message content, a Microsoft Office Excel file…. The list is long.
Each data domain has its own specific access model. When you have to query a database, you typically use SQL. You navigate XML data with Document Object Model (DOM) or XQuery. You iterate an array and build algorithms to navigate an object graph. You use specific application programming interfaces (APIs) to access other data domains, such as an Office Excel file, an e-mail message, or the Microsoft Windows registry. In the end, you have different programming models to access different data sources.
The unification of data access techniques into a single comprehensive model has been tried in many ways. For example, there are Open Database Connectivity (ODBC) providers that allow you to query an Excel file as you would a Windows Management Instrumentation (WMI) repository. However, with this approach you use an SQL-like language to access data represented through a relational model. Sometimes data is naturally represented more effectively in a hierarchical or graphical model instead of a relational one. Moreover, if the data model is not tied to the language, you probably have to manage different type systems. All these differences create an “impedance mismatch” between data and code. LINQ tries to solve these issues, offering a uniform way to access and manage data without forcing the adoption of a “one size fits all” model. LINQ leverages commonalities between the operations in these data models instead of flattening the different structures between them.
LINQ is a uniform programming model for any kind of data. LINQ enables you to query and manipulate data with a consistent model that is independent from data sources.
LINQ is just another tool for embedding SQL queries into code.
LINQ is yet another data abstraction layer.
All of these descriptions are somewhat correct, but they each focus on just a single aspect. LINQ can do a lot more than just embed SQL queries, it is much easier to use than a “uniform programming model,” and it is far from being just another set of rules for modeling data.
LINQ is a methodology that simplifies and unifies the implementation of any kind of data access. LINQ does not force you to use a specific architecture; it facilitates the implementation of several existing architectures for accessing data. As with every tool, it can be used in both good and in bad ways. To get the most out of LINQ, you will have to master it.
Today, data managed by a program can belong to different data domains: an array, an object graph, an XML document, a database, a text file, a registry key, an e-mail message, Simple Object Access Protocol (SOAP) message content, a Microsoft Office Excel file…. The list is long.
Each data domain has its own specific access model. When you have to query a database, you typically use SQL. You navigate XML data with Document Object Model (DOM) or XQuery. You iterate an array and build algorithms to navigate an object graph. You use specific application programming interfaces (APIs) to access other data domains, such as an Office Excel file, an e-mail message, or the Microsoft Windows registry. In the end, you have different programming models to access different data sources.
The unification of data access techniques into a single comprehensive model has been tried in many ways. For example, there are Open Database Connectivity (ODBC) providers that allow you to query an Excel file as you would a Windows Management Instrumentation (WMI) repository. However, with this approach you use an SQL-like language to access data represented through a relational model. Sometimes data is naturally represented more effectively in a hierarchical or graphical model instead of a relational one. Moreover, if the data model is not tied to the language, you probably have to manage different type systems. All these differences create an “impedance mismatch” between data and code. LINQ tries to solve these issues, offering a uniform way to access and manage data without forcing the adoption of a “one size fits all” model. LINQ leverages commonalities between the operations in these data models instead of flattening the different structures between them.
Tuesday, April 13, 2010
Validate TextBox
//Take one text box and call the function obblur method........
asp:TextBox ID="txt" runat="server" onblur="ValidateCCNum(this);">
//.js File
function ValidateCCNum(ccNum)
{
var ccno = ccNum.value;
if(ccno == "")
{
return true;
}
if(isNaN(ccno))
{
alert("Credit card number should be numeric");
ccNum.value="";
ccNum.focus();
return false;
}
if(ccno.length < 14 || ccno.length >18)
{
alert("Credit card number should have 14-18 digits length");
ccNum.value="";
ccNum.focus();
return false;
}
return true;
}
asp:TextBox ID="txt" runat="server" onblur="ValidateCCNum(this);">
//.js File
function ValidateCCNum(ccNum)
{
var ccno = ccNum.value;
if(ccno == "")
{
return true;
}
if(isNaN(ccno))
{
alert("Credit card number should be numeric");
ccNum.value="";
ccNum.focus();
return false;
}
if(ccno.length < 14 || ccno.length >18)
{
alert("Credit card number should have 14-18 digits length");
ccNum.value="";
ccNum.focus();
return false;
}
return true;
}
Labels:
Validate TextBox
Monday, April 12, 2010
Deleted Trigger
//titleauthor is foreigntable
//titles Primary Table......When you delete data from Primary automatically delete data from foreign table.....
//title_id is a Unique key in both table..
//deleted is a magic Table where delete data is stored...
create trigger delcascadetrig
on titleauthor
for delete
as
delete delcascadetrig
from titles, deleted
where titles.title_id = deleted.title_id
//titles Primary Table......When you delete data from Primary automatically delete data from foreign table.....
//title_id is a Unique key in both table..
//deleted is a magic Table where delete data is stored...
create trigger delcascadetrig
on titleauthor
for delete
as
delete delcascadetrig
from titles, deleted
where titles.title_id = deleted.title_id
Labels:
Deleted Trigger
Saturday, April 3, 2010
Bind GridView with Datatable
Add a GridView control, two lable controls, three textbox controls and button control in the page
Create datatable structure.
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "username";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
Insert data into datatable.
private void AddDataToTable(string username,string firstname,string lastname,DataTable myTable)
{
DataRow row;
row = myTable.NewRow();
row["id"] = Guid.NewGuid().ToString();
row["username"] = username;
row["firstname"] = firstname;
row["lastname"] = lastname;
myTable.Rows.Add(row);
}
//Add data to datatable which we have created
protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Trim() == "")
{
this.lblTips.Text = "You must fill a username.";
return;
}
else
{
AddDataToTable(parameter);
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.txtUserName.Text = "";
this.lblTips.Text = "";
}
}
// Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable myDt = new DataTable();
myDt = CreateDataTable();
this.GridView1.DataSource = myDt
this.GridView1.DataBind();
}
}
Create datatable structure.
private DataTable CreateDataTable()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "id";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "username";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "firstname";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "lastname";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
Insert data into datatable.
private void AddDataToTable(string username,string firstname,string lastname,DataTable myTable)
{
DataRow row;
row = myTable.NewRow();
row["id"] = Guid.NewGuid().ToString();
row["username"] = username;
row["firstname"] = firstname;
row["lastname"] = lastname;
myTable.Rows.Add(row);
}
//Add data to datatable which we have created
protected void btnAdd_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Trim() == "")
{
this.lblTips.Text = "You must fill a username.";
return;
}
else
{
AddDataToTable(parameter);
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.txtUserName.Text = "";
this.lblTips.Text = "";
}
}
// Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable myDt = new DataTable();
myDt = CreateDataTable();
this.GridView1.DataSource = myDt
this.GridView1.DataBind();
}
}
Labels:
Bind GridView with Datatable
Saturday, March 27, 2010
Update , Delete inside the grid view
//Take one Grid View and Bind all Column and take column inside templatefiels inside ItemTemplate and EditItemTemplate ALSO FOR Generate text box for updation
I have remove starting tag from the Html Tag because blog can't take Html field like Starting tag .....
asp:Label ID="lblId" runat="server" Visible="false" Text='%# Bind("Id") %>'>/asp:Label>
//Web.config file
add name="Master" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
SqlDataAdapter adp;
DataSet ds; SqlCommand cmd;
void fillgridview()
{
adp = new SqlDataAdapter("Select a.id,a.Name,a.Age,a.RollNo,b.Subject from student a join subject b on a.subjectid=b.subjectid", con);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
else { }
ds.Dispose();
adp = null;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgridview();
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
con.Open();
cmd = new SqlCommand("delete from student where id= " + lbnlid.Text + " ", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgridview();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
con.Open();
cmd = new SqlCommand("update student set Name= '"+txtName.Text +"' where id= "+lbnlid.Text+" ", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fillgridview();
}
I have remove starting tag from the Html Tag because blog can't take Html field like Starting tag .....
asp:Label ID="lblId" runat="server" Visible="false" Text='%# Bind("Id") %>'>/asp:Label>
//Web.config file
add name="Master" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
SqlDataAdapter adp;
DataSet ds; SqlCommand cmd;
void fillgridview()
{
adp = new SqlDataAdapter("Select a.id,a.Name,a.Age,a.RollNo,b.Subject from student a join subject b on a.subjectid=b.subjectid", con);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
else { }
ds.Dispose();
adp = null;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgridview();
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
con.Open();
cmd = new SqlCommand("delete from student where id= " + lbnlid.Text + " ", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgridview();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
con.Open();
cmd = new SqlCommand("update student set Name= '"+txtName.Text +"' where id= "+lbnlid.Text+" ", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fillgridview();
}
Labels:
Delete inside the grid view,
Update
Disable Browser back Button in asp.net
//Make one .js file
function goNewWin()
{
window.open("default2.aspx",'TheNewpop','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
self.close()
}
//Call that function and give the page name there which page you don't want browser back button....
function goNewWin()
{
window.open("default2.aspx",'TheNewpop','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
self.close()
}
//Call that function and give the page name there which page you don't want browser back button....
Gridview sorting,paging
//Take one Grid View and Bind all the column through
//hdnSort is a Hidden field take one hidden field also.
asp:TemplateField
ItemTemplate and give the sort expression also and paging and sorting also true the property of GridView...
//Web.config file
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//in aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData(string sorting)
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{
}
sql = "Select student_id,last_name,first_name,Score from Student order by " + sorting;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables.Count == 0)
{
//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }
}
//call Bind Method where you bind the Gridview perform all operation
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData("student_id");
}
}
//for sorting
private string ConvertSortDirectiontoSql(SortDirection sort)
{
string newSortDirection = string.Empty;
switch (sort)
{
case SortDirection.Ascending:
newSortDirection = "Asc";
hdnSort.Value = "Asc";
break;
case SortDirection.Descending:
newSortDirection = "Desc";
hdnSort.Value = "Desc";
break;
}
return newSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//hdnSort is a Hidden field take one hidden field also.
if (hdnSort.Value.Length == 0 || hdnSort.Value == "Desc")
e.SortDirection = SortDirection.Ascending;
else
e.SortDirection = SortDirection.Descending;
string sorting = e.SortExpression + " " + ConvertSortDirectiontoSql(e.SortDirection);
if (hdnSort.Value.Length == 0)
hdnSort.Value = "Desc";
bindData(sorting);
}
//for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindData("student_id desc");
}
//hdnSort is a Hidden field take one hidden field also.
asp:TemplateField
ItemTemplate and give the sort expression also and paging and sorting also true the property of GridView...
//Web.config file
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//in aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData(string sorting)
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{
}
sql = "Select student_id,last_name,first_name,Score from Student order by " + sorting;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables.Count == 0)
{
//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }
}
//call Bind Method where you bind the Gridview perform all operation
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData("student_id");
}
}
//for sorting
private string ConvertSortDirectiontoSql(SortDirection sort)
{
string newSortDirection = string.Empty;
switch (sort)
{
case SortDirection.Ascending:
newSortDirection = "Asc";
hdnSort.Value = "Asc";
break;
case SortDirection.Descending:
newSortDirection = "Desc";
hdnSort.Value = "Desc";
break;
}
return newSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//hdnSort is a Hidden field take one hidden field also.
if (hdnSort.Value.Length == 0 || hdnSort.Value == "Desc")
e.SortDirection = SortDirection.Ascending;
else
e.SortDirection = SortDirection.Descending;
string sorting = e.SortExpression + " " + ConvertSortDirectiontoSql(e.SortDirection);
if (hdnSort.Value.Length == 0)
hdnSort.Value = "Desc";
bindData(sorting);
}
//for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindData("student_id desc");
}
Subscribe to:
Posts (Atom)