Friday, March 28, 2008

Tips for working with WinForms DataGridView

Link

Using "params" keyword to pass array of a variable number of arguments

 

The params keyword defines an optional array of a variable number of arguments (parameters).  There can be only one argument with the params keyword, and it must appear at the end of the argument list.  Also, the params keyword must describe a single-dimension array.

public Test( params string[] args )
{
    int count = args.Length;
    Console.Write( "params: " );
    if (count == 0)
        Console.Write( "(no args)" );
    else
    {
        for (int i = 0; i < count; i++)
        {
            string prefix = i == 0 ?
                null : ", ";
            Console.Write( "{0}arg{1}={2}", prefix, i+1, args[i] );
        }
    }
    Console.WriteLine();
}

Source

Wednesday, March 26, 2008

Using the ASP.NET AJAX PageRequestManager to Provide Visual Feedback

 

Source

Creating Custom ASP.NET Server Controls with Embedded JavaScript

 

Great article (could have used it for Lookup Server control)

Source

Catch the end request of UpdatePanel

1. Get instance of PageRequestManager

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

2. Callback function:

function endRequestHandler(sender, eventArgs)
{
    if (eventArgs.get_error() != undefined && eventArgs.get_error().httpStatusCode == '500')
    {
        var error Message = eventArgs.get_error().message;
        eventArgs.set_errorHandler(true);
        alert(errorMessage);
    } else
    {
        //alert($get("hidField").value);
    }
}

Sunday, March 23, 2008

Use the ToString() method to convert a DateTime to a string

 

using System;

class MainClass
{
  public static void Main()
  {
    DateTime myDateTime = new DateTime(2004, 1, 12, 22, 2, 10);
    Console.WriteLine("myDateTime.ToString() = " + myDateTime.ToString());
    Console.WriteLine("myDateTime.ToString(\"d\") = " + myDateTime.ToString("d"));
    Console.WriteLine("myDateTime.ToString(\"D\") = " + myDateTime.ToString("D"));
    Console.WriteLine("myDateTime.ToString(\"f\") = " + myDateTime.ToString("f"));
    Console.WriteLine("myDateTime.ToString(\"F\") = " + myDateTime.ToString("F"));
    Console.WriteLine("myDateTime.ToString(\"g\") = " + myDateTime.ToString("g"));
    Console.WriteLine("myDateTime.ToString(\"G\") = " + myDateTime.ToString("G"));
    Console.WriteLine("myDateTime.ToString(\"m\") = " + myDateTime.ToString("m"));
    Console.WriteLine("myDateTime.ToString(\"r\") = " + myDateTime.ToString("r"));
    Console.WriteLine("myDateTime.ToString(\"s\") = " + myDateTime.ToString("s"));
    Console.WriteLine("myDateTime.ToString(\"t\") = " + myDateTime.ToString("t"));
    Console.WriteLine("myDateTime.ToString(\"T\") = " + myDateTime.ToString("T"));
    Console.WriteLine("myDateTime.ToString(\"u\") = " + myDateTime.ToString("u"));
    Console.WriteLine("myDateTime.ToString(\"U\") = " + myDateTime.ToString("U"));
    Console.WriteLine("myDateTime.ToString(\"y\") = " + myDateTime.ToString("y"));

  }
}

The result is:

myDateTime.ToString() = 12/01/2004 10:02:10 PM
myDateTime.ToString("d") = 12/01/2004
myDateTime.ToString("D") = January 12, 2004
myDateTime.ToString("f") = January 12, 2004 10:02 PM
myDateTime.ToString("F") = January 12, 2004 10:02:10 PM
myDateTime.ToString("g") = 12/01/2004 10:02 PM
myDateTime.ToString("G") = 12/01/2004 10:02:10 PM
myDateTime.ToString("m") = January 12
myDateTime.ToString("r") = Mon, 12 Jan 2004 22:02:10 GMT
myDateTime.ToString("s") = 2004-01-12T22:02:10
myDateTime.ToString("t") = 10:02 PM
myDateTime.ToString("T") = 10:02:10 PM
myDateTime.ToString("u") = 2004-01-12 22:02:10Z
myDateTime.ToString("U") = January 13, 2004 6:02:10 AM
myDateTime.ToString("y") = January, 2004

Source

Saturday, March 22, 2008

Sending Email In ASP.NET 2.0

Step 1: Declare the System.Net.Mail namespace

using System.Net.Mail;

Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using

public MailMessage ( string from, string to, string subject, string body );

The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.

MailMessage message = new MailMessage            ("abc@somedomain.com","administrator@anotherdomain.com","Testing","This is a test mail");

Step 3: To add an attachment to the message, use the Attachment class.

string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
message.Attachments.Add(attach);

Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.

SmtpClient client = new SmtpClient("localhost");
client.Send(message);
 
Additionally, if required, you
 
client.Timeout = 500;
// Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;

 

That’s it. It’s that simple.

To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.

<system.net>

    <mailSettings>

      <smtpfrom="abc@somedomain.com">

        <networkhost="somesmtpserver"port="25"userName="name"password="pass"defaultCredentials="true" />

      </smtp>

    </mailSettings>

</system.net>

References :

http://msdn2.microsoft.com/En-US/library/system.net.mail.mailmessage.aspx

Export GridView To Excel

 

protected void Button1_Click(object sender, EventArgs e)
{
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
    Response.Charset = String.Empty;
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.RenderControl(hw);
    Response.Write(sw.ToString());
    Response.End();
}

 

Source

Paging and Sorting in GridView without using Datasource control

 

<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging" 
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
   string newSortDirection = String.Empty;
   switch (sortDirection)
   {
      case SortDirection.Ascending:
         newSortDirection = "ASC";
         break;
      case SortDirection.Descending:
         newSortDirection = "DESC";
         break;
   }
   return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dataTable = gridView.DataSource as DataTable;
   if (dataTable != null)
   {
      DataView dataView = new DataView(dataTable);
      dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
      gridView.DataSource = dataView;
      gridView.DataBind();
   }
}

Source

Pop-up a Confirmation box before Deleting a row in GridView

 

<asp:TemplateField>
      <ItemTemplate>
        <asp:Button ID="btnDel" runat="server" Text="Delete"
            CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />
      </ItemTemplate>
</asp:TemplateField>

Source

Convert String To Integer

// Convert String to Int
public static int StringToInt(string str)
{
    return Int32.Parse(str);
}

 

int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);

Save and Retrieve Images from the Database using ASP.NET

Source

Highlight a Row in GridView without a postback using ASP.NET and JavaScript

Add "OnRowCreated" event to the GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" OnRowCreated="GridView1_RowCreated">
 
...
 
</asp:GridView>

The event code:

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Attributes.Add("onMouseOver", "this.style.background='#eeff00'");
    e.Row.Attributes.Add("onMouseOut", "this.style.background='#ffffff'");       
}
Source

ASP.NET Validation Controls – Important Points, Tips and Tricks

Source

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX

Link1

Link2

WebMethod Attribute

Vista: Removing old files after sp1 installation

Type vsp1cln.ext in command prompt.

After this, it is not possible to uninstall sp1.

Tuesday, March 18, 2008

Add Windows Explorer to Visual Studio tools menu

To set it up, click Tools, then External Tools..., then click Add.  Now enter the following data:
Title: Windows Explorer
Command: explorer.exe
Arguments: /select,"$(ItemPath)"

Leave Initial directoy blank, and click OK.  Now when you click Tools, Windows Explorer, Windows Explorer will open with the current file you are editing selected.

Wednesday, March 5, 2008

C# - String Concatenation

 

One way to format C# strings is to add strings together using the plus-sign operator, such as:

string fileStats =
    "Bytes=" + bytes.ToString() +
    ", Pages=" + pages.ToString() +
    ", Words=" + words.ToString();

This code will correctly produce the desired output but is inefficient and does not scale as well.
The problem is that in C#, strings are immutable. This means that once a string is created, its value cannot be changed. Instead, when you modify a string, a whole new string is created, and a reference to the new string is returned.
Strings are also interned, which means that if the same string is used in multiple places within an application, all references to that string will point to the same unique string instance in memory.
Back to the example. Since strings are immutable, the code above will create a new string for each addition in the expression, resulting in four extra and unnecessary strings every time the code executes:

"Bytes=2375″
"Bytes=2375, Pages="
"Bytes=2375, Pages=3″
"Bytes=2375, Pages=3, Words="
"Bytes=2375, Pages=3, Words=477″

The first four strings are essentially throw-away strings that will not likely be used again and hence waste memory space and garbage collection cycles.

The correct approach is to use the String.Format method, such as:

string fileStats = String.Format(
    "Bytes={0}, Pages={1}, Words={2}",
    bytes, pages, words );

If you are just concatenating strings and don't have any special formatting requirements, then String.Concat is even faster:

string fileStats = String.Concat(
    "Bytes=", bytes,
    ", Pages=", pages,
    ", Words=", words );

In our testing, String.Format can be 10-50% faster than string addition, and String.Concat can be 50-500% faster, depending on string length and number of iterations. Both options use less memory and have less impact on garbage collection than string addition.
So why are C# strings immutable? There is a lengthy discussion here and here. But in general, mutable strings would be a nightmare to manage in a multithreaded environment. Also, strings are stored as an array of characters, so modifying a string's length would require allocating a new character array anyway. Finally, mutable strings could pose a security risk by allowing software to modify database and system connection strings on the fly.

Source