State Management in ASP.NET Basic concepts

(I). Client Side State Management

This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

1). View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

2). Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

3). Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

4). Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

5). Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

Advantages:-
a. Better Scalability:
b. Supports multiple Web servers:



(II). Server Side State Management

1). Application State - Application State allows to store application specific information is available to all pages, regardless of which user requests a page.

Three Events you can use to initialize Application variables

a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.

b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.

c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.


2). Session State – Session State information is available to all pages opened by a user during a single visit. You can use session state to store user-specific information.

Advantages:-
a. Better security
b. Reduced bandwidth

More Info:-
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx
http://www.dotnetfunda.com/articles/article61.aspx

LIST Search using Anonymous Methods

An Anonymous method is a new feature introduced in C# 2.0 to have methods without name. which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. Prior to C# 2.0, a developer would have to define a separate method when needing to execute a callback using a delegate. But in C# 2.0 Anonymous method uses the keyword, delegate, instead of a method name and contain the body of the method.

Following sample code contains a C# List Searching and filtering technique by using Anonymous method.

public class Employee
{
private string name;
private double salary;

public string Name
{
get { return name; }
set { name = value; }
}

public double Salary
{
get { return salary; }
set { salary = value; }
}
}

Employee emp1 = new Employee();
emp1.Name = "Jeff";
emp1.Salary = 200000.00;

Employee emp2 = new Employee();
emp2.Name = "Anne";
emp2.Salary = 500000.00;

Employee emp3 = new Employee();
emp3.Name = "Jane";
emp3.Salary = 900000.00;

List empList = new List();
empList.Add(emp1);
empList.Add(emp2);
empList.Add(emp3);

//Search the Employees those salaries are larger than specified value.
List newEmpList = new List(empList).FindAll(
delegate(Employee emp)
{
return emp.Salary > 400000.00;
}
);

Use Activator.CreateInstance() to Create Objects Dynamically

You can use Activator.CreateInstance() method to create objects from String type of Assembly Name. The following code stub demonstrate how to use that method.

namespace ActivatorTest
{
public interface IActBase
{
void Execute();
}
}

namespace ActivatorTest
{
public class ActChild1 : IActBase
{
public void Execute()
{
Console.WriteLine("Activator Child 1");
}
}
}

namespace ActivatorTest
{
public class ActChild2 : IActBase
{
public void Execute()
{
Console.WriteLine("Activator Child 2");
}
}
}

namespace ActivatorTest
{
public class Program
{
static void Main(string[] args)
{
const string AssemblyName = "ActivatorTest.ActChild2";
//The AssemblyName can be loaded through the configuration based
// on your requirement. Here its hard coded.
IActBase instance = (IActBase)Activator.CreateInstance(Type.GetType(AssemblyName));
instance.Execute();
}
}
}
For More Info:- http://www.knowdotnet.com/articles/activator_createinstance.html

Fixing SSIS Deployment Issues

SQL Server Integration Service (SSIS) is a platform for building enterprise level data integration and transformations solutions in Microsoft SQL Server. For example updating a SQL Database from an external source such as XML Source, Excel source and there are many more.

There are enough articles available on internet regarding SSIS package development and deployment, but hard to find exact solution regarding SSIS issues.

The purpose of this article is to provide solutions regarding few SSIS deployment issues in SQL Server 2005.

Issue 1:-

Error Message:-

The SQL Job fails with following Error:-
“The command line parameters are invalid. The step failed.”……

Description:-

This error occurred due to SQL Server 2005 Agent Bug. When you deployed your DTSX package as a SQL Server job and define DataSources [Ex:- DB Connection, Excel Connection] in SQL Job property window, it will automatically generate a Command Line string. [You can view it by Job Properties: - Edit "Step":- "General":- Select "Command line" Window]
When you try to run the SQL Job, the generated Command Line string cannot be recognized due to Command line String validation failure.

Solutions:-

1) The slashes should be backslashes and the quotes need to be escaped (i.e. \").

2) Use a Config file for your DTSX package. You need to parameterize all DataSource Connections and define them in a Config file. So you don’t need to edit “DataSources“under SQL Job Properties. This will avoid generating unnecessary Command Line String under SQL Job. [Recommended]

This Bug has been fixed in MS SQL Server 2008.


Issue 2 (In 64 Bit Machine):-

Error Message:-

The SQL Job fails with following Error:-
- Pre-execute (Error)
Messages
Error 0xc0202009: {F1B3B35C-FAE3-48F6-A169-4E4D8D99F9B6}: An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available. Source: "Microsoft JET Database Engine" Hresult: 0x80004005 Description: "Unspecified error".
(SQL Server Import and Export Wizard)

Error 0xc020801c: Data Flow Task: The AcquireConnection method call to the connection manager "DestinationConnectionExcel" failed with error code 0xC0202009.
(SQL Server Import and Export Wizard)……………………………………………

Description:-

The above error occurred due to limitation of 64 Bit environment since some .NET Framework data providers and some native OLE DB providers may not be available in 64-bit versions. When you try to execute DTSX Package as “SQL Server Integration Services Package” type in SQL Job window, by default it will try to use DTExec.exe available in 64 Bit environment. So it gets failed if your DTSX package contains any OLE DB/etc connections which are not available in 64 Bit environment.

Solution:-

Change SSIS package the setting to False from
Visual Studio Solution->Properties->Debug->64Bit .

Additionally you need to run you’re your DTSX package by using the 32 Bit DTExec.exe executable by default available in "C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe" path.

In order run it as a SQL Job you need to schedule it as an Operating System Command by changing the SQL Job Properties-> Steps -> Edit Etep-> Change the Type as “Operation System (CmdExec) ”

And the Command should be similar to following sample Command:-

"C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\dtexec.exe" /FILE "C:\ImportClientInfoPackage.dtsx" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E /CONFIGFILE "C:\ImportClientInfo.dtsConfig"

XSLT: Useful Method implementations for XML Transformation

XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents. XSLT stands for XSL Transformations.

XSLT is used for the transformation of XML documents into other XML documents. In details the original xml document will not be changed; rather, a new XML document will be created according to specified schema document (XSLT Document) based on the data content of an existing Original Xml doc.

Following sample codes are very useful for you to write Common XML Transformation Component.

The following method used to create an Xml Document by Serializing the given Object in to a memory stream. The passed Object should be a XML [Serializable] class.

/// -summary
/// Used to serialize given object to a XML Document that is used for XML Transformation
/// -summary
/// "templateDto"- Serializable Object
/// "mailType"- Enum used to identify particular mail category
/// returns-Transformed HTML message
public static string GenerateMailContent(Object templateDto,MailType mailType)
{
if (templateDto == null)
{
throw new CbsException(BaseErrorCode.ArgumentIsNull);
}
XmlDocument mailContent = new XmlDocument();
//Initialize Memery stream by loading Memory stream size from Config file.
MemoryStream memoryStream =
new MemoryStream(int.Parse(CbsConfigurationManager.GetConfigurationSection
(CbsConfigurationConstants.CbsConfigurationSection, CbsConstant.MemoryStreamSize),
CbsCultureManager.NumberFormat));
XmlSerializer xmlSerializer = new XmlSerializer(templateDto.GetType());
// Serialize object to a memory stream.
xmlSerializer.Serialize(memoryStream, templateDto);
// Set seeker at begining of stream
memoryStream.Seek(0, 0);
// Load memory stream to xml document
mailContent.Load(memoryStream);

// Transform mailContent XML to a specified format.
return TransformData(mailType, mailContent);
}


The following method is used to transform given XML document according to specified XSLT document and return the newly generated document.

/// -summary
/// Used to create the XML content of the Email using XSLT template.
/// -summary
/// param name="mailType"- Email Category
/// param name="xmlContent"-XML document content.
/// returns- XML content
public static string TransformData(MailType mailType, XmlDocument xmlContent)
{
// Load XSL transformation
XslCompiledTransform xform = new XslCompiledTransform();

// Load Absolute path for the XSLT Mail Template folder.
string mailTemplatePath =
CbsConfigurationManager.GetConfigurationSection
(CbsConfigurationConstants.CbsConfigurationSection, CbsConstant.EmailTemplatesPath);

// Switch for different XSLT mail template documents.
switch (mailType)
{
case MailType.RarSwitch:
xform.Load(mailTemplatePath + PollerSwitchXslt);
break;

case MailType.DeliveryUnsucesfull:
xform.Load(mailTemplatePath + DeliveryUnsucesfullStoresXslt);
break;
case MailType.HpSwitch:
xform.Load(mailTemplatePath + RiDMSwitchXslt);
break;
}

XmlNodeReader reader = new XmlNodeReader(xmlContent);
XmlUrlResolver resolver = new XmlUrlResolver();

// Execute and Cache results.
XmlDocument resultsDoc = new XmlDocument();
XPathNavigator resultsNav = resultsDoc.CreateNavigator();

// using makes sure that we flush the writer at the end
using (XmlWriter writer = resultsNav.AppendChild())
{
xform.Transform(reader, null, writer, resolver);
}
resultsNav.MoveToChild(XPathNodeType.Element);
return resultsNav.OuterXml;
}

WMI Queries on Win32 Environment

Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on remote computers but WMI also supplies management data to other parts of the operating system and products.

Sample WMI Query to Uninstall Softwares in Win32 Environment.

ObjectQuery oq = new ObjectQuery("Select * from Win32_Product where Name like 'Microsoft Office%'");
ManagementObjectSearcher allProducts = new ManagementObjectSearcher(oq);

ManagementObjectCollection MngObjeColl = allProducts.Get();
foreach (ManagementObject product in MngObjeColl)
{
foreach (PropertyData property in product.Properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.Value);
}
// Uninstall the poduct.
object res = product.InvokeMethod("Uninstall", null);
Console.WriteLine("-Successfully Uninstalled-\n");
}

You can find sample available Win32 Classes:-
http://msdn.microsoft.com/en-us/library/aa394084(VS.85).aspx

Reading and Writing Files in C#

string writeFilePath = @"C:\PlugIn\Dimuthu.txt";
string readFilePath = @"C:\PlugIn\Nuwan.txt";

/// Used to read from one file and write to an another file using
/// Byte Array.
FileStream openFile = new FileStream(readFilePath, FileMode.Open, FileAccess.ReadWrite);
FileStream writeFile = new FileStream(writeFilePath, FileMode.Create, FileAccess.Write);
BufferedStream outFile = new BufferedStream(writeFile);

int count;
byte[] buffer;
buffer = new byte[4096];
while ((count = openFile.Read(buffer, 0, buffer.Length)) > 0)
{
outFile.Write(buffer, 0, count);
outFile.Flush();
}

/// Used to write a Large File for 20 seconds.
/// This will be helpful for performance testing.
FileStream fileStream = new FileStream(writeFilePath, FileMode.Create, FileAccess.Write);
DateTime end = DateTime.Now.AddSeconds(20.0);
StreamWriter file = new StreamWriter(fileStream);

while (DateTime.Now < end)
{
file.WriteLine(count);
file.Flush();
Console.WriteLine(count);
count++;
}
file.Close();


/// Used to create a zero byte text file.
string folderPath = @"C:\Test";
Directory.CreateDirectory(folderPath);
File.Create(folderPath + "\\Game.txt", 1);

Base64 Encoding and Decoding

Following Base64Encode() method can be used Encode any file in to a Base64 string and write it in to a given file path. The Base64Decode() method can be used to generate original file from given Base64 String.

Basically Base64 can be used to encode a any file such as jpeg, avi, dat, txt, etc in to a String format.

private string Base64Encode()
{
string strBase64;
FileStream fileStream = new FileStream(msiFilePath, FileMode.Open, FileAccess.Read,
FileShare.Read);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
strBase64 = Convert.ToBase64String(buffer);
return strBase64;
}

private void Base64Decode(string filePath, string base64String)
{
FileStream fileStream = null;
try
{
byte[] plugInObjectBytes = Convert.FromBase64String(base64String);
fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
fileStream.Write(plugInObjectBytes, 0, plugInObjectBytes.Length);
fileStream.Flush();
}
catch (Exception ex)
{
if (File.Exists(filePath))
{
fileStream = null;
File.Delete(filePath);
}
throw;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
}