Niranjan Kala's coding blog

on software development and productivity

How to close a MessageBox after several seconds?

Related to: Close a MessageBox after several seconds.
Scenario:
I need to create a message box or Popup which must be visible for specified time and close automatically after then.

Solution:
There is not inbuilt feature in .net framework to do this. You need to create your custom logic that message box close after a specific time. To do this create a custom message box class which have a timer which close the raised pop message when elapsed time equal to specified time to make it visible to the user.
Here is the custom class:

public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout) {
        new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow(null, _caption);
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

It can be called as below:

AutoClosingMessageBox.Show("Text", "Caption", 1000);
 

How to prevent selection change in drop down from key press when UltraComboEditor’s DropdownStyle set to DropDownList?

Scenario:
Current requirement is that user can select option from drop down from mouse selection only, but whenever use type anything in the drop down it automatically raise control’s ComboBox.SelectionChangeCommitted event with first match that satisfies auto complete condition of the control. As required we need
ignore the key press to raise the ComboBox.SelectionChangeCommitted event of the combo box and it only allow selection only on mouse.

Solution:

 

To do this, I set the control’s DropdownStyle set to DropDownList, but no work correctly. Along this I have to suppress combo box’s key press by handling KeyDown event as below.

LibraryListDropdown libDropdown = null;
public Form1()
{
    InitializeComponent();
    libDropdown = new LibraryListDropdown();
    this.libDropdown.DropDownStyle = DropDownStyle.DropDownList;
    libDropdown.Name = "cmbObjectType";
    libDropdown.SelectionChangeCommitted += new EventHandler(libDropdown_SelectionChangeCommitted);
    libDropdown.KeyDown += libDropdown_KeyDown;
    this.Controls.Add(libDropdown);
    libDropdown.PopulateLibraries();
}

void libDropdown_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true;
}

private void libDropdown_SelectionChangeCommitted(object sender, EventArgs e)
{
    
}

How to display tooltip on mouse hover in particular cell or column cell?

Scenario:  

Today I got an assignment to display tooltip on particular column cell depending on its text that contain some specific prefix to create different tool tip text.  The grid control was used is Infragistics UltraWinGrid to populate data to user.

Solution/Description:

Most of the time I work with DevExpress controls and default win form controls, there we have different approach to get the grid element when hovering mouse over the grid element.  These controls use HitTestInfo to determine that which grid element currently hovered. While looking for the solution I found one Stackoverflow thread - DataGridView.HitTestInfo equivalent in Infragistics UltraWinGrid? . I am also hunting for the same question’s answer that does Infragistics’s UltraGrid control provides functionality similar to that of DataGridView.HitTestInfo?

Source - Task-based Tutorial - How to use ToolTips with the Infragistics UltraWinGrid

 I found out that Infragistics controls don't convert the coordinates, but they use a special Infragistics grid event (MouseEnterElement) to get the element, which the mouse currently hovers over. Also with the Infragistics UltraWinGrid-control it required to keep track of the grid-row, over which the cursor is hovering. In contrast to our generic solution, the position is stored in a data-type provided by the UltraWinGrid-control and not in a Point-structure: 

Public Class Form1
    Inherits System.Windows.Forms.Form 
   ...  
    'Holds the row/column-coordinates of the cell on which
    'the mouse is hovering...
    Private mCurrentCell As Infragistics.Win _ 
                .UltraWinGrid.UltraGridCell = Nothing
  ...

The way of implement for the generic grid-control (in the section on "How to use ToolTips with grid-controls"), the whole logic, to keep track of the current mouse-position in terms of grid-coordinates (row/column) and to provide the tooltip with the content of the current grid-element, is located in the MouseEnterMouseLeave and MouseMove event-handlers. This is slightly different for the UltraWinGrid-control. Of course, the needed logic is also coupled to mouse-events, but the UltraWinGrid-control provides additional mouse-related events, which make the integration even easier. 

 

Code snippet to show tooltip while using UltraWinGrid:

private void ultraGrid1_MouseEnterElement(object sender, UIElementEventArgs e)
{
    if (e.Element is RowUIElement)
    {
        if (e.Element.SelectableItem is UltraGridRow)
        {
            UltraGridRow ultraGridRow = (UltraGridRow)e.Element.SelectableItem;

            if (ultraGridRow.Band.Key == PaletteZoneHVACGroupingConstants.BAND_PARENT)
            {
                toolTip.ToolTipText = "Drag-n-drop here";
                toolTip.Show();
            }
        }                
    }
    else if(e.Element is CellUIElement)
    {
        // Get a refernce to the column.
        UltraGridColumn column = (UltraGridColumn)e.Element.GetContext();
        if (column != null && column.Key == ColumnName.DESIGNTEMPLATE)
        {
            UltraGridCell cell = e.Element.SelectableItem as UltraGridCell;
            if (cell.Row.Band.Key == Constants.BAND_PARENT)
            {
                string toolTipMessage = string.Empty;
                if (cell.Text.StartsWith(Constants.TextDesginChangePrefix))
                {
                    toolTipMessage = ResourceMessage.GetMessage(ResourceConstants. DESGINS_CHANGE);
                }
                else if (cell.Text.StartsWith(Constants.TextParametersChangePrefix))
                {
                    toolTipMessage = ResourceMessage.GetMessage(ResourceConstants.DESGINS_PARAMETERS_CHANGE);
                }
                
                if (!string.IsNullOrWhiteSpace(toolTipMessage))
                {
                    toolTip.ToolTipText = toolTipMessage;
                    toolTip.Show();
                }
            }
        }
    }
}

private void ultraGrid1_MouseLeaveElement(object sender, UIElementEventArgs e)
{
    toolTip.Hide();
}

 

References:

How to set UltraToolTipeInfo in perticular row in win ultra grid control.

display tooltip on mouse hover in cell

 

Debugging Threads with Concurrency Visualizer

Features of Concurrency Visualizer:

  • Shift+Alt+F5
  • Fast processing, faster loading
           o Supports big traces
  • Supports big traces
  • Support s EventSource and custom markers
            o Built-in support for TPL, PLINQ, Sync Data Structures, and Dataflow
            o Built-in support for your own EventSource types
                    § Also provides Visual Studio markers API
  • New Visualizations
             o e.g. defender view

Demo:

Here are few steps to know that how to utilize “Concurrency Visualizer” for multithreaded applications.

  1. Create a Console project.
  2. Create custom EventSource to trace in the visualizer as below:
    [EventSource(Guid = "7BBB4E52-7DA7-45EB-B6C2-C01D460A087C")]
    class MyEventSource : EventSource
    {
        internal static MyEventSource log = new MyEventSource();
    
        [Event(1)]
        public void SomeEventHandled(int data)
        {
            WriteEvent(1, data);
        }
    }

    To provide GUID to the event source use “guidgen” and copy newly generated GUID. Then put it in the attribute of the EventSource class.



  3. Now complete the test code to proceed the demo.

    Full code snippet:
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConcurrencyVisualizerDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var list = new List<Task>();
                for (int i = 0; i < 10; i++)
                {
                    list.Add(Task.Run(() =>
                        {
                            //Loging here
                            MyEventSource.log.SomeEventHandled(21);
                            Thread.SpinWait(1000000);
                        }));
                }
                Task.WaitAll(list.ToArray());
            }
    
            [EventSource(Guid = "7BBB4E52-7DA7-45EB-B6C2-C01D460A087C")]
            class MyEventSource : EventSource
            {
                internal static MyEventSource log = new MyEventSource();
    
                [Event(1)]
                public void SomeEventHandled(int data)
                {
                    WriteEvent(1, data);
                }
            }
        }
    }
  4. There is optional extension “Concurrency Visualizer” for visual studio, which visual all the data to debug the concurrency between the treads. After installing this, you can find the option under Analyze menu. See image below:

    clip_image004
  5. Now copy the GUID  of MyEventSource and go to the Concurrency Visualizer’s settings. Then add new provider and put this copied guid in the provider.
    Analyze->Concurrency Visualizer->Advance Settings->Markers

    image

    Provide name and paste copied guid in the Privider GUID field. Click ok to complete provider addition.
  6. Now start Concurrency Visualizer by pressing Shift+Alt+F5 and it will start Shift+Alt+F5. Now it will start generating reports. See the below images:

    image

    image

    image

    image

 

Welcome to BlogEngine.NET 3.1

If you see this post it means that BlogEngine.NET is running and the hard part of creating your own blog is done. There is only a few things left to do.

Write Permissions

To be able to log in, write posts and customize blog, you need to enable write permissions on the App_Data and Custom folders. If your blog is hosted at a hosting provider, you can either log into your account’s admin page or call the support.

If you wish to use a database to store your blog data, we still encourage you to enable this write access for an images you may wish to store for your blog posts.  If you are interested in using Microsoft SQL Server, MySQL, SQL CE, or other databases, please see the BlogEngine docs to get started.

Security

When you've got write permissions set, you need to change the username and password. Find the sign-in link located either at the bottom or top of the page depending on your current theme and click it. Now enter "admin" in both the username and password fields and click the button. You will now see an admin menu appear. It has a link to the "Users" admin page. From there you can change password, create new users and set roles and permissions. Passwords are hashed by default so you better configure email in settings for password recovery to work or learn how to do it manually.

Configuration and Profile

Now that you have your blog secured, take a look through the settings and give your new blog a title.  BlogEngine.NET is set up to take full advantage of many semantic formats and technologies such as FOAF, SIOC and APML. It means that the content stored in your BlogEngine.NET installation will be fully portable and auto-discoverable.  Be sure to fill in your author profile to take better advantage of this.

Themes, Widgets & Extensions

One last thing to consider is customizing the look and behavior of your blog. We have themes, widgets and extensions available right out of the box. You can install more right from admin panel under Custom/Gallery.

On the web

You can find news about BlogEngine.NET on the official website. For tutorials, documentation, tips and tricks visit our docs site. The ongoing development of BlogEngine.NET can be followed at CodePlex where the daily builds will be published for anyone to download.

Good luck and happy writing.

The BlogEngine.NET team

What is the use of AsyncCallback in Client server programs and GUI improvements? why should we use it?

When the asyn method finishes processing, the AsyncCallback method is automatically called, where post processing stmts can be executed. With this technique there is no need to poll or wait for the asyn thread to complete.

This is some explanation on Aynsc Call back usage:

Callback Model: The callback model requires that we specify a method to callback on and include any state that we need in the callback method to complete the call. The callback model can be seen in the following example:

static byte[] buffer = new byte[100];

static void TestCallbackAPM()
{
    string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");

    FileStream strm = new FileStream(filename,
        FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
        FileOptions.Asynchronous);

    // Make the asynchronous call
    IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
        new AsyncCallback(CompleteRead), strm);
}

In this model, we are creating a new AsyncCallback delegate, specifying a method to call (on another thread) when the operation is complete. In addition, we are specifying some object that we might need as the state of the call. For this example, we are sending the stream object in because we will need to call EndRead and close the stream.

The method that we create to be called at the end of the call would look somewhat like this:

static void CompleteRead(IAsyncResult result)
{
    Console.WriteLine("Read Completed");

    FileStream strm = (FileStream) result.AsyncState;

    // Finished, so we can call EndRead and it will return without blocking
    int numBytes = strm.EndRead(result);

    // Don't forget to close the stream
    strm.Close();

    Console.WriteLine("Read {0} Bytes", numBytes);
    Console.WriteLine(BitConverter.ToString(buffer));
}

Other techniques are wait-until-done and pollback

Wait-Until-Done Model The wait-until-done model allows you to start the asynchronous call and perform other work. Once the other work is done, you can attempt to end the call and it will block until the asynchronous call is complete.

// Make the asynchronous call
strm.Read(buffer, 0, buffer.Length);
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Do some work here while you wait

// Calling EndRead will block until the Async work is complete
int numBytes = strm.EndRead(result);

Or you can use wait handles.

result.AsyncWaitHandle.WaitOne();

Polling Model The polling method is similar, with the exception that the code will poll the IAsyncResult to see whether it has completed.

// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Poll testing to see if complete
while (!result.IsCompleted)
{
    // Do more work here if the call isn't complete
    Thread.Sleep(100);
}

How to open DateTime picker C# control programmatically on Button Click

You have to use interop to to send request to windows that show DataTimePicker 
on click of the button
//include namespace section 
using System.Runtime.InteropServices;

//declares
[DllImport("user32.dll")]
private static extern bool PostMessageForCalender(
IntPtr hWnd, // handle to destination window
Int32 msg, // message
Int32 wParam, // first message parameter
Int32 lParam // second message parameter
);

const Int32 WM_LBUTTONDOWN = 0x0201;

//method to call  calender dropdown
private void button1_Click(object sender, EventArgs e)
{
    Int32 x = dateTimePicker1.Width - 10;
    Int32 y = dateTimePicker1.Height / 2;
    Int32 lParam = x + y * 0x00010000;

    PostMessageForCalender(dateTimePicker1.Handle, WM_LBUTTONDOWN, 1,lParam);

}

Configuring ASP.NET for sending Email

How ASP.NET Sends Mail

One of the most common uses of forms in a website is to send email. Sending email from a website used to be a complex and difficult task, but as with so many other tasks that used to be complex, ASP.NET makes sending email easy.

In this chapter you'll see two different classes from the .NET Framework used to send email with ASP.NET; the System.Net.SmtpClient class and the System.Net.MailMessage class.

The System.Net.SmtpClient Class

The SmtpClient class facilitates the sending of email with the Simple Mail Transfer Protocol or SMTP. The SmtpClient class is used to connect your ASP.NET application to the network (either the Internet or another network) and to authenticate you (if necessary) to the SMTP mail server.

We will use a few properties of the SmtpClient class to connect to the SMTP server on the network:

  • Host Property— The Host property is used to specify the name of the SMTP server to which you are connecting.

  • Port Property— Every connection on a network takes place over a specific channel on the network called a port. SMTP communication takes place on port 25 by default. The Port property defaults to a value of 25, but if your SMTP server requires a different port, you can specify that by using the Port property.

    Tip: It's uncommon for an SMTP server to not use port 25. Ask your network administrator, ISP, or hosting company if you're not sure what port your SMTP server uses.

  • Credentials Property— Most SMTP servers require that you provide a username and password or otherwise authenticate yourself before you can send email.

    Some SMTP servers (usually on corporate networks) allow you to use the credentials of the account running your ASP.NET code. In those cases, you can specify to use the default credentials, but in this web application, we'll specify a username and password.

The System.Net.MailMessage Class

The MailMessage class (as you've likely guessed) represents the actual message that is sent. The following list shows some of the properties of the MailMessage class, all of which should be self-explanatory:

  • To— The destination email address(es) for the message.

  • From— The email address of the sender.

  • Cc— The email address(es) that appear on the CC line.

  • Bcc— The email address(es) that appear on the BCC line.

  • Subject— The email's subject.

  • Attachments— A list of file attachments included with the email.

  • IsBodyHtml— A Boolean property that specifies whether or not the Body property uses HTML code.

  • Body The body of the email being sent. This is the actual text of the email message.

After you set the properties of the MailMessage class, you call the Send method and the SmtpClient class is used to send the message.

Modifying the Configuration File for internal Email Settings

In a real-world ASP.NET application, you may be sending email from many pages in your application. If the SMTP properties (such as server name, username, password, and so on) change, it's not efficient to have to make changes on each page that sends email.

Fortunately, many of the properties of the SmtpClient class can be specified in the configuration file for your ASP.NET application. If you specify properties in the configuration file, you have to modify only the configuration file if any of those properties change, and all pages that send email will automatically use the new settings.

Tip: If you specify a setting in your server-side code that's already been specified in your configuration file, the setting that you specify in code overrides the setting in the configuration file.

Adding Email Configuration to the web.config File

Mail configuration is specified in the <system.net> section of the web.config file. The web.config file doesn't contain a <system.net> section by default, so you need to add one.

Open the web application and then open the web.config file in Visual Web Developer. Add the following code to the web.config file directly before the opening <system.web> element:

<system.net>
    <mailSettings>
        <smtp>
            <network host="smtp.yourServer.com"
                     password="yourPassword"
                     userName="yourUsername" />
        </smtp>
    </mailSettings>
</system.net>

Tip: The settings you specify for your SMTP server are often the same settings you use in your email client for the outgoing mail server for your domain. Your hosting company probably has instructions for setting up email clients on their website that you can use to find settings for your configuration file.

Using the Web Site Administration Tool

You can also use the Web Site Administration Tool to configure your SMTP settings. The Web Site Administration Tool enables you to add and edit SMTP settings while minimizing the possibility of errors due to incorrect configuration or typographical errors.

Tip: When using the Web Site Administration Tool to configure SMTP settings, all entries are optional. If you don't provide a value for a required property in the configuration file, you need to provide it in your ASP.NET server-side code.

To use the Web Site Administration Tool to configure your SMTP settings, follow these steps:

1. Open your website and click the ASP.NET Configuration button at the top of the Solution Explorer window

2. Click the Application tab or the Application Configuration link in the Web Site Administration Tool.

3. Click the Configure SMTP Email Settings link on the Application page of the Web Site Administration Tool.

4. Enter your SMTP server name, as shown in Figure 1.

Figure 1. SMTP configuration can be modified on the Application tab of the Web Site Administration Tool.

 

5. Enter the port if necessary. In most cases, the default value of 25 should not be changed.

6. Enter an email address in the From text box if desired. The email address you enter here will show up as the sender of the email that ASP.NET sends.

7. Select an authentication method. Choose None if your SMTP server doesn't require authentication. Choose Basic if your SMTP server requires authentication that differs from the credentials of the account that your ASP.NET code is using. Choose NTLM if you want to use the credentials of the account running your ASP.NET code.

8. Click Save to save the configuration settings to the web.config file in your application.

After you click Save, the Web Site Administration Tool automatically updates your web.config file with the changes, and they take effect immediately.

What Happens When a Configuration File Is Saved

Every ASP.NET application runs inside a special area set aside in memory called an application domain. The purpose of the application domain is to provide isolation between different ASP.NET applications. The application domain ensures that one ASP.NET application doesn't access protected areas of another ASP.NET application.

When an application domain starts up, ASP.NET reads the information in the configuration file to set up the application domain. It then begins monitoring certain folders and files within the application for any changes. If a change is detected, ASP.NET shuts down the application domain and restarts it again so that any changes will take effect.

When you make a modification to the application's web.config file (whether by directly modifying the file or by modifying it indirectly with a tool such as the Web Site Administration Tool), ASP.NET immediately recycles the application pool so that the new configuration applies immediately to the application.

 

 

 

Sample Code to send Email in Asp.net without ASP.net web.config settings:

try
        {
            MailMessage msg = new MailMessage();

            msg.To.Add(toId);
            MailAddress frmAdd = new MailAddress(frmyahoo);
            msg.From = frmAdd;

            //Check user enter CC address or not
            if (ccId != "")
            {
                msg.CC.Add(ccId);
            }
            //Check user enter BCC address or not
            if (bccId != "")
            {
                msg.Bcc.Add(bccId);
            }
            msg.Subject = msgsubject;
            //Check for attachment is there
            if (FileUpload1.HasFile)
            {
                msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
            }
            msg.IsBodyHtml = true;
            msg.Body = mailContent;

            SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
            NetworkCredential NetCrd = new NetworkCredential(frmyahoo, frmpwd);
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = NetCrd;
            mailClient.EnableSsl = false;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.Send(msg);

            clear();
            Label1.Text = "Mail Sent Successfully";
        }
        catch (Exception ex)
        {
            Label1.Text = "Unable to send Mail Please try again later";
        }
    }

Sample Code to send email in ASP.net with web.config with <mailsettings>

try
            {
                MailMessage mailMessage = new System.Net.Mail.MailMessage();
                mailMessage.To.Add(userEmailAddress);
                mailMessage.Subject = "Subject";
                mailMessage.Body = "Body Text";
                var smtpClient = new SmtpClient();
                smtpClient.Send(mailMessage);
                return "Mail send successfully";
            }
            catch (SmtpException ex)
            {
                return "Mail send failed:" + ex.Message;
            }

manual MailSettings for web.config

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="from@yourdomain.com">
        <network host="smtp server addresss" userName="username" password="password" 
          defaultCredentials="false" port="xxx" enableSsl="true"  />
      </smtp>
    </mailSettings>
  </system.net>

Displaying ASP GridView row index number

You can achieve this through two way:

Method 1

Step 1. Add this your GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
            DataSourceID="SqlDataSource1" OnRowCreated="GridView1_RowCreated" >

  <Columns>
            <asp:TemplateField HeaderText="RowId">
            <ItemTemplate><asp:Label runat="server" />                      
            </ItemTemplate>            
            </asp:TemplateField> 
...
</Columns>

Step 2: Add following GridView Event code snippet to your code – behind file (.cs)

protected void GridView1_RowCreated(object sender, 
			System.Web.UI.WebControls.GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) {
        // Retrieve the Label from the first column.
        Label myLabel = (Label)e.Row.Cells[0].Controls[0]; 

        // Set Label text equal to the rowIndex +1
        myLabel.Text = e.Row.RowIndex.ToString() + 1; 
    }
}

Method 2
The another way to do it is this one in the Columns section of your GridView control:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" DataSourceID="SqlDataSource1" PageSize="5">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <%# Container.DataItemIndex + 1 %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
            <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
        </Columns>
    </asp:GridView>

Inline ASP.Net Tags, Code Render Blocks... (<%$, <%=, <%, <%#, etc.)

Code render blocks define inline code or inline expressions that execute when the page is rendered. There are two styles of code render blocks: inline code and inline expressions.
Use inline expressions as a shortcut for calling the Write method.

<% inline code %>
<%=inline expression %>

thee tags are evaluated during the Render portion of the page load cycle.

<% ... %>

The most basic inline tag, basically runs normal code:

<% if (User.IsInRole("admin")) { %> 
  You can see this 
<% } else { %> 
  You are no admin fool! 
<%} %>

http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx

 

<%= ... %>

Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable:

The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>

http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx

*note: <%= is the equivalent of Response.Write() .

 

<%# .. %>

Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:

<asp:Repeater ID="rptMeetings" DataSourceID="meetings" runat="server"> 
    <ItemTemplate> 
        <%# Eval("MeetingName") %> 
    </ItemTemplate> 
</asp:Repeater>

 

http://msdn2.microsoft.com/en-us/library/ms178366.aspx

 

<%$ ... %>

Used for expressions, not code; often seen with DataSources:

<asp:SqlDataSource ID="party" runat="server" ConnectionString="<%$ ConnectionStrings:letsParty %>" SelectCommand="SELECT * FROM [table]" />

http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx

 

<%@ ... %>

This is for directive syntax; basically the stuff you see at the top your your aspx pages like control registration and page declaration:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> 
<%@ Register TagPrefix="wp" Namespace="CustomWebParts" %>

http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx

 

<%-- ... --%>

This is a server side comment, stuff you don't want anyone without code access to see:

    <asp:Label ID="lblAwesome" runat="server" /> 
    <%-- sometimes end users make me angry --%> 
    <asp:LinkButton ID="lbEdit" Text="Edit" OnClick="Edit_Click" runat="server" />

http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx