Tuesday, February 1, 2011

Cloning Object(user defined class) in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;

namespace Namespace
{
///
/// Used to create shallow copy of object
///

public static class Cloner
{
static Dictionary _cachedIL = new Dictionary();

public static T Clone(T myObject)
{
Delegate myExec = null;

if (!_cachedIL.TryGetValue(typeof(T), out myExec))
{
var dymMethod = new DynamicMethod("DoClone", typeof(T), new Type[] { typeof(T) }, true);
var cInfo = myObject.GetType().GetConstructor(new Type[] { });

var generator = dymMethod.GetILGenerator();

var lbf = generator.DeclareLocal(typeof(T));

generator.Emit(OpCodes.Newobj, cInfo);
generator.Emit(OpCodes.Stloc_0);

foreach (var field in myObject.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
// Load the new object on the eval stack... (currently 1 item on eval stack)
generator.Emit(OpCodes.Ldloc_0);
// Load initial object (parameter) (currently 2 items on eval stack)
generator.Emit(OpCodes.Ldarg_0);
// Replace value by field value (still currently 2 items on eval stack)
generator.Emit(OpCodes.Ldfld, field);
// Store the value of the top on the eval stack into the object underneath that value on the value stack.
// (0 items on eval stack)
generator.Emit(OpCodes.Stfld, field);
}

// Load new constructed obj on eval stack -> 1 item on stack
generator.Emit(OpCodes.Ldloc_0);
// Return constructed object. --> 0 items on stack
generator.Emit(OpCodes.Ret);

myExec = dymMethod.CreateDelegate(typeof(Func));

_cachedIL.Add(typeof(T), myExec);
}

return ((Func)myExec)(myObject);
}
}
}

Thursday, July 1, 2010

Save Image in Data Base & Retrieve it on GridView using ASP.Net 2.0

Save Image in Data Base & Retrieve it on GridView using ASP.Net 2.0::

http://docs.google.com/document/pub?id=1IANkP1TeWgE_3pzf1BfrBnJZarqaIXDVJuCHnzkvSqU

Friday, June 18, 2010

Menu Control binded with Site Map

Code for Site Map (Add web1.sitemap before start in your project.)

STr=?xml version="1.0" encoding="utf-8" ?
siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"

siteMapNode url="" title="" description=""
siteMapNode url="" title="Itinerary" description="hi"
siteMapNode url="main.aspx" title="Search" description="Search Itinerary" /
/siteMapNode
siteMapNode url="" title="Password" description="About" >
siteMapNode url="ChangePassword.aspx" title="Change Password" description="Change Password" />

siteMapNode>-->
siteMapNode url="" title="Setup" description="Setup" >
siteMapNode url="Settings.aspx" title="Setup and Config" description="Setup and Config" />
/siteMapNode>

siteMapNode url="" title="About" description="About" >
siteMapNode url="about.aspx" title="Product" description="Product" />
siteMapNode url="http://www.amadeus.in" title="Amadeus" description="Amadeus" />
/siteMapNode>
/siteMapNode>
/siteMap>

****in above code Please put Evry row in <> Brackets, then it works

Then Code for code behind in Menu page

private void CreateMenuControl()
{
Menu1.DataSource = GetSiteMApDataSource();
Menu1.DataBind();
}

private SiteMapDataSource GetSiteMApDataSource()
{
XmlSiteMapProvider xmlsiteMAp = new XmlSiteMapProvider();
System.Collections.Specialized.NameValueCollection myCollection =
new System.Collections.Specialized.NameValueCollection(1);

if (Session["UserRole"].ToString().ToUpper() == "ADMIN")
{
myCollection.Add("siteMapFile", "web.sitemap");
}
else if (Session["UserRole"].ToString().ToUpper() == "USER")
{
myCollection.Add("siteMapFile", "Web2.sitemap");
}

xmlsiteMAp.Initialize("provider", myCollection);
xmlsiteMAp.BuildSiteMap();
SiteMapDataSource siteMap = new SiteMapDataSource();
siteMap.ShowStartingNode = false;
myCollection = null;
if (Session["UserRole"].ToString().ToUpper() == "ADMIN")
{
siteMap.SiteMapProvider = "DefaultSiteMapProvider";
}
else if (Session["UserRole"].ToString().ToUpper() == "USER")
{
siteMap.SiteMapProvider = "MySiteMapProvider";
}

return siteMap;
}

Download server file on Client Side using ASP.net 2.0

private void DownloadFileMSI()
{
string fname = Server.MapPath("PNRExtractor") + "\\PNRExtractor.msi";
Response.ContentType = "application/exe";
Response.AddHeader("content-disposition", "attachment; filename=PNRExtractor.msi");

//System.IO.FileStream sourceFile = new System.IO.FileStream(@"" + fname, System.IO.FileMode.OpenOrCreate);
System.IO.FileStream sourceFile = new System.IO.FileStream(@"" + fname, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
long FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
Response.BinaryWrite(getContent);
}

Thursday, May 13, 2010

Crystal report- Handling multiple values in parameter seperated by(,)

Please follow the link :
1. https://docs.google.com/document/edit?id=1IlBv-F5N0ByQwzyouGqwUiFlQ9DXc5Zi5imAzGAKZcM&hl=en

2. If want to assign Subreport parameter through code then Add Parameter in Main Report ,Create Same type Parameter in Subreport & link it with mail report using report link.

Now Pass the value through code to main report's parameter.

Monday, April 26, 2010

Getting Value of Control inherited by Master Page through Javascript

ddlServiceFee is a serverside drop down list control.
This function enable/ disable other control on selection of values.

https://docs.google.com/document/edit?id=1fcWwbcHUOarvyEmTuZRKQlval6zY3gZMQeSmpmOGkgs#

Wednesday, June 3, 2009

Encrypting or Decripting a file using VB.net 2005

Dim strFileToEncrypt As String
Dim strFileToDecrypt As String
Dim strOutputEncrypt As String
Dim strOutputDecrypt As String
Dim fsInput As System.IO.FileStream
Dim fsOutput As System.IO.FileStream
'Current Index
Public lstIndex As Int16
'*************************
'** Create A Key
'*************************
Public Function CreateKey(ByVal strPassword As String) As Byte()
'Convert strPassword to an array and store in chrData.
Dim chrData() As Char = strPassword.ToCharArray
'Use intLength to get strPassword size.
Dim intLength As Integer = chrData.GetUpperBound(0)
'Declare bytDataToHash and make it the same size as chrData.
Dim bytDataToHash(intLength) As Byte
'Use For Next to convert and store chrData into bytDataToHash.
For i As Integer = 0 To chrData.GetUpperBound(0)
bytDataToHash(i) = CByte(Asc(chrData(i)))
Next
'Declare what hash to use.
Dim SHA512 As New System.Security.Cryptography.SHA512Managed
'Declare bytResult, Hash bytDataToHash and store it in bytResult.
Dim bytResult As Byte() = SHA512.ComputeHash(bytDataToHash)
'Declare bytKey(31). It will hold 256 bits.
Dim bytKey(31) As Byte
'Use For Next to put a specific size (256 bits) of
'bytResult into bytKey. The 0 To 31 will put the first 256 bits
'of 512 bits into bytKey.
For i As Integer = 0 To 31
bytKey(i) = bytResult(i)
Next
Return bytKey 'Return the key.
End Function

Public Function CreateIV(ByVal strPassword As String) As Byte()
'Convert strPassword to an array and store in chrData.
Dim chrData() As Char = strPassword.ToCharArray
'Use intLength to get strPassword size.
Dim intLength As Integer = chrData.GetUpperBound(0)
'Declare bytDataToHash and make it the same size as chrData.
Dim bytDataToHash(intLength) As Byte
'Use For Next to convert and store chrData into bytDataToHash.
For i As Integer = 0 To chrData.GetUpperBound(0)
bytDataToHash(i) = CByte(Asc(chrData(i)))
Next
'Declare what hash to use.
Dim SHA512 As New System.Security.Cryptography.SHA512Managed
'Declare bytResult, Hash bytDataToHash and store it in bytResult.
Dim bytResult As Byte() = SHA512.ComputeHash(bytDataToHash)
'Declare bytIV(15). It will hold 128 bits.
Dim bytIV(15) As Byte
'Use For Next to put a specific size (128 bits) of bytResult into bytIV.
'The 0 To 30 for bytKey used the first 256 bits of the hashed password.
'The 32 To 47 will put the next 128 bits into bytIV.
For i As Integer = 32 To 47
bytIV(i - 32) = bytResult(i)
Next
Return bytIV 'Return the IV.
End Function
'****************************


'** Encrypt/Decrypt File
'****************************
Public Enum CryptoAction
'Define the enumeration for CryptoAction.
ActionEncrypt = 1
ActionDecrypt = 2
End Enum
Public Sub EncryptOrDecryptFile(ByVal strInputFile As String, _
ByVal strOutputFile As String, _
ByVal bytKey() As Byte, _
ByVal bytIV() As Byte, _
ByVal Direction As CryptoAction)
Try 'In case of errors.
'Setup file streams to handle input and output.
fsInput = New System.IO.FileStream(strInputFile, IO.FileMode.Open, IO.FileAccess.Read)
fsOutput = New System.IO.FileStream(strOutputFile, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
fsOutput.SetLength(0) 'make sure fsOutput is empty
'Declare variables for encrypt/decrypt process.
Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing
Dim lngBytesProcessed As Long = 0 'running count of bytes processed
Dim lngFileLength As Long = fsInput.Length 'the input file's length
Dim intBytesInCurrentBlock As Integer 'current bytes being processed
Dim csCryptoStream As CryptoStream
'Declare your CryptoServiceProvider.
Dim cspRijndael As New System.Security.Cryptography.RijndaelManaged
'Setup Progress Bar
' pbStatus.Text = 0
' pbStatus.Maximum = 100
'Determine if ecryption or decryption and setup CryptoStream.
Select Case Direction
Case CryptoAction.ActionEncrypt
csCryptoStream = New CryptoStream(fsOutput, _
cspRijndael.CreateEncryptor(bytKey, bytIV), _
CryptoStreamMode.Write)
Case CryptoAction.ActionDecrypt
csCryptoStream = New CryptoStream(fsOutput, _
cspRijndael.CreateDecryptor(bytKey, bytIV), _
CryptoStreamMode.Write)
End Select
'Use While to loop until all of the file is processed.
While lngBytesProcessed < lngFileLength
'Read file with the input filestream.
intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)
'Write output file with the cryptostream.
csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
'Update lngBytesProcessed
lngBytesProcessed = lngBytesProcessed + _
CLng(intBytesInCurrentBlock)
'Update Progress Bar
' pbStatus.Value = CInt((lngBytesProcessed / lngFileLength) * 100)
End While
'Close FileStreams and CryptoStream.
csCryptoStream.Close()
fsInput.Close()
fsOutput.Close()
Catch e As Exception
MsgBox(e.Message, MsgBoxStyle.Exclamation)
End Try
End Sub

/////Calling function to Encrypt file.

'Encrypted The XML
Dim bytKey As Byte()
Dim bytIV As Byte()
'Send the password to the CreateKey function.
bytKey = CreateKey("soumitra")
'Send the password to the CreateIV function.
bytIV = CreateIV("soumitra")
'Start the encryption.
EncryptOrDecryptFile(Application.StartupPath & "\config.xml", "C:\Foldername\" & txtAgencyId.Text.Trim() & "\config.xml.encrypted", _
bytKey, bytIV, CryptoAction.ActionEncrypt)


/////Calling function to DEcrypt file.
Dim bytKey As Byte()
Dim bytIV As Byte()
'Send the password to the CreateKey function.
bytKey = CreateKey("soumitra")
'Send the password to the CreateIV function.
bytIV = CreateIV("soumitra")
'Start the encryption.
'Application.StartupPath & "\config.xml.encrypted"
EncryptOrDecryptFile(strDecryptPath & "\config.xml.encrypted", Application.StartupPath & "\config.xml", _
bytKey, bytIV, CryptoAction.ActionDecrypt)