Thursday, May 28, 2009

Get Network Information in C#

public static string DisplayNICInfo()
{
//Display current network adapter states
StringBuilder sb= new StringBuilder();
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
sb.Append("Network Adapter Information:");
foreach (NetworkInterface n in adapters)
{
sb.Append(string.Format("\tId: {0}", n.Id));
sb.Append(string.Format("\tPhysical (MAC) Address: {0}",
n.GetPhysicalAddress().ToString()));
sb.Append(string.Format("\tDescription: {0}", n.Description));
sb.Append(string.Format("\tName: {0}", n.Name));
sb.Append(string.Format("\tOperationalStatus: {0}",
n.OperationalStatus.ToString()));
sb.Append(string.Format("\tInterface type: {0}",
n.NetworkInterfaceType.ToString()));
sb.Append(string.Format("\tSpeed: {0}", n.Speed));
//IPInterfaceProperties ipProps = n.GetIPProperties();
//DisplayInterfaceProperties(ipProps);
}
return sb.ToString();
}

Simplest way to send email using GMail in ASP.Net (C#)

///
/// This is the primery method try from the program
/// Latest & easiest method of sending an Email using ASP.NET
///

///
///
///
///
public static void sendMail(string to, string from, string subject, string body)
{
///Smtp config
SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
// Edit password and username
client.Credentials = new NetworkCredential("kalit.sikka@gmail.com", "password");
client.EnableSsl = true;

///mail details
MailMessage msg = new MailMessage();


try
{

msg.From = new MailAddress(from);
msg.To.Add(to);
// msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Subject = subject;
//msg.CC.Add();
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.Body = body;
msg.Priority = MailPriority.Normal;

// Enable one of the following method.

client.Send(msg);

// or use the following alternative after enabling send mail asynchronous option in the global.asax

//object userState = msg;
//client.SendAsync(msg, userState);



}
catch (Exception exp)
{
///This runs the backup plan
SendMailAlt(to, from, subject, body);
}

}

Monday, May 25, 2009

Write TextFile from SQLDataReader

public static void mWriteTextFileFromSQLDataReader(SqlDataReader rd, string strTextFilePath)
{
using (FileStream fs = new FileStream(strTextFilePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Unicode))
{
while (rd.Read())
{

for (int i = 0; i < rd.VisibleFieldCount; i++)
{
if (!rd.IsDBNull(i))
{
switch (rd.GetDataTypeName(i))
{
case "NUMBER":
sw.Write(rd.GetInt32(i).ToString());
break;
case "DATE":
sw.Write(rd.GetDateTime(i).ToString("MM/dd/yyyy HH:mm:ss"));
break;
case "VARCHAR2":
sw.Write(rd.GetString(i));
break;
default:
sw.WriteLine(rd.GetValue(i).ToString());
break;
}

if (i < rd.VisibleFieldCount) // Between DataFields
sw.Write("\t");


}
}

sw.WriteLine(); // Between Records
}
}
}
}

Wednesday, May 20, 2009

Disable Editing in DataGridView+Winforms

// Method 1

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (((DataGridView)sender).CurrentCell.ColumnIndex == 1)
e.Cancel = true;
}

//Method 2

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if(this.dataGridView1.CurrentCell.ColumnIndex==1)
this.dataGridView1.CurrentCell.Selected = false;
}

Tuesday, May 19, 2009

Export DataTable into CSV

class ExportDataToCSV
{
///
/// It will export data in DataTable into CSV format
/// and use TextWriter Object to write it.
///

///
///
///
public static void mCreateCSV(DataTable dt, System.IO.TextWriter httpStream, bool WriteHeader)
{
if(WriteHeader)
{
string[] arr = new String[dt.Columns.Count];
int k = dt.Columns.Count;
for(int i = 0; i {
arr[i] = dt.Columns[i].ColumnName;
arr[i] = GetWriteableValue(arr[i]);
}

httpStream.WriteLine(string.Join(",", arr));
}

for(int j = 0; j {
string[] dataArr = new String[dt.Columns.Count];
for(int i = 0; i {
object o = dt.Rows[j][i];
dataArr[i] = GetWriteableValue(o);
}
httpStream.WriteLine(string.Join(",", dataArr));
}
}

///
/// It will export Data in DataTable into CSV format
/// and write it using object of StreamWriter
///

///
///
///
public static void mCreateCSV(DataTable dt, System.IO.StreamWriter file, bool WriteHeader)
{
if(WriteHeader)
{
string[] arr = new String[dt.Columns.Count];
for(int i = 0; i {
arr[i] = dt.Columns[i].ColumnName;
arr[i] = GetWriteableValue(arr[i]);
}

file.WriteLine(string.Join(",", arr));
}

for(int j = 0; j {
string[] dataArr = new String[dt.Columns.Count];
for(int i = 0; i {
object o = dt.Rows[j][i];
dataArr[i] = GetWriteableValue(o);
}
file.WriteLine(string.Join(",", dataArr));
}
}

public static string GetWriteableValue(object o)
{
if(o==null || o == Convert.DBNull)
return "";
else if(o.ToString().IndexOf(",")==-1)
return o.ToString();
else
return "\"" + o.ToString() + "\"";

}

}

Monday, May 18, 2009

To Remove specfic string from Collection of string

///
/// To Remove specfic string from Collection of string
///

///
///
///
public static string mRemoveStringFromCollection(string strNames, string sep, string specificStr)
{
List list = new List();
string strValue = String.Empty;
if (!string.IsNullOrEmpty(strNames))
{
list.AddRange(Regex.Split(strNames, sep));
foreach (string str in list)
{
if (!str.Contains(specificStr))
{
if (string.IsNullOrEmpty(strValue))
{
strValue = str;
}
else
{
strValue = strValue + sep + str;
}
}
}

return strValue;
}
return strNames;
}

Setting Opacity of WinForm

public static void mSetOpacity(Form form)
{
form.Opacity = 0.05;
for(double i=0.20; i < 1; i+=0.20)
{
form.Opacity = System.Math.Round(i, 2);

System.Threading.Thread.Sleep(5);

}
}

Sunday, May 17, 2009

Alert Message in ASP.net

public static string GetAlert(string Message)
{
string Script = "";
Script += "";
return Script;
}

I code behind:

Script = VetCareUtilities.GetAlert("File does not exists");
Page.ClientScript.RegisterStartupScript(typeof(Page), "Filedoesnotexists", Script);

Saturday, May 16, 2009

Update Database with DataGridView+Update Command

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OracleClient;

namespace Trans829115.PL
{
public partial class frmUpdateDBViaDataGridView : Form
{
private OracleConnection connection;
private OracleCommand command;
private OracleDataAdapter adapter;
private OracleCommandBuilder builder;
private DataSet ds;
private DataTable userTable;
private bool mAllowInsert;
private bool mAllowDelete;
private bool IsDirty = false;


public frmUpdateDBViaDataGridView()
{
InitializeComponent();

// In Form control definition

connection = new OracleConnection(BLL.QuerySet.ConString);
command = new OracleCommand(BLL.QuerySet.UpFTP, connection);
adapter = new OracleDataAdapter(command);
builder = new OracleCommandBuilder(adapter);
ds = new DataSet();
adapter.Fill(ds);
userTable = ds.Tables[0];

userDataGridView.AllowUserToAddRows = true;
userDataGridView.AllowUserToDeleteRows = true;
btnDelete.Enabled = true;

}

private void btnDelete_Click(object sender, EventArgs e)
{
Delete();
}

private void frmUpdateDBViaDataGridView_Load(object sender, EventArgs e)
{
userDataGridView.DataSource = userTable.DefaultView;
lblRowCount.Text = "Number of records: " + userTable.Rows.Count.ToString();
userDataGridView.AllowUserToResizeColumns = true;
if (userTable.Rows.Count == 0)
{
btnDelete.Enabled = false;
btnUpdate.Enabled = false;
}

}

private void Delete()
{
if (MessageBox.Show("Do you really want to delete the selected record(s)?",
"Delete records", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false)
== DialogResult.Yes)
{
try
{

int cnt = userDataGridView.SelectedRows.Count;
for (int i = 0; i < cnt; i++)
{
if (this.userDataGridView.SelectedRows.Count > 0 &&
this.userDataGridView.SelectedRows[0].Index !=
this.userDataGridView.Rows.Count - 1)
{
this.userDataGridView.Rows.RemoveAt(
this.userDataGridView.SelectedRows[0].Index);
}
}

if(ds.HasChanges())
{
DataTable changes = ds.Tables[0].GetChanges();

if (changes != null)


adapter.Update(changes);
ds.Tables[0].AcceptChanges();


}

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{

}
}
if (userTable.Rows.Count == 0)
{
btnUpdate.Enabled = false;
if (mAllowDelete) btnDelete.Enabled = false;
}
IsDirty = true;
}

private void Update()
{
try
{
connection.Open();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(userTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}

private void btnUpdate_Click(object sender, EventArgs e)
{
Update();
}

private void frmUpdateDBViaDataGridView_FormClosing(object sender, FormClosingEventArgs e)
{
if (IsDirty)
if (MessageBox.Show("Do you want to save changes?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
Update();

}

private void userDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (IsDirty)
if (MessageBox.Show("Do you want to save changes?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
Update();

}

private void userDataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete) Delete();
e.Handled = true; // Cancel
}



}
}

Encryption and Decryption in .NET

public class EnCodingDeCoding
{
public static string Encode(string sData)
{
try
{
byte[] encData_byte = new byte[sData.Length];

encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);

string encodedData = Convert.ToBase64String(encData_byte);

return encodedData;

}
catch(Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}

public static string Decode(string sData)
{

System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();

System.Text.Decoder utf8Decode = encoder.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(sData);

int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

char[] decoded_char = new char[charCount];

utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

string result = new String(decoded_char);

return result;

}




}

Friday, May 15, 2009

How to get IPAddress in .Net

public static string mGetIPAddress()
{
string strHostName = Dns.GetHostName();
string strIPAddress = "";

IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);

foreach (IPAddress ipaddress in iphostentry.AddressList)
{
strIPAddress = ipaddress.ToString();
}
return strIPAddress;
}

How to get Gateway in .NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;

public class ClsGatewayID
{
private static string _GatewayID = string.Empty;

public static string GatewayID
{
get
{
return mGetGatewayID();
}
}

private static string mGetGatewayID()
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses;
if (addresses.Count > 0)
{
foreach (GatewayIPAddressInformation address in addresses)
{

if(string.IsNullOrEmpty(_GatewayID))
_GatewayID += address.Address.ToString();
else
_GatewayID += address.Address.ToString() + "\r\n";

}
}
}

return _GatewayID;
}
}

Wednesday, May 13, 2009

How to use Favicon in ASP.net

To display your own icon on the browser address bar when visitors view or bookmark your web page?

Note: '<' is replace with '[' so that blog's editor can not resolve the HTML tags on this page

[link runat="server" rel="shortcut icon" href="~/favicon.ico" type="image/x- icon" /]
[link runat="server" rel="icon" href="~/favicon.ico" type="image/ico" /]

Put the above text in header section of your html

Get the name of previous page in ASP.Net

public static string mGetPreviousPage()
{
if (Request.UrlReferrer != null)
{
string strPage = Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];
return strPage;
}
return null; // No Previous page found
}

Monday, May 11, 2009

How to Convert DataGridView into HTML Table

public static StringBuilder DataGridToHMTLTable(System.Windows.Forms.DataGridView dg)
{
StringBuilder sb = new StringBuilder();
//Setting HTML and table tags
sb.AppendLine("
<" +
"table border='2' cellpadding='1' cellspacing='1'>");
sb.AppendLine("");
//setting table headers
for (int i = 0; i < dg.Columns.Count; i++)
{
sb.AppendLine("" +
dg.Columns[i].HeaderText + "");
}
//Table body
sb.AppendLine("");
for (int i = 0; i < dg.Rows.Count; i++)
{
sb.AppendLine("");
foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
{
sb.AppendLine("" +
dgvc.Value.ToString() + "");
}
sb.AppendLine("");

}
//Table Footer and End of HTML Tag
sb.AppendLine("
");
return sb;
}

How to use the radiobutton in WPF and XAML

WPF RadioButton Control:

RadioButton controls are usually grouped together to offer user a single choice among several options (only one button at a time can be selected).

tag is used too create the radio button in XAML.

Properties:
In the following tag I create the RadioButton in which Height is height of the RadioButton, Name is the nameof the RadioButton, text in the between the RadioButton tag is the centent visibile to user. Background the the color of the box, Borderbrush is the color of the border, Forground is the color of the text.

ASP.net Articles


To change the orientation from left to right use the FlowDirection property to RightToLeft.

RadioButton is used in the group so that user can select only one option from the available options (No extra coding is required to uncheck others). Use same GroupName of the radiobuttons to mark in a group so that only one option can be selected as follows.


ASP.net Articles
C# Articles
ADO.net Articles
SQL Server 2005 Articles






Events:


Now write the code to the handler so that we can take appropriate action on these events in windows1.xaml.cs.


Finding out which radiobutton is checked use the property IsChecked as follows in the btnShow button

private void btnShow_Click(object sender, RoutedEventArgs e)
{
if (RadioButton_Option1.IsChecked==true)

System.Diagnostics.Process.Start(@"http://www.eggheadcafe.com/ASPNetBlog.aspx");
else if(RadioButton_Option2.IsChecked==true)
System.Diagnostics.Process.Start(@"http://www.eggheadcafe.com/CSharpBlog.aspx");
else if(RadioButton_Option3.IsChecked==true)
System.Diagnostics.Process.Start(@"http://www.eggheadcafe.com/ADONetBlog.aspx");
else if(RadioButton_Option4.IsChecked==true)
System.Diagnostics.Process.Start(@"http://www.eggheadcafe.com/SQLServerBlog.aspx");


}

Summary: Radio button is very simple control and used for selecting only one option from the available options.

3-Tier architecture in .Net

3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).

Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.

Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.

Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.

Designing 3-Tier Architecture

For the ease of understanding, I have created BAL, DAL into the App_Code folder. In real scenario, you should create separate projects for BAL, DAL (as Class Library) and UI (as Web project) and reference your BAL into UI.




Data Access Layer
Lets proceed with desiging 3-Tier architecture. To do that lets proceed with DAL, BAL and then UI. Add a class named by right clicking App_Code folder. (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for DAL and add reference of this project into your BAL.) and copy-paste folowing code (Your can overwrite your default written code for the class file by pasting this code). Here, I have assumed that you will create the respective stored procedure yourself into the database or you may download attachment from http://www.dotnetfunda.com/articles/article18.aspx article and look for App_Data folder for complete database structure and stored procedure for this article.

Data Access Layer (DAL)

Code for Data Access Layer

- Hide Code

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;





///

/// Summary description for PersonDAL3

///


public class PersonDAL3

{

string connStr = ConfigurationManager.ConnectionStrings["TutTestConn"].ToString();



public PersonDAL3()

{



}



///

/// Used to insert records into database

///


///

///

///

///

public int Insert(string firstName, string lastName, int age)

{

SqlConnection conn = new SqlConnection(connStr);

conn.Open();

SqlCommand dCmd = new SqlCommand("InsertData", conn);

dCmd.CommandType = CommandType.StoredProcedure;

try

{

dCmd.Parameters.AddWithValue("@firstName", firstName);

dCmd.Parameters.AddWithValue("@lastName", lastName);

dCmd.Parameters.AddWithValue("@age", age);

return dCmd.ExecuteNonQuery();

}

catch

{

throw;

}

finally

{

dCmd.Dispose();

conn.Close();

conn.Dispose();

}

}





///

/// Update record into database

///


///

///

///

///

///

public int Update(int personID, string firstName, string lastName, int age)

{

SqlConnection conn = new SqlConnection(connStr);

conn.Open();

SqlCommand dCmd = new SqlCommand("UpdateData", conn);

dCmd.CommandType = CommandType.StoredProcedure;

try

{

dCmd.Parameters.AddWithValue("@firstName", firstName);

dCmd.Parameters.AddWithValue("@lastName", lastName);

dCmd.Parameters.AddWithValue("@age", age);

dCmd.Parameters.AddWithValue("@personID", personID);

return dCmd.ExecuteNonQuery();

}

catch

{

throw;

}

finally

{

dCmd.Dispose();

conn.Close();

conn.Dispose();

}

}



///

/// Load all records from database

///


///

public DataTable Load()

{

SqlConnection conn = new SqlConnection(connStr);

SqlDataAdapter dAd = new SqlDataAdapter("LoadAll", conn);

dAd.SelectCommand.CommandType = CommandType.StoredProcedure;

DataSet dSet = new DataSet();

try

{

dAd.Fill(dSet, "PersonTable");

return dSet.Tables["PersonTable"];

}

catch

{

throw;

}

finally

{

dSet.Dispose();

dAd.Dispose();

conn.Close();

conn.Dispose();

}

}



///

/// Delete record from database

///


///

///

public int Delete(int personID)

{

SqlConnection conn = new SqlConnection(connStr);

conn.Open();

SqlCommand dCmd = new SqlCommand("DeleteData", conn);

dCmd.CommandType = CommandType.StoredProcedure;

try

{

dCmd.Parameters.AddWithValue("@personID", personID);

return dCmd.ExecuteNonQuery();

}

catch

{

throw;

}

finally

{

dCmd.Dispose();

conn.Close();

conn.Dispose();

}

}



}


In the above code, I have a member variable called connStr that is getting database connection string from my web.config file that is being used through out the class. I have separate method for inserting, deleting, updating records into database and loading records from database. I am not goint into details of how I am connecting database and manipulating the data just to make this tutorials short.

Business Access Layer (BAL)

Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).

Code for Business Access Layer

- Hide Code

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;



///

/// Summary description for PersonBAL3

///


public class PersonBAL3

{

public PersonBAL3()

{



}



///

/// insert records into database

///


///

///

///

///

public int Insert(string firstName, string lastName, int age)

{

PersonDAL3 pDAL = new PersonDAL3();

try

{

return pDAL.Insert(firstName, lastName, age);

}

catch

{

throw;

}

finally

{

pDAL = null;

}

}



///

/// Update records into database

///


///

///

///

///

///

public int Update(int personID, string firstName, string lastName, int age)

{

PersonDAL3 pDAL = new PersonDAL3();

try

{

return pDAL.Update(personID, firstName, lastName, age);

}

catch

{

throw;

}

finally

{

pDAL = null;

}

}



///

/// Load records from database

///


///

public DataTable Load()

{

PersonDAL3 pDAL = new PersonDAL3();

try

{

return pDAL.Load();

}

catch

{

throw;

}

finally

{

pDAL = null;

}

}



///

/// Delete record from database

///


///

///

public int Delete(int personID)

{

PersonDAL3 pDAL = new PersonDAL3();

try

{

return pDAL.Delete(personID);

}

catch

{

throw;

}

finally

{

pDAL = null;

}

}



}


Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.

Presentation Layer




Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form

- Hide Code

















































Add Records


First Name:








Display="dynamic">




Last Name:








Display="dynamic">




Age:








Display="dynamic">



Operator="DataTypeCheck" Type="Integer">


 







Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method

- Hide Code

protected void AddRecords(object sender, EventArgs e)

{

//Lets validate the page first

if (!Page.IsValid)

return;



int intResult = 0;

// Page is valid, lets go ahead and insert records

// Instantiate BAL object

PersonBAL3 pBAL = new PersonBAL3();

// Instantiate the object we have to deal with

string firstName = txtFirstName.Text;

string lastName = txtLastName.Text;

int age = Int32.Parse(txtAge.Text);



try

{

intResult = pBAL.Insert(firstName, lastName, age);

if (intResult > 0)

lblMessage.Text = "New record inserted successfully.";

else

lblMessage.Text = "FirstName ["+ txtFirstName.Text +"] alredy exists, try another name";



}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

pBAL = null;

}

}


In the above code, first I am validating the page by using Page.IsValid method just to check if correct data has been entered. Then I have instantiated PersonBAL3 and calling Insert method of it (pBAL.Insert) by passing firstName, lastName, age as parameter.

Dispalying Records into GridView



Create a .aspx file called List.aspx and create a GridView something like displayed into the picture. To list the record into GridView that will also enable us to Edit, Delete record, copy paste following code.

Code for GridView

- Hide Code


DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"

OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord"

OnRowDeleting="DeleteRecord" PageSize="5" >























<%# Eval("FirstName") %>















<%# Eval("LastName") %>















<%# Eval("Age") %>































Code to Load records and Displaying Records into GridView

- Hide Code

private DataTable BindGrid()

{

PersonBAL3 p = new PersonBAL3();



try

{

DataTable dTable = p.Load();

GridView1.DataSource = dTable;

GridView1.DataBind();

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

p = null;

}



return dTable;

}


In the above method I am instantiating PersonBAL3 class and calling Load method to get the record into DataTable and binding it into GridView.

Code to Delete Records


- Hide Code

protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)

{

int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());





// instantiate BAL

PersonBAL3 pBAL = new PersonBAL3();

try

{

pBAL.Delete(personID);



lblMessage.Text = "Record Deleted Successfully.";

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

pBAL = null;

}



GridView1.EditIndex = -1;

// Refresh the list

BindGrid();

}


Above method will fire when Delete link will be clicked on the GridView. In the above code, I am instantiating PersonBAL3 and calling Delete method by passing personID as parameter so that select reocrds will be deleted from datbase.

Code to Update records


- Hide Code

protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)

{

int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

int intResult = 0;

GridViewRow row = GridView1.Rows[e.RowIndex];



TextBox tFN = (TextBox) row.FindControl("txtFName");

TextBox tLN = (TextBox)row.FindControl("txtLName");

TextBox tAge = (TextBox)row.FindControl("txtAge");



// instantiate BAL

PersonBAL3 pBAL = new PersonBAL3();



try

{

intResult = pBAL.Update(personID, tFN.Text, tLN.Text, int.Parse(tAge.Text));

if (intResult > 0)

lblMessage.Text = "Record Updated Successfully.";

else

lblMessage.Text = "Record couldn't updated";

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

} finally

{

pBAL = null;

}



GridView1.EditIndex = -1;

// Refresh the list

BindGrid();

}


Above method will fire when Update link will be clicked for a particular row of the GridView in edit mode. In the above method, I am instantiating PersonBAL3 and calling the Update method by p[assing required parameters.

Now we have all set to go, now just run your project and try inserting records. You can also navigate to another page your created (list.aspx) and try updating, deleting records.

Conclusion

By using 3-Tier architecture in your project you can achive

1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.

Check password strength in javascipt

function passwordStrength(password)

{

var desc = new Array();

desc[0] = "Very Weak";

desc[1] = "Weak";

desc[2] = "Better";

desc[3] = "Medium";

desc[4] = "Strong";

desc[5] = "Strongest";



var score = 0;



//if password bigger than 6 give 1 point

if (password.length > 6) score++;



//if password has both lower and uppercase characters give 1 point

if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;



//if password has at least one number give 1 point

if (password.match(/\d+/)) score++;



//if password has at least one special caracther give 1 point

if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;



//if password bigger than 12 give another 1 point

if (password.length > 12) score++;



document.getElementById("passwordDescription").innerHTML = desc[score];

document.getElementById("passwordStrength").className = "strength" + score;

}



Password strength metter













































Password not entered












FTP File Upload using FtpWebRequest in .Net C#

public void ftpfile(string ftpfilepath, string inputfilepath)
{
string ftphost = "127.0.0.1";
//here correct hostname or IP of the ftp server to be given

string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential("userid", "password");
//userid and password for the ftp server to given

ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(inputfilepath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}

Split String in C#

public static string[] SplitString()
{
string str="|name;87,156|new_ic1;28,239|new_ic2;31,239,156|new_ic3;34,239|new_ic4;38,239|new_ic5;41,239.....|";

// char[] array for the separators
char[] separators = new char[] {'|', ',', ';', '.'};

// string[] array to store splitted valus

string[] values= new string[7];

values = str.Split(separators);

return values;


}

Friday, May 8, 2009

How to Set Focus to Web Form Controls By Using Client-Side Script?

Thursday, May 7, 2009

Add Header and Footer in Word document

Header:

foreach (Word.Section section in this.Application.ActiveDocument.Sections)
{
object fieldEmpty = Word.WdFieldType.wdFieldEmpty;
object autoText = "AUTOTEXT \"Page X of Y\" ";
object preserveFormatting = true;

section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields.Add(
section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range,
ref fieldEmpty, ref autoText, ref preserveFormatting);
section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]
.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
}


Footer:

Word.Document document = this.Application.ActiveDocument;
foreach (Word.Section wordSection in document.Sections)
{
wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]
.Range.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;

wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]
.Range.Font.Size = 20;
wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]
.Range.Text = "Confidential";
}

Wednesday, May 6, 2009

Display data in GridView from Excel Sheet

OleDbConnection DBConnection = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=...;" + "Extended
Properties=\"Excel 8.0;HDR=Yes\"");
DBConnection.Open();
string SQLString = "SELECT * FROM [Sheet1$]";
OleDbCommand DBCommand = new OleDbCommand(SQLString, DBConnection);
IDataReader DBReader = DBCommand.ExecuteReader();
GridView1.DataSource = DBReader;
GridView1.DataBind();
DBReader.Close();
DBConnection.Close();

Rendering the underlying DataTable to Excel

protected void RenderDataTableToExcel_Click(object sender, EventArgs e)

{

DataTable dt = GetData();

string attachment = "attachment; filename=Employee.xls";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/vnd.ms-excel";

string tab = "";

foreach (DataColumn dc in dt.Columns)

{

Response.Write(tab + dc.ColumnName);

tab = "\t";

}

Response.Write("\n");



int i;

foreach (DataRow dr in dt.Rows)

{

tab = "";

for (i = 0; i < dt.Columns.Count; i++)

{

Response.Write(tab + dr[i].ToString());

tab = "\t";

}

Response.Write("\n");

}

Response.End();

}

Tuesday, May 5, 2009

AllowOnlyNumeric() function in Javascript

// JavaScript Function
function AllowOnlyNumeric()
{
// Get the ASCII value of the key that the user entered
var key = window.event.keyCode;
// Verify if the key entered was a numeric character (0-9) or a decimal (.)
if ( (key > 47 && key < 58) || key == 46 )
// If it was, then allow the entry to continue
return;
else
// If it was not, then dispose the key and continue with entry
window.event.returnValue = null;
}

// HTML Code

Use web config for connection string

WebConfig:





Code Behind:

string connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;

DataSet export to Excel

private void createDataInExcel(DataSet ds)
{
Application oXL;
_Workbook oWB;
_Worksheet oSheet;
Range oRng;
string strCurrentDir = Server.MapPath(".") + "\\reports\\";
try
{
oXL = new Application();
oXL.Visible = false;
//Get a new workbook.
oWB = (_Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (_Worksheet)oWB.ActiveSheet;
//System.Data.DataTable dtGridData=ds.Tables[0];
int iRow =2;
if(ds.Tables[0].Rows.Count>0)
{
for(int j=0;j {
oSheet.Cells[1,j+1]=ds.Tables[0].Columns[j].ColumnName;

for(int j=0;j {
oSheet.Cells[1,j+1]=ds.Tables[0].Columns[j].ColumnName;
}
// For each row, print the values of each column.
for(int rowNo=0;rowNo {
for(int colNo=0;colNo {
oSheet.Cells[iRow,colNo+1]=ds.Tables[0].Rows[rowNo][colNo].ToString();
}
}
iRow++;
}
oRng = oSheet.get_Range("A1", "IV1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
string strFile ="report"+ DateTime.Now.Ticks.ToString() +".xls";//+
oWB.SaveAs( strCurrentDir + strFile,XlFileFormat.xlWorkbookNormal,null,null,false,false,XlSaveAsAccessMode.xlShared,false,false,null,null);
// Need all following code to clean up and remove all references!!!
oWB.Close(null,null,null);
oXL.Workbooks.Close();
oXL.Quit();
Marshal.ReleaseComObject (oRng);
Marshal.ReleaseComObject (oXL);
Marshal.ReleaseComObject (oSheet);
Marshal.ReleaseComObject (oWB);
string strMachineName = Request.ServerVariables["SERVER_NAME"];
Response.Redirect("http://" + strMachineName +"/"+"ViewNorthWindSample/reports/"+strFile);
}
catch( Exception theException )
{
Response.Write(theException.Message);
}
}

Web address validations in Javascript with Regex

public static bool IsUrl(string Url) { string strRegex = "^(https?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@ + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184 + "" // allows either IP or domain + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www. + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // port number- :80 + "((/?)" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; Regex re = new Regex(strRegex);
if (re.IsMatch(Url)) return (true); else return (false); }

Open remote URL in Maximize window

public static void mOpenFile(string URL)
{

Screen scr = Screen.PrimaryScreen;
int oldWidth = scr.Bounds.Width;
int oldHeight = scr.Bounds.Height;
Process proc = new Process();
proc.StartInfo.FileName = URL; // put full path in here
proc.StartInfo.WindowStyle =ProcessWindowStyle.Maximized;
proc.Start();
proc.Dispose();
}

Application base path of executable

public static stringGetPath()
{

return System.AppDomain.CurrentDomain.BaseDirectory.ToString();
}

Anonymous Methods in C#

protected void DemoForm_Load(object sender, EventArgs e)
{
List customerList = new List();
customerList.Add(new Customer(00004, "kabir"));
customerList.Add(new Customer(00005, "Krishan"));
customerList.Add(new Customer(00006, "Karan"));
customerList.Sort( delegate(Customer lhs, Customer rhs)
{
return lhs.CustomerID.CompareTo(rhs.CustomerID);
//OR return rhs.CustomerID.CompareTo(lhs.CustomerID);
}); //one can use customerList.Reverse() to reverse the sort order
foreach (Customer customer in customerList)
Response.Write(customer.CustomerID+"");
}
public class Customer
{
private int m_CustomerID = int.MinValue;
private string m_CustomerName = string.Empty;
public Customer(int customerId,string customerName)
{
this.m_CustomerID = customerId;
this.m_CustomerName = customerName;
}
public int CustomerID
{
get { return m_CustomerID;
}
set
{
m_CustomerID = value;
}
}
public string CustomerName
{
get
{
return m_CustomerName;
}
set
{
m_CustomerName = value;
}
}
}
 
Locations of visitors to this page