Sunday, October 25, 2009

Fragment Caching in ASP.NET

ASP.NET provides a mechanism for caching portions of pages, called page fragment caching. To cache a portion of a page, you must first encapsulate the portion of the page you want to cache into a user control. In the user control source file, add an OutputCache directive specifying the Duration and VaryByParam attributes. When that user control is loaded into a page at runtime, it is cached, and all subsequent pages that reference that same user control will retrieve it from the cache.



<%@ OutputCache Duration='60'
VaryByParam='none' %>
<%@ Control Language="'C#'" %>




Here I have user caching on user control, so when ever we used in a page , only partial page will be cached.

To get Collection of checked items in CheckedListBox

private void WhatIsChecked_Click(object sender, System.EventArgs e) {
// Display in a message box all the items that are checked.

// First show the index and check state of all selected items.
foreach(int indexChecked in checkedListBox1.CheckedIndices) {
// The indexChecked variable contains the index of the item.
MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" +
checkedListBox1.GetItemCheckState(indexChecked).ToString() + ".");
}

// Next show the object title and check state for each item selected.
foreach(object itemChecked in checkedListBox1.CheckedItems) {

// Use the IndexOf method to get the index of an item.
MessageBox.Show("Item with title: \"" + itemChecked.ToString() +
"\", is checked. Checked state is: " +
checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
}

}

Wednesday, September 30, 2009

GetDateFormat Method

Example: string sdate = dt.GetDateTimeFormats()[3]; // mm/dd/yyyy

(0) 9/1/2003
(1) 9/1/03
(2) 09/01/03
(3) 09/01/2003
(4) 03/09/01
(5) 2003-09-01
(6) 01-Sep-03
(7) Monday, September 01, 2003
(8) September 01, 2003
(9) Monday, 01 September, 2003
(10) 01 September, 2003
(11) Monday, September 01, 2003 12:00 AM
(12) Monday, September 01, 2003 12:00 AM
(13) Monday, September 01, 2003 0:00
(14) Monday, September 01, 2003 00:00
(15) September 01, 2003 12:00 AM
(16) September 01, 2003 12:00 AM
(17) September 01, 2003 0:00
(18) September 01, 2003 00:00
(19) Monday, 01 September, 2003 12:00 AM
(20) Monday, 01 September, 2003 12:00 AM
(21) Monday, 01 September, 2003 0:00
(22) Monday, 01 September, 2003 00:00
(23) 01 September, 2003 12:00 AM
(24) 01 September, 2003 12:00 AM
(25) 01 September, 2003 0:00
(26) 01 September, 2003 00:00
(27) Monday, September 01, 2003 12:00:00 AM
(28) Monday, September 01, 2003 12:00:00 AM
(29) Monday, September 01, 2003 0:00:00
(30) Monday, September 01, 2003 00:00:00
(31) September 01, 2003 12:00:00 AM
(32) September 01, 2003 12:00:00 AM
(33) September 01, 2003 0:00:00
(34) September 01, 2003 00:00:00
(35) Monday, 01 September, 2003 12:00:00 AM
(36) Monday, 01 September, 2003 12:00:00 AM
(37) Monday, 01 September, 2003 0:00:00
(38) Monday, 01 September, 2003 00:00:00
(39) 01 September, 2003 12:00:00 AM
(40) 01 September, 2003 12:00:00 AM
(41) 01 September, 2003 0:00:00
(42) 01 September, 2003 00:00:00
(43) 9/1/2003 12:00 AM
(44) 9/1/2003 12:00 AM
(45) 9/1/2003 0:00
(46) 9/1/2003 00:00
(47) 9/1/03 12:00 AM
(48) 9/1/03 12:00 AM
(49) 9/1/03 0:00
(50) 9/1/03 00:00
(51) 09/01/03 12:00 AM
(52) 09/01/03 12:00 AM
(53) 09/01/03 0:00
(54) 09/01/03 00:00
(55) 09/01/2003 12:00 AM
(56) 09/01/2003 12:00 AM
(57) 09/01/2003 0:00
(58) 09/01/2003 00:00
(59) 03/09/01 12:00 AM
(60) 03/09/01 12:00 AM
(61) 03/09/01 0:00
(62) 03/09/01 00:00
(63) 2003-09-01 12:00 AM
(64) 2003-09-01 12:00 AM
(65) 2003-09-01 0:00
(66) 2003-09-01 00:00
(67) 01-Sep-03 12:00 AM
(68) 01-Sep-03 12:00 AM
(69) 01-Sep-03 0:00
(70) 01-Sep-03 00:00
(71) 9/1/2003 12:00:00 AM
(72) 9/1/2003 12:00:00 AM
(73) 9/1/2003 0:00:00
(74) 9/1/2003 00:00:00
(75) 9/1/03 12:00:00 AM
(76) 9/1/03 12:00:00 AM
(77) 9/1/03 0:00:00
(78) 9/1/03 00:00:00
(79) 09/01/03 12:00:00 AM
(80) 09/01/03 12:00:00 AM
(81) 09/01/03 0:00:00
(82) 09/01/03 00:00:00
(83) 09/01/2003 12:00:00 AM
(84) 09/01/2003 12:00:00 AM
(85) 09/01/2003 0:00:00
(86) 09/01/2003 00:00:00
(87) 03/09/01 12:00:00 AM
(88) 03/09/01 12:00:00 AM
(89) 03/09/01 0:00:00
(90) 03/09/01 00:00:00
(91) 2003-09-01 12:00:00 AM
(92) 2003-09-01 12:00:00 AM
(93) 2003-09-01 0:00:00
(94) 2003-09-01 00:00:00
(95) 01-Sep-03 12:00:00 AM
(96) 01-Sep-03 12:00:00 AM
(97) 01-Sep-03 0:00:00
(98) 01-Sep-03 00:00:00
(99) September 01
(100) September 01
(101) Mon, 01 Sep 2003 00:00:00 GMT
(102) Mon, 01 Sep 2003 00:00:00 GMT
(103) 2003-09-01T00:00:00
(104) 12:00 AM
(105) 12:00 AM
(106) 0:00
(107) 00:00
(108) 12:00:00 AM
(109) 12:00:00 AM
(110) 0:00:00
(111) 00:00:00
(112) 2003-09-01 00:00:00Z
(113) Monday, September 01, 2003 4:00:00 AM
(114) Monday, September 01, 2003 04:00:00 AM
(115) Monday, September 01, 2003 4:00:00
(116) Monday, September 01, 2003 04:00:00
(117) September 01, 2003 4:00:00 AM
(118) September 01, 2003 04:00:00 AM
(119) September 01, 2003 4:00:00
(120) September 01, 2003 04:00:00
(121) Monday, 01 September, 2003 4:00:00 AM
(122) Monday, 01 September, 2003 04:00:00 AM
(123) Monday, 01 September, 2003 4:00:00
(124) Monday, 01 September, 2003 04:00:00
(125) 01 September, 2003 4:00:00 AM
(126) 01 September, 2003 04:00:00 AM
(127) 01 September, 2003 4:00:00
(128) 01 September, 2003 04:00:00
(129) September, 2003
(130) September, 2003


Here are the results of en-GB - (english, Great Britain) formats:

(0) 01/09/2003
(1) 01/09/03
(2) 1/9/03
(3) 1.9.03
(4) 2003-09-01
(5) 01 September 2003
(6) 1 September 2003
(7) 01 September 2003 00:00
(8) 01 September 2003 0:00
(9) 01 September 2003 12:00 AM
(10) 01 September 2003 12:00 AM
(11) 1 September 2003 00:00
(12) 1 September 2003 0:00
(13) 1 September 2003 12:00 AM
(14) 1 September 2003 12:00 AM
(15) 01 September 2003 00:00:00
(16) 01 September 2003 0:00:00
(17) 01 September 2003 12:00:00 AM
(18) 01 September 2003 12:00:00 AM
(19) 1 September 2003 00:00:00
(20) 1 September 2003 0:00:00
(21) 1 September 2003 12:00:00 AM
(22) 1 September 2003 12:00:00 AM
(23) 01/09/2003 00:00
(24) 01/09/2003 0:00
(25) 01/09/2003 12:00 AM
(26) 01/09/2003 12:00 AM
(27) 01/09/03 00:00
(28) 01/09/03 0:00
(29) 01/09/03 12:00 AM
(30) 01/09/03 12:00 AM
(31) 1/9/03 00:00
(32) 1/9/03 0:00
(33) 1/9/03 12:00 AM
(34) 1/9/03 12:00 AM
(35) 1.9.03 00:00
(36) 1.9.03 0:00
(37) 1.9.03 12:00 AM
(38) 1.9.03 12:00 AM
(39) 2003-09-01 00:00
(40) 2003-09-01 0:00
(41) 2003-09-01 12:00 AM
(42) 2003-09-01 12:00 AM
(43) 01/09/2003 00:00:00
(44) 01/09/2003 0:00:00
(45) 01/09/2003 12:00:00 AM
(46) 01/09/2003 12:00:00 AM
(47) 01/09/03 00:00:00
(48) 01/09/03 0:00:00
(49) 01/09/03 12:00:00 AM
(50) 01/09/03 12:00:00 AM
(51) 1/9/03 00:00:00
(52) 1/9/03 0:00:00
(53) 1/9/03 12:00:00 AM
(54) 1/9/03 12:00:00 AM
(55) 1.9.03 00:00:00
(56) 1.9.03 0:00:00
(57) 1.9.03 12:00:00 AM
(58) 1.9.03 12:00:00 AM
(59) 2003-09-01 00:00:00
(60) 2003-09-01 0:00:00
(61) 2003-09-01 12:00:00 AM
(62) 2003-09-01 12:00:00 AM
(63) 01 September
(64) 01 September
(65) Mon, 01 Sep 2003 00:00:00 GMT
(66) Mon, 01 Sep 2003 00:00:00 GMT
(67) 2003-09-01T00:00:00
(68) 00:00
(69) 0:00
(70) 12:00 AM
(71) 12:00 AM
(72) 00:00:00
(73) 0:00:00
(74) 12:00:00 AM
(75) 12:00:00 AM
(76) 2003-09-01 00:00:00Z
(77) 01 September 2003 04:00:00
(78) 01 September 2003 4:00:00
(79) 01 September 2003 04:00:00 AM
(80) 01 September 2003 4:00:00 AM
(81) 1 September 2003 04:00:00
(82) 1 September 2003 4:00:00
(83) 1 September 2003 04:00:00 AM
(84) 1 September 2003 4:00:00 AM
(85) September 2003
(86) September 2003

Thursday, September 10, 2009

Iterate through SeverVariable in ASP.net

public string ServerVariables()
{

System.Collections.Specialized.NameValueCollection oValues =
new System.Collections.Specialized.NameValueCollection();
oValues = Request.ServerVariables;
for(int i=0; i < oValues.Count ; i++)
{
value += string.Format("Key {0} - Text {1}", oValues.Keys[i].ToString(), oValues.Get(i).ToString());
}


return value;
}

Tuesday, June 30, 2009

Combine byte[]

public byte[] CombineArrays(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
System.Buffer.BlockCopy(a, 0, c, 0, a.Length);
System.Buffer.BlockCopy(b, 0, c, a.Length, b.Length);
return c;
}

Write text file from the byte[]

public static void WriteFileStreamFromArray(string FilePath, byte[] b)
{


FileStream fs = null;

try
{

fs = new FileStream(FilePath,FileMode.Append);

fs.Write(b, 0, b.Length);

}
finally
{
fs.Close();
}


}

Convert byte [] to string

public string convertByteArrayToString(byte[] input)
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(input);
return str;
}

Get Bytes [] from the File

public byte[] GetBytesFromFile(string fullFilePath)
{
// this method is limited to 2^32 byte files (4.2 GB)

FileStream fs = File.OpenRead(fullFilePath);
try
{
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
return bytes;
}
finally
{
fs.Close();
}

}

Read whole text of text file into string

public string mReadFileIntoString(string FullPath, string Separator)
{
string ReturnString = string.Empty;

if (!string.IsNullOrEmpty(FullPath) && !string.IsNullOrEmpty(Separator))
{
if (File.Exists(FullPath))
{
try
{
string Line = string.Empty;

using (FileStream fs = new FileStream(FullPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader rd = new StreamReader(fs, Encoding.Default))
{
while (!rd.EndOfStream)
{
Line = rd.ReadLine();
if (string.IsNullOrEmpty(ReturnString) && !string.IsNullOrEmpty(Line))
ReturnString = Line;
else if (!string.IsNullOrEmpty(ReturnString) && !string.IsNullOrEmpty(Line))
ReturnString = ReturnString + Separator + Line;
}
rd.Close();
}
}

return ReturnString;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("{0} has Input Error, Please Check the Input Files", FullPath);
System.Windows.Forms.MessageBox.Show("Please re-run the application with correct Input");
return string.Empty;
// return string.Format("{0} has Input Error, Please Check the Input Files", FullPath);
}
}
else
{
System.Windows.Forms.MessageBox.Show("{0} does not Exists, Please Check the Input Files", FullPath);
System.Windows.Forms.MessageBox.Show("Please re-run the application with correct Input");
return string.Empty;
// return string.Format("{0} does not Exists, Please Check the Input Files", FullPath);
}
}
return null;
}

Friday, June 26, 2009

Sending Email Via SMTP mail Server

To send emails your SmtpServer should be running. This can be checked using the Internet Services Manager found in Start->Programs->Administrative Tools. When you open the Internet Services Manager you can see whether the Default SMTP Virtual Server is running or not. If the ‘Play’ icon in the toolbar is disabled it means that the Default SMTP Virtual Server is running. You can also check by Right clicking the Default SMTP Virtual Server and see whether ‘Start’ is disabled. If it is so then the Default SMTP Virtual Server is running. This SMTP Service is shipped with Windows XP Professional and Windows 2000 by default.

It is better to test your SMTP Server whether it functions properly before developing any application in ASP.Net to send emails. The easiest way to test the SMTP Server is to open a text editor like Notepad and write,

To: someperson@somesite.com
From: me@mysite.com
Subject: Testing SMTP Server in my system.

Make sure that you are typing some valid email address for the To and From fields in the text file. Now save this text file in c:\inetpub\mailroot\pickup folder. Once you save this file it will disappear indicating that the mail has been sent. If the SMTP Server is not functioning properly it will not disappear indicating that the mail is not sent. The SMTP Service uses the c:\inetpub\mailroot folder for all the mail services.

Now we will see how to send mails from your web application. Create a web application using your Visual Studio.Net IDE. Now drop four text fields in the design page and make the fourth field to accept multi-line content by setting the TextMode property to MultiLine. Drop down a submit button which can be used to send mails when clicked. Now double click the button on the form to open the code window and write code in the Button1_Click() event to send emails. The steps involved in code are:

1. Import the System.Web.Mail namespace
2. Create an instance of the MailMessage class
3. Set the properties of the MailMessage class like To, From, Subject, and Body
4. Use the Send method of the SmtpMail class to send the email message by passing the instance of the MailMessage class as the parameter to the Send method.

The code for sending emails will look somewhat like this after you follow the above steps:

using System.Web.Mail;

protected MailMessage emailMesg;

emailMesg = new MailMessage();
emailMesg.From = txtFrom.Text;
emailMesg.To = txtTo.Text;
emailMesg.Subject = txtSubject.Text;
emailMesg.Body = txtBody.Text;
emailMesg.Priority = MailPriority.High;
SmtpMail.Send(emailMesg);
By default the mail messages are sent as Plain text. It is possible to send mails in the HTML format which allows you to sent mails as web pages which is rich in look. To send emails in the HTML format you need to set the BodyFormat property of the MailMessage instance to MailFormat.Html. If you need to send mail in HTML format the above code would be added one more line like,

emailMesg.BodyFormat = MailFormat.Html;

The Body property of the MailMessage instance would be in the HTML code as given in the following example.


The above HTML code will send the mail message in white color with Maroon background color for the page. You can also send attachments with an email message. For sending attachments you have to use the MailAttachment class available. The code given below will add a file as attachment to the email message.

protected MailAttachment emailAttach;
emailAttach = new MailAttachment(@"path-to-the-document");
emailMesg.Attachments.Add(emailAttach)

This code has to be given before using the Send method. The path to the document to be attached can also be given from the File Input field in the HTML code.

Thus it is easy to send emails through a web page in your web application. You may try to send emails by following the above methods in your websites

Friday, June 19, 2009

Write CSV from Oralce Reader

public static string mWriteRequired(OracleDataReader rd)
{
StringBuilder sb = new StringBuilder();
//For field Names
for(int i = 0 ;i< rd.FieldCount;i++)
{
if( i < (rd.FieldCount - 1) )
{
sb.Append("\t" + rd.GetName(i) + "\t" + ",");
}
else
{
sb.Append("\t" + rd.GetName(i) + "\t" + "\n");
}
}
//For field Values
while( rd.Read())
{
for(int i = 0 ;i< rd.FieldCount;i++)
{
if( i < (rd.FieldCount - 1) )
{
sb.Append("\t" + rd.GetValue(i) + "\t" + ",");
}
else
{
sb.Append("\t" + rd.GetValue(i) + "\t" + "\n");
}
}
}
rd.Close();
return sb.ToString();

}

Monday, June 8, 2009

How to display Client Date and Time

function displayTime()
{
var localTime = new Date();
var year= localTime.getYear();
var month= localTime.getMonth() +1;
var date = localTime.getDate();
var hours = localTime .getHours();
var minutes = localTime .getMinutes();
var seconds = localTime .getSeconds();
var div=document.getElementById("div1");
div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
}

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