Wednesday, October 28, 2009

SOAP and BINARY formatter serialization

using System;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
secreteClass obj = new secreteClass();
obj.MyAccNum = 123321456;
obj.Passwd="newPassword";
//// SOAP FORMATTER
SoapFormatter formatter = new SoapFormatter();
Stream objfilestream = new FileStream("c:\\Myserialzed.xml", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(objfilestream, obj);
objfilestream.Close();
//deserialization
Stream objreadstream = new FileStream("c:\\Myserialzed.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
secreteClass objSecrete2 = (secreteClass)formatter.Deserialize(objreadstream);


int Myaccno = objSecrete2.MyAccNum;
Response.Write ("AccNo:{0} " + Myaccno.ToString());
//// BINARY FORMATTER
BinaryFormatter bformatter = new BinaryFormatter();
Stream objbfilestream = new FileStream("c:\\Myserialzed.txt", FileMode.Create, FileAccess.Write, FileShare.None);
bformatter.Serialize(objbfilestream, obj);
objbfilestream.Close();
//deserialization
Stream objBreadstream = new FileStream("c:\\Myserialzed.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
secreteClass objBSecrete2 = (secreteClass)bformatter.Deserialize(objBreadstream);
}
}
[Serializable]
public class secreteClass
{
private int myaccountnumber = 0;
[NonSerialized()]
private string password = "qwerty321";
public int MyAccNum
{
get
{
return myaccountnumber;
}
set
{
myaccountnumber = value;
}
}
public string Passwd
{
get
{
return password;
}
set
{
password = value;
}
}
public secreteClass()
{


}
public void SerializedMethod()
{
}

}

Thursday, October 22, 2009

Delay sigining

Delay signing?

During development process you will need strong name keys to be exposed to developer which is not a good practice from security aspect point of view.In such situations you can assign the key later on and during development you an use delay signing

Following is process to delay sign an assembly:

First obtain your string name keys using SN.EXE.

Annotate the source code for the assembly with two custom attributes from System.Reflection: AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute, which indicates that delay signing, is being used by passing true as a parameter to its constructor.
For example as shown below:

C#
using System;
using System.Reflection;
[assembly:AssemblyKeyFileAttribute("TestPublicKey.snk")]
[assembly:AssemblyDelaySignAttribute(true)]
namespace DelaySign
{
public class Test { }
}


When this attribute is used on an assembly, space is reserved for the signature which is later filled by a signing tool such as the Sn.exe utility. Delayed signing is used when the author of the assembly does not have access to the private key that will be used to generate the signature, as in [assembly:AssemblyDelaySignAttribute(true)].

The compiler inserts the public key into the assembly manifest and reserves space in the PE file
for the full strong name signature. The real public key must be stored while the assembly is built
so that other assemblies that reference this assembly can obtain the key to store in their own
assembly reference.
• Because the assembly does not have a valid strong name signature, the verification of
that signature must be turned off. You can do this by using the –Vr option with the
Strong Name tool. The following example turns off verification for an assembly called
myAssembly.dll.
Sn –Vr myAssembly.dll
• Just before shipping, you submit the assembly to your organization signing authority
for the actual strong name signing using the –R option with the Strong Name tool. The
following example signs an assembly called myAssembly.dll with a strong name using the
sgKey.snk key pair.
Sn -R myAssembly.dll sgKey.snk
The compiler inserts the public key into the assembly manifest and reserves space in the PE file for the full strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assembly reference.

Because the assembly does not have a valid strong name signature, the verification of that signature must be turned off. You can do this by using the -Vr option with the Strong Name tool.The following example turns off verification for an assembly called myAssembly.dll.

Just before shipping, you submit the assembly to your organization's signing authority for the actual strong name signing using the -R option with the Strong Name tool. The following example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair.

Tuesday, October 6, 2009

Reflaction and example

Reflection

To read method, prop, construtor, etc from assembly.

We can create assembly at run time

When we use c# dll in vb, and two variables a and A can also be used using reflection

Create new class liabrary (new project in c#)

Public class class1

{

Private int32 eno , es;

Private string en,ed;

Public class1()

{

}

Public class1 ( int32 a, string b, string c, int32 d)

{

Eno = a; ed= c; en=b; es = d;

}

Public int32 p_empno

{

Get

{

Return eno;

}

Set

{

Eno =value;

}

}

Public string p_ename

{

Get

{

Return en;

}

Set

{

En =value;

}

}

Public string p_eadd

{

Get

{

Return ed;

}

Set

{

Ed =value;

}

}

Public int32 p_esal

{

Get

{

Return es;

}

Set

{

Es = value;

}

}

Public int32 callall()

{

Return p_sal * 10 /100;

}

Public int32 calded(int32 pf, int32 tax)

{

Return p_esal * pf/100 + p_esal * tax / 100;

}

}

Compile this class file

Create new web site in c#

Default.aspx;

Code

Using System.reflection;

Type typ = null;

Pageload()

{

Assembly asm = assembly.loadfile(“d:\\classliabrary24 \\classlibrary24\\bin\\debug\\classlibrary24.dll”); //path of dll file

Type[] typs = asm.gettypes; //element of class may be more than one

Typ = asm.gettype(typs[0].tostring());

}

Design

Button1 button2 button3 button4

Button1()

{

Constructorinfo[] ci = typ.getconstructors();

//all constructors in class lib

Int32 I;

For(i=0; i<>

{

Response.write(ci[i].tostring() + “
”);

}

}

Button2()

{

Propertyinfo[] pi = typ.getproperty();

Int32 I;

For(i=0;i

{

Resoponse.write(pi[i].tostring() + “
”);

}

}

Button3()

{

Methodinfo[] mi = typ.getmethods();

Int32 I;

For(i=0;i

{

Response.write(mi[i].tostring() + “
”);

}

}

Button4()

{

Constructorinfo[] ci = typ.getconstructors();

Object obj = activator.createinstance(typ);

//Ci[0].invoke(obj,null); //calling default constructor

Object[] ar = new object[4];

Ar[0] = 10;

Ar[1]=”vikas”;

Ar[2]=”#2223”;

Ar[3]=12000;

Ci[1].invoke(obj,ar);

Propertyinfo[] pi = typ.getproperties();

Response.write(pi[0].getvalue(obj,null).tostring() + “
”);

//to read from property getvalue used

Response.write(pi[1].getvalue(obj,null).tostring() + “
”);

Response.write(pi[2].getvalue(obj,null).tostring() + “
”);

}

Add one more button5

Button5()

{

Propertyinfo[] pi = typ.getproperties();

Object obj = activator.createinstanse(typ);

Pi[0].setvalue(obj,101,null);

Pi[1].setvalue(obj,”aman”,null);

Pi[2].setvalue(obj,”#23adsf”,null);

Pi[3].setvalue(obj,23000,null);

Methodinfo[] mi = typ.getmethods();

Int32 k = (int32)(mi[8].invoke(obj,null));

Response.write(k.tostring() + “
”);

Object[] ar = new object[2];

Ar[0]=20;

Ar[1]=30;

Int32 k1 (int32)(mi[9].invoke(obj,ar));

Response.write(k1.tostring());

}

Add new page:




Dll at runtime:

--------------

Default2.aspx:

Textbox1 Button1

Code:

Using system.reflection;

Using system.reflection.emit;

//emit namespace is used for

Pageload()

{

}

Private assembly abc()

{

Assemlyname nam = new assemblyname();

Nam.name = “myfirstasm”;

Assemblybuilder asmbul = appdomain.currentdomain. definedynamicassembly(nam,assemblybuilderaccess.runandsave,”e:\\abc”);

//current area of app where it is running

//assemblybuilderaccess is used for the type of assmb at runtime, run save or both

//very useful for security purpose

Modulebuilder modbul = asmbul.definedynamicmodule (“myfirstasm”,”myfirstasm.dll”);

// for making namespace

Typebuilder typbul = modbul.definetype(“clsabc”,typeattributes.public | typeattributes.class);

//for making class

Type[] ar = new type[]{typeof(int32),typeof(int32)};

//prototype of a method

Methodbuilder metbul = typbul.definemethod(“sum”,methodattribute.public, typeof(int32), ar);

// for making runtime method

Parameterbuilder p1 = metbul.defineparameter(1, parameterattributes.in, “n1”);

Parameterbuilder p2 = metbul.defineparameter(2, parameterattributes.in, ”n2”);

Ilgenerator ilgen = metbul.getilgenerator();

//for generating msil

Ilgen.emit(opcodes.lgarg_1);

//ldarg_1 stores in stack

Ilgen.emit(opcodes.ldarg_2);

Ilgen.emit(opcodes.add);

Ilgen.emit(opcodes.ret);

Typbul.createtype();

Asmbul.save(“myfirstasm.dll”);

Return asmbul;

}

Button1()

{

Assembly asm = abc();

Type typ = asm.gettype(“clsabc”);

Object obj = activator.createinstance(typ);

Object[] ar = new object[2];

Ar[0]=350;

Ar[1]=500;

Int32 k = (int32) ( typ.invokemember(“sum”,bindingflags.invokemethod,null, obj, ar);

//name of method, invoking method, overloading situation, object name, parametr

Textbox1.text = k.tostring();

}

Sunday, October 4, 2009

connection Pooling

­­­Connection Pooling
Default value of Max Pool size is 100.You can set that in SQL Connection String...e.g"Server=(local); ..........; Database=Northwind; Max Pool Size=45; Min Pool Size=10When a connection is opened and a pool is created, multiple connections are added to the pool to bring the connection count to the configured minimum level. Connections can be subsequently added to the pool up to the configured maximum pool count. When the maximum count is reached, new requests to open a connection are queued for a configurable duration.
Creating a Connection Pool
Each connection pool is associated with a specific connection string. By default, the connection pool is created when the first connection with a unique connection string connects to the database. The pool is populated with connections up to the minimum pool size.
Additional connections can be added until the pool reaches the maximum pool size.
The pool remains active as long as any connections remain open, either in the pool or used by an application with a reference to a Connection object that has an open connection.
If a new connection is opened and the connection string does not exactly match an existing pool, a new pool must be created. By using the same connection string, you can enhance the performance and scalability of your application.
In the following C# code fragment, three new DbConnection objects are created, but only two connection pools are required to manage them. Note that the connection strings for conn1 and conn2 differ by the values assigned for User ID, Password, and Min Pool Size connection string options.
DbProviderFactory Factory = DbProviderFactories.GetFactory("DDTek.Oracle");
DbConnection Conn1 = Factory.CreateConnection();
Conn1.ConnectionString = "Host=Accounting;Port=1521;User ID=scott;Password=tiger; " +
"Service Name=ORCL;Min Pool Size=50";

Conn1.Open();
// Pool A is created and filled with connections to the
// minimum pool size

DbConnection Conn2 = Factory.CreateConnection();
Conn2.ConnectionString =
"Host=Accounting;Port=1521;User ID=Jack;Password=quake; " +
"Service Name=ORCL;Min Pool Size=100";

Conn2.Open();
// Pool B is created because the connections strings differ

DbConnection Conn3 = Factory.CreateConnection();
Conn3.ConnectionString =
"Host=Accounting;Port=1521;User ID=scott;Password=tiger; " +
"Service Name=ORCL;Min Pool Size=50";

Conn3.Open();
// Conn3 is assigned an existing connection that was created in
// Pool A when the pool was created for Conn1

Once created, connection pools are not destroyed until the active process ends or the connection lifetime is exceeded. Maintenance of inactive or empty pools involves minimal system overhead.