Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Wednesday, December 29, 2010

Send data through Post Method

///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"] + "
");

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);
}

Monday, December 27, 2010

Create Directory when not Exist

string tempFolder = Request.PhysicalApplicationPath + "Assets\\temp";
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}

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

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;

}

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();
}

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 ! ");

}
}

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);
}

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

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();
}
}

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();

/**/