Showing posts with label meetu choudhary. Show all posts
Showing posts with label meetu choudhary. Show all posts

Thursday, June 18, 2009

Move Cursor to the Last Index in The Texbox

Code for script section in the head

<script type="text/javascript" language="javascript">
function moveindex() {
var me2 = document.selection.createRange();
me2.moveStart("character", 200);
me2.select();
}
</script>

code for calling the function in the body section

<asp:TextBox ID="TextBox1" runat="server" onfocus="moveindex()"/>


Thanks and Regards
Meetu Choudhary

Wednesday, June 17, 2009

Showing Image Dynamically

This piece of code demonstrate that when we take mouse on a particular image the place holder for the image displays the corresponding image... here goes the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>Meetu Choudhary</title>

Script for head section


<script language="javascript" type="text/javascript">

function showimage(imagename)

{

targetimage.src="images/" + imagename;

}

</script>

</head>

Body will have these contents..


<body>
<table width="694" height="525" border="0">

<tr>

<td width="141" height="95" valign="top">

<img src="images/image1.jpg" onmouseover="showimage('image1.jpg')" width="141" height="93">

</td>

<td width="141">

<img src="images/image2.jpg" width="141" height="93" onmouseover="showimage('image2.jpg')">

</td>

<td width="141">

<img src="images/image3.jpg" width="141" height="93" onmouseover="showimage('image3.jpg')">

</td>

<td width="139">

<img src="images/image4.jpg" width="141" height="93" onmouseover="showimage('image4.jpg')">

</td>

<td width="98">

<img src="images/image5.jpg" width="141" height="93" onmouseover="showimage('image5.jpg')">

</td>

</tr>

<tr>

<td height="424">&nbsp;</td>

<td colspan="3" valign="top">

<img id="targetimage" src="images/image1.jpg" width="420" height="252"/>

</td>

<td>&nbsp;</td>

</tr>

</table>

</body>

</html>


To download the zip folder conating the demo of the article click here



Thanks and Regards

Meetu Choudhary

Thursday, June 11, 2009

Encrypt And Decrypt Using Digital Signatures

Encrypt And Decrypt Using Digital Signatures


Now in continutaion to my earlier artcile the mirroe link of the article here I am going to describe how we can use the digital signatures for the purpose of Encryption and Decryption.

The Following code will show how we can encrypt the plain text.

Encryption


#region Encryption

public string GetEncryptedText(string PlainStringToEncrypt)

{

try

{

string PlainString = PlainStringToEncrypt.Trim();

byte[] cipherbytes = ASCIIEncoding.ASCII.GetBytes(PlainString);

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;

byte[] cipher = rsa.Encrypt(cipherbytes, false);

return Convert.ToBase64String(cipher);

}

catch (Exception e)

{

throw e;

}

}
#endregion

Now once we have encrypted text we need to decrypt it. the following section of code will demonstrate how to decrypt that encrypted text.

Decryption


#region Decryption

public string GetDecryptedText(string EncryptedStringToDecrypt)

{

try

{



try

{

byte[] cipherbytes = Convert.FromBase64String(EncryptedStringToDecrypt);

if (x509_2.HasPrivateKey)

{

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PrivateKey;

byte[] plainbytes = rsa.Decrypt(cipherbytes, false);

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

return enc.GetString(plainbytes);

}

else

{

throw new Exception("Certificate used for has no private key.");

}

}

catch (Exception e)

{

return e.Message;

}

}

catch

{

return EncryptedStringToDecrypt;

}

}
#endregion



Thanks and Regards

Meetu Choudhary

Tuesday, June 9, 2009

How do I specify more than one parameter for my HyperlinkColumn?

How do I specify more than one parameter for my HyperlinkColumn?
================================================================
Many times will developing the applications we come accross the thing that how i can pass more then one parameter in the query string which is genertated by the datagrid or gridviews... once i was developing an application and the same problem came accross at that time i was quite new to ASP.net and was stucked there did lots of googleing and found the answer now today i want to share that piece of code as an example may be i may help you to avoid a bit burdden of yours to find the code

Here i have encoded the querstring or the URL to avoid some unwanted error which are normaly genertaed due to spaces and special characters.
the code follows like

[code]
< asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" >
< Columns >
< asp:TemplateColumn HeaderText="Sample Column" >
< ItemTemplate >
< asp:Hyperlink runat="server" Text=' < %#Container.DataItem("TextVal")% >' NavigateUrl=' < %# "page.aspx?Param1=" & Server.UrlEncode(Container.DataItem("Val1")) & "&Param2=" & Server.UrlEncode(Container.DataItem("Val2"))%>'/>
</itemtemplate >
</asp:TemplateColumn >
</columns >
[/code]




Thanks and regards
Meetu Choudhary

Monday, June 8, 2009

Shortcut Keys of Edit Menu in VS 2008

Check the follwoing Link
http://www.dotnetspider.com/resources/28921-Shortcut-Keys-Edit-Menu-VS.aspx

Organize Usings

Once we have created our class. In that class we use the using statment at the top of the class.To include namespaces in our class. But sometimes we realize after compeleting the code of that calss we have used some extra namespaces which are of no use in th class to remove all those unused using statment. we can use InteliSense in the edit menu. in the submenu of InteliSense we will find the option organize usings. and in its sub menu we hve the options to remove unused usings to sort usings and to remove and sort usings.


Thanks and Regards
Meetu Choudhary

Friday, June 5, 2009

Format document

To format any document (.cs,XML,aspx,HTML etc) in visual studio 2008
use the following key combinations:
To format whole document : ctrl +k ,(followed by) ctrl + d
To format the selection : ctrl +k, (followed by) ctrl +f




Thanks and Regards
Meetu Choudhary

Wednesday, June 3, 2009

Accessing the properties of a digital signature

Accessing the properties of a digital signature



Now once we have selected the certificate. We need to access the properties of the certificate. Here is a small piece of code to access all the properties which may be helpful to us for any context.

before accessing these properties we have to set the certificate object. for that you can get the code from any of the two previous articles.
1. Article link , Mirror link
2. Article link , Mirror link


Now once we have the certificate (X509Certificate2 x509_2;)
we can o with the following code

[code]

///



/// Set All the Properties of the Certificate

///


public Boolean SetProperties()

{

if (x509_2 != null)

{

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;

_PublicKey_Key =_PublicKeyXML = rsa.ToXmlString(false);

//_PrivateKeyXML = rsa.ToXmlString(true );

_PrivateKeyXML=_Private_Key = x509_2.PrivateKey.ToXmlString(false);

_PKeyExchangeAlgorithm = x509_2.PrivateKey.KeyExchangeAlgorithm;

_PublicKey = x509_2.GetPublicKeyString();

//_PublicKey_Key = Convert.ToString(x509_2.PublicKey.Key);

_SerialNumber = x509_2.GetPublicKeyString();

_Thumbprint = x509_2.Thumbprint;

_RawCertDataString = x509_2.GetRawCertDataString();

_FriendlyName = x509_2.FriendlyName;

_HashString = x509_2.GetCertHashString();

_EffectiveDate = x509_2.GetEffectiveDateString();

_ExpirationDate = x509_2.GetExpirationDateString();

_Format = x509_2.GetFormat();

_IssuerName = x509_2.GetIssuerName();

_KeyAlgorithm = x509_2.GetKeyAlgorithm();

_KeyAlgorithmParameters = x509_2.GetKeyAlgorithmParametersString();

_CertName = x509_2.GetName();

_CertSubject = x509_2.Subject;

_CertVersion = x509_2.Version;

_SignatureAlgorithm_Value = x509_2.SignatureAlgorithm.Value;

_SignatureAlgorithm_ToString = x509_2.SignatureAlgorithm.ToString();

_SignatureAlgorithm_FriendlyName = x509_2.SignatureAlgorithm.FriendlyName;

return true;

}

else { return false; }

}

[/code]




Thanks and Regards
Meetu Choudhary

Open Certificate Stores Including Certificates in Token

Open Certificate Stores Including Certificates in Token



In My Previous article Mirror Link I have shown how to open a certificate store (Machine certificate store which is displayed in the Internet Explorer.) but the drawback of that code was it can't open the certificates stored in the token. so here is another method which will overcome the drawback stated above. It will open the certificates of the machine store as well as of the tokens.

[code]
///

/// Opens the Certificate Store of IE including the Certificates in Token

///


/// The variable passed to store the reason if function returns false

/// True if a certificate is selected and false if no certificate is selected

public Boolean OpenStoreToken(ref string popupScript)

{

x509_2 = null;

//Create and Initilaize a variable of x509Store providing the store name and the store location

X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);

//Create X509Certificate2Collection

X509Certificate2Collection col = new X509Certificate2Collection();

//Create X509Certificate2Collection

X509Certificate2Collection sel = new X509Certificate2Collection();

//Create X509Certificate2Enumerator

X509Certificate2Enumerator en;// =new X509Certificate2Enumerator();

//Open the Store for readonly purpose

st.Open(OpenFlags.ReadOnly);

//set the col i.e. X509Certificate2Collection to the collection of the certificates stored in the IE and the Token

col = st.Certificates;

//set the sel i.e. X509Certificate2Collection which actuly displays a dialog box for selecting an X.509 certificate from a certificate collection.

sel = X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection);

if (sel.Count > 0)

{

en = sel.GetEnumerator();

en.MoveNext();

x509_2 = en.Current;

}

st.Close();

if (x509_2 == null)

{

popupScript = "You didn't select a certificate!!!";

return false;

}

else

{

return true;

}

}



[/code]



Thanks and Regards
Meetu Choudhary

Thursday, May 28, 2009

Open Certificate Stores

Open Certificate Stores



I am working on Digital Signatures with ASP.Net. Once in a life time for a programmer we get a chance to work for security or with security and even myself is not an exception . I have to work with digital signatures to achieve security and I searched a lot in internet to achieve what i need and I am still in the process to learn more but in this journey I have found many things but most of them were related to java and applets as I was form .net domain I had to work on it. So here I am Starting the discussion with the first obstacle I met, it is to open a certificate store as of Internet Explorer... I am calling it first as I need not to generate the digital signature as I have them which were already issued by the authorized CA. still if you want to have a look then you can go through the link where i have explained how to create a certificate.. or the mirror link...

Proceeding further... I have encountered two ways to open a certificate store discussing them here..


Method One:



Certfun is a class which i found on the Internet which i don't remember where exactly but i have modified that class as i found that code in vb and i need that in C# so i will paste the code at the end

Limitation:-- This will not open the certificate in the token.

[code]
///

/// Opens the Certificate Store of IE Excluding the Certificates in Token

///


/// The variable passed to store the reason if function returns false

/// True if a certificate is selected and false if no certificate is selected

public Boolean OpenStoreIE(ref string popupScript)

{

x509_2 = null;

//declare a pointer and initilize it with Zero This pointer will hold the value returened by opening the Store

IntPtr hCertStore = IntPtr.Zero;

//declare a pointer and initilize it with Zero This pointer will hold the value returened by selecting the certificate from the store

IntPtr pCertContext = IntPtr.Zero;

//Declare a string and Intilaize it with the store name to open by default it is 'My' Stroe from where we store or install the certificates

string kk = "MY";

//Declaring a StringBuilder Object to hold the NameString of the certificate

StringBuilder NS = new StringBuilder(128);

//To hold the size

int provinfosize = 0;

//Opens the Store and returns a pointer handler of the Store.

hCertStore = CertFun.CertOpenSystemStore(IntPtr.Zero, kk);

//Will returns the pointer handler of the selected certificate

pCertContext = CertFun.CryptUIDlgSelectCertificateFromStore(hCertStore, IntPtr.Zero, "Personal Store", "Please select a PKC12 (.pfx) Certificate and press ok", cf.CRYPTUI_SELECT_LOCATION_COLUMN, 0, IntPtr.Zero);

//Testing if the pointer handler is equal to zero then informing the user that no certificate is selected and exiting the function

if (pCertContext.Equals(IntPtr.Zero))

{

popupScript = "You didn't select a certificate!!!";

//ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "nocert", popupScript, false);

return false;

}

//check certificate is PKCS12

if (!CertFun.CertGetCertificateContextProperty(pCertContext, cf.CERT_KEY_PROV_INFO_PROP_ID, IntPtr.Zero, ref provinfosize))

{

//Check the pointer handler if it is not eqal to zero then

if (!(pCertContext.Equals(IntPtr.Zero)))

{

//free the pointer handler as the certificate is not PKCS12

CertFun.CertFreeCertificateContext(pCertContext);

}

//Display a message and exit from the function

popupScript = "Selected certificate is not PKCS12. Please select a PKCS12 certificate!!!";

//ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "invalidcert", popupScript, false);

return false;



}

else

{

// yes pkcs12

//need not to do anything here

}

//Get Name String for the Certificate into your stringbuilder created above

if ((CertFun.CertGetNameString(pCertContext, cf.CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, IntPtr.Zero, NS, 128)))

{

}

else

{

// Can Display the message here that certificate name failed

//in my case no requirement to display this message

}

//Now store the user selected certificate into the global static variable for later use

x509_2 = new X509Certificate2(pCertContext);

return true;

}
[/code]


CertFun



[code]
using

System;

using

System.Runtime.InteropServices;

using

System.Security.Cryptography;

using

System.Text;

namespace

Secure_Login

{

///

/// Summary description for CertFun

/// class which will handle and implemet the delegates

///


public class CertFun

{

[StructLayout(LayoutKind.Sequential)]

public struct CRYPTUI_CERT_MGR_STRUCT

{

public int dwSize;

public IntPtr hwndParent;

public int dwFlags;

public string pwszTitle;

public IntPtr pszInitUsageOID;

}

[StructLayout(LayoutKind.Sequential)]

public struct CRYPT_KEY_PROV_INFO

{

[MarshalAs(UnmanagedType.LPWStr)]

public string ContainerName;

[MarshalAs(UnmanagedType.LPWStr)]

public string ProvName;

public int ProvType;

public int Flags;

public int ProvParam;

public IntPtr rgProvParam;

public int KeySpec;

}

[DllImport("cryptui.dll", SetLastError = true)]

public static extern IntPtr CryptUIDlgSelectCertificateFromStore(IntPtr hCertStore, IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)]

string

pwszTitle, [MarshalAs(UnmanagedType.LPWStr)]

string

pwszDisplayString, int dwDontUseColumn, int dwFlags, IntPtr pvReserved);

[DllImport("crypt32.dll", SetLastError = true)]

public static extern IntPtr CertEnumCertificatesInStore(IntPtr hCertStore, IntPtr pPrevCertContext);

[DllImport("crypt32.dll", SetLastError = true)]

public static extern bool CertGetNameString(IntPtr pCertContext, int dwType, int dwFlags, IntPtr pvTypePara, StringBuilder pszNameString, Int32 cchNameString);

[DllImport("crypt32.dll", SetLastError = true)]

public static extern bool CertGetCertificateContextProperty(IntPtr pCertContext, int dwPropId, IntPtr pvData, ref int pcbData);

[DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]

public static extern IntPtr CertOpenSystemStore(IntPtr hCryptProv, string storename);

[DllImport("crypt32.dll", SetLastError = true)]

public static extern bool CertFreeCertificateContext(IntPtr hCertStore);

[DllImport("crypt32.dll", SetLastError = true)]

public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);

[DllImport("cryptui.dll", SetLastError = true)]

public static extern bool CryptUIDlgCertMgr(ref CRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr);

[DllImport("crypt32.dll")]

public static extern bool CryptDecodeObject(int CertEncodingType, int lpszStructType, byte[] pbEncoded, int cbEncoded, int flags, [In(), Out()]

byte

[] pvStructInfo, ref int cbStructInfo);



[DllImport("crypt32.dll", SetLastError = true)]

public static extern IntPtr CertFindCertificateInStore(IntPtr hCertStore, int dwCertEncodingType, int dwFindFlags, int dwFindType, [In(), MarshalAs(UnmanagedType.LPWStr)]

string

pszFindString, IntPtr pPrevCertContext);

[StructLayout(LayoutKind.Sequential)]

public struct PUBKEYBLOBHEADERS

{

////BLOBHEADER

public byte bType;

// //BLOBHEADER

public byte bVersion;

////BLOBHEADER

public short reserved;

////BLOBHEADER

public Int32 aiKeyAlg;

// //RSAPUBKEY

public int magic;

//; '//RSAPUBKEY

public int bitlen;

//; //RSAPUBKEY

public int pubexp;

}

public int CERT_NAME_SIMPLE_DISPLAY_TYPE = 0x4;

public int CRYPTUI_SELECT_LOCATION_COLUMN = 0x10;

public int CERT_KEY_PROV_INFO_PROP_ID = 0x2;

static public int X509_ASN_ENCODING = 0x1;

static public int PKCS_7_ASN_ENCODING = 0x10000;

public int RSA_CSP_PUBLICKEYBLOB = 19;

static public int ENCODING_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;

public int CERT_FIND_SUBJECT_STR = 0x80007;

public byte[] pubblob;

public string PKC12CertSelectedName = "";

public byte[] EncKey;

public byte[] EncIv;

public byte[] EncData;

//creates new instance of Rinjndael

public RijndaelManaged Rin = new RijndaelManaged();

public byte[] SignedData;

public string CertForEnc = "";

public string CertForSig = "";

}

}

[/code]

I will Cover the next method in my next resource which will overcome the limitation of the method one



Thanks and Regards
Meetu Choudhary

Wednesday, May 27, 2009

Few moments with Dotnetspider : DNS-MVM award

In continuation on my award of MVM from dotnetspider.com, DNS published my interview on this award.

In this interview I have shared my views with Raghav on my this achievement.

The tenure of interview is around 60-minutes, I really enjoyed with Raghav.

Here is the link of my interview : http://www.dotnetspider.com/forum/206923-Few-moments-with-Meetu-Choudhary-DotNetSpider-MVM.aspx

Wednesday, April 29, 2009

MVM from DotnetSpider.com

Its a very cool Morning today. I got a call from Gaurav Arora informing me that I got the MVM Award and then foolwed by a mail from Raghav , The webmaster of http//:dotnetspider.com regarding the Most Valuable Member award from Dotnetspider. This is the moment of my dreams come true. Here are the few lines from the mail :

Congratulations from dotnetspider.com! Your contributions to the technology world is recognized by dotnetspider.com, one of the most respected technology community. We are glad to inform you that you are selected as the MOST VALUABLE MEMBER (MVM) for your active participation and contribution to dotnetspider.com. You will be awarded with a certificate of appreciation from us.Visit this page for the list of winners - http://www.dotnetspider.com/credits/Index.aspx
and you can catch the annoucment at
http://www.dotnetspider.com/forum/203217-Winners-MVM-award.aspx

My thanks to DNS family for this award and special thanks to Raghav who showed the faith in me and to Gaurav Arora who have nominated me for this prestigious award.

Sunday, April 26, 2009

How to Scale your entire App and its Elements to your Browsers Size

How to Scale your entire App and its Elements to your Browsers Size



Wow, Today I found the answer of the question "How to Scale your entire App and its Elements to your Browsers Size?" And the answer provided to me is by the silverlight 2.0. I always wonder that how can i scale my application to different browser sizes... and to different screen resolutions I found some PHP sites which were scalable according to the browser size but was unable to handle the same in my ASP.net applications... I have Hear-ed a lot about the silverlight and its applications but never give a thought to it and now finally when my client needs the scalable sites then i have no other option left with me i have to search it and thought to go ahead with silverlight and today only i get all the essentials for the silverlight and started to find the solution and to my wonders i found the solution so simple and easy... Here I would like to share it with you all...

we can achieve it in simple two steps

Step 1:

Add the following line of code to the canvas... in page.xaml....
[code]
< Canvas.RenderTransform >
< ScaleTransform x:Name="CanvasScale" ScaleX="1" ScaleY="1" > < /ScaleTransform >
< /Canvas.RenderTransform >
[/code]

and the example code i took to demonstrate it is
[code]
<
UserControl xmlns:inputToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit" x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" >
< Grid x:Name="LayoutRoot" Background="White" >
< Canvas Height="150" Width="400" Background="Bisque" VerticalAlignment="Center" >
< Canvas.RenderTransform >
< ScaleTransform x:Name="CanvasScale" ScaleX="1" ScaleY="1" > < /ScaleTransform >
< /Canvas.RenderTransform >
< Button x:Name="myButton" Canvas.Top="50"
Canvas.Left="75" Content="Click Me"
Height="37" Width="118" Click="myButton_Click"
ToolTipService.ToolTip ="Click to change above text"/ >
< Button x:Name="myButton1" Canvas.Top="50"
Canvas.Left="195" Content="Click Me"
Height="37" Width="118"/ >
< /Canvas >
< /Grid >
< /
UserControl >
[/code]


Step 2:

Add the following piece of code in the page.xaml.cs
in page()
[code]
App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
[/code]

and the function
[code]
void
Content_Resized(object sender, EventArgs e)
{
double height = App.Current.Host.Content.ActualHeight;
double width = App.Current.Host.Content.ActualWidth;
CanvasScale.ScaleX = width / _startingWidth;
CanvasScale.ScaleY = height / _startingHeight;
}
[/code]

in my example
[code]
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Net;
using
System.Windows;
using
System.Windows.Controls;
using
System.Windows.Documents;
using
System.Windows.Input;
using
System.Windows.Media;
using
System.Windows.Media.Animation;
using
System.Windows.Shapes;
namespace
SilverlightApplication1
{
public partial class Page : UserControl
{
private int _startingWidth = 800;
private int _startingHeight = 600;
public Page()
{
InitializeComponent();
App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
}
void Content_Resized(object sender, EventArgs e)
{
double height = App.Current.Host.Content.ActualHeight;
double width = App.Current.Host.Content.ActualWidth;
CanvasScale.ScaleX = width / _startingWidth;
CanvasScale.ScaleY = height / _startingHeight;
}
}
}
[/code]


Test Yourself....
I am sure you will also enjoy as I did.....



Thanks and Regards
Meetu Choudhary

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com