Thursday, July 2, 2009
Monday, May 25, 2009
Navigation From One Page to Another Page with Data.
Navigation From One Page to Another Page with Data. |
There are various ways to send the data from one page to other |
1> Using QueryString. |
e.g. In first page you can write as follows : Response.Redirect("mypage.aspx?id=" + value from control or variable or anystring); mypage.aspx?id=10 Above dummy my page now contains id as the query string and It can be retrieved on the other page as follows : string id = Request.QueryString["id"].ToString(); |
2> Using Session. e.g. You can create session in first page like. Session["id"] = value from control or variable or anystring; and you can retrive it from other page as following: string id = Session["id"].ToString(); |
3>Using Cookies e.g. You can write cookie as in first page as follows : Response.Cookies["id"].Value = value from control or variable or anystring; and to retrive cookie you can request it as follows: string id = Request.Cookies["BackgroundColor"].Value.ToString(); |
Friday, May 22, 2009
Advanced Diploma in Software Development
Advanced Diploma in Software Development (ADSD) About ADSD
Selection Procedure Based on the performance in the MET CET (consisting of Written Test & Personal Interview). Programme Modules The ADSD programme is divided into two parts. Each part consists of four modules. Each module is divided into two units. Following is the detailed structure:
|
Sunday, May 3, 2009
In-Depth look at the GridView Control
In this article we will examine more features of the Grid View control. In this article we will see some of the common operations that can be performed using the GridView control. Apart from these operations there are many more functions that can be performed on the control and which we will see in the later articles.
Adding a SqlDataSource and binding to GridView Control:
In this article I will be using the Northwind database which comes with SQL Server 2000. In the last article I explained how easy it is to bind the Grid View control to the SqlDataSource. You can perform all these actions using the wizard. If you want to code and bind the datasource you can easily perform it using the following code sample:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Binds the data
BindData();
}
}
public void BindData()
{
// you can use this line
string connectionString = myDataSource.ConnectionString;
// you can also use this line since by using the SqlDataSource it makes an entry in the
// web.config file if that is what choose to do
//string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
// if you are using Enterprise Library you can also use
//string connectionString = (string)ConfigurationSettings.ConnectionStrings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
myGridView.DataSource = ds;
myGridView.DataBind();
}
You will need to set the Bound column in order to see the text in the cells of the grid view control. This can be easily done by using the Smart tag which appears when you right click on the grid view control.

I have also added a Status column to show you the checkbox column feature. The Status column is a simple bit field whose value can be either 1 or 0. If you are using Access database you can choose Yes/No Column. Once you have set up all your columns and execute the page it will display something like this:

At this moment if you try to select the Checkbox column, meaning if you try to check or uncheck the Status column it won't work. Let's see how we can make it work with our grid view control.
In the above image you see that the Checkboxes are not marked. The reason is because in the database the Checkbox column is NULL. If you make the column value to either 1 or 0 you will see check marks where the value is 1. See the image below and you will have a better idea of what I mean.

Editing in the Grid View Control
You can easily add the editing, updating, selecting, paging and sorting capabilities to your grid view control. Just add a new command column and you will be asked to add whatever functionality you desire.
If you are using the SqlDataSource to bind to the GridView control you will get most of the features by just using the SqlDataSource wizard. Since we are binding the control at runtime we need to add most of the functionality manually.
Edit Mode:
The fields that are marked readonly = false will change into TextBoxes when the Row_Editing event triggers. Like DataGrid control its easy to set the fields in the edit mode.
// Editing mode
void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex;
BindData();
}
Cancel Edit:
If you don't like to edit the row you can press cancel link button which will fire the RowCancelingEdit event. The code to turn the row back to its original form is quite simple and straight forward.
// Cancel Edit Mode
void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
myGridView.EditIndex = -1;
BindData();
}
Selecting Row:
Selecting row event is fired when you make a click on the select link. If you need any particular item in that row you can easily select it using the cells property:
// Selecting row
void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
// This will contain the selectedValue of the row
string selectedCategory = myGridView.SelectedRow.Cells[1].Text;
}
The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so on.
Update Row:
For Updating the row we first need to get the value from the row that is entered by the user into the TextBox. For this purpose you can change the bound column into a Template column which will make is easier to locate the item.
After changing the CategoryName column to a tem plated column we can easily use the RowUpdating event to find the Text entered by the user.
void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = myGridView.Rows[e.RowIndex];
if (row != null)
{
TextBox t = row.FindControl("TextBox1") as TextBox;
if (t != null)
{
Response.Write("The Text Entered is" + t.Text);
}
}
Paging:
Paging can also be easily enabled in the grid view control. Its just like DataGrid from Asp.net 1.1. First you need to make set the allow paging property to true. And you can also set the page size. Here is a small code sample that will enable paging.
// Grid View Paging
void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
myGridView.PageIndex = e.NewPageIndex;
BindData();
}
Here is a small image shown below of paging. I have limited the page size to 3 so that the distribution of page will take place. In the image below we are in the page number 2.

Using SqlDataSource to execute commands:
You can also use the powerful SqlDataSource control to run and make your query. The SqlDataSource also contains the QUERY builder interface which can enhance the user experience in making SQL Queries. Apart from the SELECT query there are also INSERT, DELETE and UPDATE query builders wizards that you can use in your application.
When you use SqlDataSource you gets the advantage of having the paging, sorting implemented automatically which is pretty cool in some cases.
In the next article we will see some more features of the Grid View control. I hope you liked the article
Happy Programming !
Encryption and Decryption Functions
System.Security.Cryptography.
Coding Sample Given as follows:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Security.Cryptography;
///
/// Class which contains static reusable methods for encrypting a string.
/// Mainly constructed for URL encryption but further can be used for string encryption
/// needed in other operation.
///
public class Cryptex
{
public Cryptex()
{
//
// TODO: Add constructor logic here
//
}
internal static HttpServerUtility sUtil = HttpContext.Current.Server;
///
/// Method used to encrypt a string making use of DES Algorithm.
///
///
///
///
public static string StringEncrypt_DES(string queryString) {
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
string key = ConfigurationManager.AppSettings["DESCryptokey"];
des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
ICryptoTransform cryptotransform = des.CreateEncryptor();
try {
MemoryStream mStream = new MemoryStream();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptostream);
writer.WriteLine(queryString);
writer.Close();
cryptostream.Close();
byte[] buffer = mStream.ToArray();
mStream.Close();
return Convert.ToBase64String(buffer);
}
catch {
throw;
}
return string.Empty;
}
///
/// Method used to dencrypt a string making use of DES Algorithm.
///
///
///
///
public static string StringDecrypt_DES(string queryString) {
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
string key = ConfigurationManager.AppSettings["DESCryptokey"];
des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
try {
queryString = sUtil.UrlDecode(queryString);
byte[] buffer = Convert.FromBase64String(queryString.Trim());
MemoryStream mStream = new MemoryStream(buffer);
ICryptoTransform cryptotransform = des.CreateDecryptor();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptostream);
queryString = reader.ReadLine();
reader.Close();
cryptostream.Close();
mStream.Close();
}
catch {
throw;
}
return queryString;
}
///
/// Method used to encrypt a string making use of RC2 Algorithm.
///
///
///
///
public static string StringEncrypt_RC2(string inputString, string key) {
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;
rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rc2.CreateEncryptor();
return encrypt(inputString, cryptotransform);
}
///
/// Method used to dencrypt a string making use of RC2 Algorithm.
///
///
///
///
public static string StringDecrypt_RC2(string inputString, string key) {
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;
rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rc2.CreateDecryptor();
return decrypt(inputString, cryptotransform);
}
///
/// Method used to encrypt a string making use of Rijndael Algorithm.
///
///
///
///
public static string StringEncrypt_RIJNDAEL(string inputString, string key) {
Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);
rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rijndael.CreateEncryptor();
return encrypt(inputString, cryptotransform);
}
///
/// Method used to dencrypt a string making use of Rijndael Algorithm.
///
///
///
///
public static string StringDecrypt_RIJNDAEL(string inputString, string key) {
Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);
rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rijndael.CreateDecryptor();
return decrypt(inputString, cryptotransform);
}
protected static string encrypt(string Str, ICryptoTransform cryptotransform) {
try {
MemoryStream mStream = new MemoryStream();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptostream);
writer.WriteLine(Str.Trim());
writer.Close();
cryptostream.Close();
byte[] buffer = mStream.ToArray();
mStream.Close();
Str = sUtil.UrlEncode(Convert.ToBase64String(buffer));
}
catch{
throw;
}
return Str;
}
protected static string decrypt(string Str, ICryptoTransform cryptotransform) {
try {
Str = sUtil.UrlDecode(Str.Trim());
byte[] buffer = Convert.FromBase64String(Str);
MemoryStream mStream = new MemoryStream(buffer);
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptostream);
Str = reader.ReadLine();
reader.Close();
cryptostream.Close();
mStream.Close();
}
catch {
throw;
}
return Str;
}
const string DESKey = "AQWSEDRF";
const string DESIV = "AQWSEDRF";
public static string DESDecrypt(string stringToDecrypt)//Decrypt the content
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
try {
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex) {
throw ex;
}
}
public static string DESEncrypt(string stringToEncrypt)// Encrypt the content
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
try {
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex) {
throw ex;
}
}
static byte[] Convert2ByteArray(string strInput) {
int intCounter; char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte = new byte[arrChar.Length];
for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
return arrByte;
}
}
For More Info Follow Following Link :
http://msdn.microsoft.com/en-us/library/system.security.cryptography.asnencodeddataenumerator.aspx
Friday, March 20, 2009
Read Excel Database using ADO.Net
Excel is nothing but the other database only. It can be set like below
The table example as follows :
e.g. Student.xls
Here
-------------------------------------
Database ---------------Table
(Excel Workbook)------ (Excel Sheet)
-------------------------------------
Student.xls------------- personal_info
-------------------------------------
id ------- Name -------- Address
1 ------- Sachin -------- Patan
2 ------- Sam ---------- New Lands
Now below given code gives you access for the excel database.
C# code snippet
-----------------------------
using System;
using System.Data;
class Test{
public static void Main(){
IDbConnection con = new System.Data.Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};DBQ=db\\Student.xls");
// The above line is for connection string.
con.Open();
IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "select id,name,address from [personal_info$]";
//Here the personal_info$ is the worksheet i.e. (table) of Student.xls Workbook i.e. (Database).
IDataReader reader = cmd.ExecuteReader();
while(reader.Read()){
Console.WriteLine("{0, -6}{1}{2}", reader.GetInt32(0), reader[1], reader["address"]);
// We can retrieve data with given three ways
// as reader.GetInt32(0) ----------> Gives first field.
// reader[1] ------------------------>Gives second field.
// reader["address"] --------------->Gives third field.
}
reader.Close();
con.Close();
}
}
Finding or Verifying Credit Card Numbers
You can use a slightly different regular expression to find credit card numbers, or number sequences that might be credit card numbers, within larger documents. This can be very useful to prove in a security audit that you're not improperly exposing your clients' financial details.
We'll start with the order form.
Stripping Spaces and Dashes
The first step is to remove all non-digits from the card number entered by the customer. Physical credit cards have spaces within the card number to group the digits, making it easier for humans to read or type in. So your order form should accept card numbers with spaces or dashes in them.
To remove all non-digits from the card number, simply use the "replace all" function in your scripting language to search for the regex [^0-9]+ and replace it with nothing. If you only want to replace spaces and dashes, you could use [ -]+. If this regex looks odd, remember that in a character class, the hyphen is a literal when it occurs right before the closing bracket (or right after the opening bracket or negating caret).
If you're wondering what the plus is for: that's for performance. If the input has consecutive non-digits, e.g. 1===2, then the regex will match the three equals signs at once, and delete them in one replacement. Without the plus, three replacements would be required. In this case, the savings are only a few microseconds. But it's a good habit to keep regex efficiency in the back of your mind. Though the savings are minimal here, so is the effort of typing the extra plus.
Validating Credit Card Numbers on Your Order Form
Validating credit card numbers is the ideal job for regular expressions. They're just a sequence of 13 to 16 digits, with a few specific digits at the start that identify the card issuer. You can use the specific regular expressions below to alert customers when they try to use a kind of card you don't accept, or to route orders using different cards to different processors. All these regexes were taken from RegexBuddy's library.
Visa: ^4[0-9]{12}(?:[0-9]{3})?$
All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.
MasterCard: ^5[1-5][0-9]{14}$
All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.
American Express: ^3[47][0-9]{13}$
American Express card numbers start with 34 or 37 and have 15 digits.
Diners Club: ^3(?:0[0-5][68][0-9])[0-9]{11}$
Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
Discover: ^6(?:0115[0-9]{2})[0-9]{12}$
Discover card numbers begin with 6011 or 65. All have 16 digits.
JCB: ^(?:2131180035\d{3})\d{11}$
JCB cards beginning with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.
If you just want to check whether the card number looks valid, without determining the brand, you can combine the above six regexes into
^(?:4[0-9]{12}(?:[0-9]{3})?5[1-5][0-9]{14}6(?:0115[0-9][0-9])[0-9]{12}3[47][0-9]{13}3(?:0[0-5][68][0-9])[0-9]{11}(?:2131180035\d{3})\d{11})$.
You'll see I've simply alternated all the regexes, and used a non-capturing group to put the anchors outside the alternation. You can easily delete the card types you don't accept from the list.
These regular expressions will easily catch numbers that are invalid because the customer entered too many or too few digits. They won't catch numbers with incorrect digits. For that, you need to follow the Luhn algorithm, which cannot be done with a regex. And of course, even if the number is mathematically valid, that doesn't mean a card with this number was issued or if there's money in the account. The benefit or the regular expression is that you can put it in a bit of JavaScript to instantly check for obvious errors, instead of making the customer wait 30 seconds for your credit card processor to fail the order. And if your card processor charges for failed transactions, you'll really want to implement both the regex and the Luhn validation.
Finding Credit Card Numbers in Documents
With two simple modifications, you could use any of the above regexes to find card numbers in larger documents. Simply replace the caret and dollar with a word boundary,
e.g.: \b4[0-9]{12}(?:[0-9]{3})?\b.
If you're planning to search a large document server, a simpler regular expression will speed up the search. Unless your company uses 16-digit numbers for other purposes, you'll have few false positives. The regex \b\d{13,16}\b will find any sequence of 13 to 16 digits.
When searching a hard disk full of files, you can't strip out spaces and dashes first like you can when validating a single card number. To find card numbers with spaces or dashes in them, use \b(?:\d[ -]*){13,16}\b. This regex allows any amount of spaces and dashes anywhere in the number. This is really the only way. Visa and MasterCard put digits in sets of 4, while Amex and Discover use groups of 4, 5 and 6 digits. People typing in the numbers may have different ideas yet.