Archive for the “C#” Category

Time again to dig into the next question on Scott Hanselman’s list of ASP.NET interview questions.  This question focuses on PostBacks; specifically, this question is posed:

"Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality?"

Lets start with what a simple definition: A PostBack happens when the contents of a web page is sent back to the server for processing.

From the definition, it would seem that most (if not all) PostBacks happen on the server side.  Indeed, server-side PostBacks are the type you’re probably most familiar with.  For example, any time a component is declared with runat=server, it is taking advantage of the server-side handling of PostBacks.  When a PostBack happens, the information entered into a form is sent back to the same page for processing.  Newer versions of ASP.NET allow for cross-page PostBacks, but the vast majority of pages still post back to themselves.  That being said, there are a few things to remember when working with PostBacks:

  • The PostBack request contains the current value of every control within your form declared with runat=server.  The data is commonly referred to as the Post Data
  • The Post Data will also contain the content of the page’s ViewState.  In this case (unless specified otherwise), the ViewState will contain the original value of these same controls before their values were changed
  • Finally, the Post Data will contain the ID of the control that initiated the PostBack (for example, if you clicked a ‘Submit’ button, the ID of that button will be part of the Post Data

There is some additional information on ViewState and server-side PostBacks on MSDN, but that should get you started.

Regarding client-side PostBacks, and despite my best efforts to fully research the topic, without being able to directly talk to a potential interviewer posing this question, I’m not exactly certain what kind of answer Mr. Hanselman is looking for.  Almost every article I’ve found online seems to suggest that a client-side PostBack is little more than having an ASP.NET button, link button, or image button call a bit of JavaScript either before doing a server-side PostBack (i.e. displaying a confirmation dialog or doing some form validation) or in lieu of doing a server-side PostBack at all.  If that is indeed the case, this can be accomplished a few different ways.

For example, assume you have an ASP.NET button declared with ID = "btnSubmit"

<asp:button id="btnSubmit" runat="server" text="Do Something Potentially Destructive?"/>

And you want to add a confirmation dialog before the server-side PostBack occurs.  One way is to add an attribute to the control on PageLoad:

void Page_Load(object sender, EventArgs e)
{
  
btnSubmit.Attributes.Add("onclick", "return confirm(‘Are you want to do something potentially destructive?’);");
}

Starting with .NET 2.0, you can also take advantage of the OnClientClick property to accomplish the same goal:

<asp:button id="btnSubmit" runat="server" OnClientClick="return confirm(‘Are you sure you want to do something potentially destructive?’);" text="Do Something Potentially Destructive?" />

Assuming I’ve correctly interpreted the question, I believe that should set you on your way.  If not, please let me know in the comments.  This blog is as much a learning experience for me as it is for any potential readers, so don’t be shy. :)

Now, there is one lingering branch of this question that still needs answered.  Specifically, how do we chain our own JavaScript without losing PostBack functionality?  Well, again, to really answer this question, it would be best to get some more information as to exactly what is being asked.  That is, if you use one of the two methods above to add a confirmation dialog to a button, you won’t lost PostBack functionality.  In fact, I had to dig a bit deeper to really find a good example of how to answer this question.  Surprisingly (or maybe not-so-surprisingly), the answer came from Scott’s site.

What I think is being asked here is better understood when thinking about an ASP.NET LinkButton as opposed to your everyday Button.  If you’ve ever noticed, ASP.NET achieves the functionality of LinkButtons by creating and then calling a JavaScript function called __doPostBack that takes in two arguments — an EventTarget (the server-side function to be called) and an EventArgument (any arguments to that function).  This is important to note because if you now wanted to create your own JavaScript function that did some client-side processing and then called the appropriate server-side method, you would need to know the signature of this __doPostBack method.  It turns out you can get this method signature by calling Page.GetPostBackEventReference.  Tying this altogether, assume we have a LinkButton with ID = "lnkSubmit" and you want to set the NavigateUrl on PageLoad to your own JavaScript function that calls __doPostBack when it is finished.  You could do this in the following manner:

string PostBackReference = Page.GetPostBackEventReference(lnkSubmit);
lnkSubmit.NavigateUrl = BuildMyJavaScriptFunction("My first parameter", PostBackReference);

That should wrap it up.  If you have any questions, leave them in the comments!

Comments 5 Comments »

So, it’s time to tackle the next question in the original list of Scott Hanselman’s ASP.NET interview questions.  This time, the question asks to describe what events are fired when binding data to a data grid and what they could be used for.  If you are looking for a very technical overview, MSDN has the scoop on all of the data grid binding events.  Since this is a blog (and therefore not meant to be a technical document), I’ll try to approach the topic with a bit more of a pragmatic eye and give some example code usages.

On the the events!

The easiest way to figure out what events you have at your disposal is to create a DataGrid on your .aspx page and browse through the different intellisense options that pop-up beginning with "On".

Intellisense


As you can see in the image above, DataGrids in ASP.NET can do much more than display data.  However, in this case, we are only interested in the events that get fired as part of the process that binds the data to the DataGrid.  It turns out, out of the myriad of events that can be utilized, only two of them happen as part of the data binding process.  These two events are the ItemCreated event and the ItemDataBound event.

 

ItemCreated:

The ItemCreated event is fired when an item in a DataGrid control is created.  This means that at the time the event is fired, the DataGrid does not yet know about the data that will be bound to it.  So, if the logic of your method depends on this data being available to the control, you’re better off using the ItemDataBound event.  Other than that, the ItemCreate event differentiates itself in one other way from the ItemDataBound event: the ItemCreated event is raised when data is bound to the control and during round-trips (postbacks).  These qualities make the event especially well-suited to add custom attributes to a DataRow (such as onmouseover or other javascript events) or to control the appearance in ways that do not depend on the data within the DataRow (such as making every 10th row a different color).

 

ItemDataBound:

The ItemDataBound event is fired after after an item in a DataGrid control is bound.  This means that (unlike the ItemCreated event) you can add special formatting to a DataRow that is dependent upon the data contained within that row.  Since ItemDataBound is fired after the ItemCreated event, it is within this event that you are presented with the final opportunity to access the data before it is rendered to the client.  These qualities make the event well-suited for changing the appearance of a row or cell based on the data within that row or cell (such as highlighting outliers or other important information).

 

Example:

Assume we have the following DataGrid declared on our .aspx page:

<asp:DataGrid ID="MainDataGrid"
    runat
="server"
    AutoGenerateColumns
="true"
    OnItemDataBound
="MainDataGrid_ItemDataBound"
    OnItemCreated
="MainDataGrid_ItemCreated" />

On the code behind page then, we can create the following two methods to handle adding titles to header row, to specify more descriptive headers, and to change the row background color based on an employee’s salary:

protected void MainDataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
   
//If the item is in the header
    if (e.Item.ItemType == ListItemType.Header)
   
{
       
//Iterate through each cell
        foreach(TableCell item in e.Item.Cells)
       
{
           
//Add the title attribute — we could just as easily
            //add a javascript onmouseover event here
            item.Attributes.Add("title", item.Text);
       
}

        //Since the header values are set before we have access
        //to the data, we can modify the third column header to
        //be a bit more descriptive
        e.Item.Cells[2].Text = "Salary (in US$)";
   
}
}

 
protected void MainDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
   
//Since DataGrid differentiates between Items and AlternatingItems, you sometimes have to check
    //for one *or* the other
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   
{
       
//Here we will modify the row color based on the salary
        //We can only do this within ItemDataBound since it relies
        //on the data being available from the data source
        if (Convert.ToInt32(e.Item.Cells[2].Text) < 10000)
       
{
           
e.Item.BackColor = System.Drawing.Color.LightPink;
       
}
       
else if (Convert.ToInt32(e.Item.Cells[2].Text) < 1000000)
       
{
           
e.Item.BackColor = System.Drawing.Color.LightBlue;
       
}
       
else
       
{
           
e.Item.BackColor = System.Drawing.Color.LightGreen;
       
}
   
}
}

 

I created a sample DataTable that I have bound to.  Using the two methods above, I get the following output in the browser:

 SampleOutput 


If it helps, I have include a sample project that you can use to get started with your project.  You can download it here.

Hopefully that gives you a good idea of how best to take advantage of the events fired as part of binding data to a DataGrid.  If you have any questions or comments, please feel free to add them to the comment section.  I find these blog entries to be a great learning experience for me, so I’d love to know if they’ve been helpful to anyone else.

Comments 1 Comment »

Welcome to the third entry in my series of posted dedicated to answering Scott Hanselman’s ASP.NET interview questions.  In this entry, we will tackle using custom extensions (Scott uses *.jsp as an example to preserve backwards compatibility) to serve up ASP.NET pages.  By custom extensions, I mean that if you go to http://localhost/default.jsp you can actually direct the webserver to process the request using the ASP.NET worker process.

As it turns out, custom extensions are not all that difficult in ASP.NET assuming you have no aversions to getting under the hood and making some changes to IIS.  It also ties back nicely to the last post I did in this series that covered ASHX files and HttpHandlers.

To start out, lets first instruct IIS to send any request ending in a *.jsp extension to be passed on to the ASP.NET worker process.  To do this, open up Internet Information Services and find the website on your machine that you want to configure:

IIS


Next, select "Configuration" on the Properties page:

Properties


Here, you will be able to add the custom *.jsp extension.  For ease of use, I just copied the configuration values from the *.aspx extension.

Configuration


Extension


Click "OK" until you are back to the main IIS screen and then exit.  At this point, IIS knows that when it receives a request with a *.jsp extension to pass the request along to the ASP.NET worker process.  Next, we need to instruct our application to process these incoming requests using the PageHandlerFactory HttpHandler.  To do this, open up the web.config file and add the following lines to the httpHandlers section in the system.web node:

<httpHandlers>
 
<add path="*.jsp" verb="*" type="System.Web.UI.PageHandlerFactory" validate="true" />
</
httpHandlers>

Also, you’ll need to add the following lines to the compilation node (again in the system.web node):

<buildProviders>
 
<add extension=".jsp" type="System.Web.Compilation.PageBuildProvider" />
</
buildProviders>

Visual Studio 2005 automatically creates the compilation node as self-closing, so here is what it should look like after you’ve added the lines above:

<compilation debug="true" strict="false" explicit="true">
 
<buildProviders>
   
<add extension=".jsp" type="System.Web.Compilation.PageBuildProvider" />
  </
buildProviders>
</compilation>

Now, IIS knows how to pass the request along and your application knows how to process any request with a *.jsp extension.  At this point, we’re basically finished.  If you already have an *.aspx page that you’d like to serve up with a *.jsp extension, all that’s left is to rename it and rebuild your application.  Otherwise, I’ve found it easier to create your pages uses the *.aspx extension and then change it to *.jsp once you’re finished making your code changes.

Here is a screenshot from an application that I configured on my machine before the Page PostBack:

JspLoad


And after the PostBack:

JspPostBack


If you’d like, I also zipped up the solution which can be downloaded here.  If you have any additional questions, please feel free to leave them in the comments!

Comments 1 Comment »

I recently wanted to set up log4net on a project I’ve been working on and found the documentation somewhat lacking when trying to find a quick and easy setup guide.  So, once I had everything set up and working, I resolved to create one myself.

So, in less time than it takes to get a pizza delivered, here is how to quickly get log4net setup on your project.

What you’ll need:

  • The log4net dll (you can find the most recent version here)
  • A .Net project/solution that you’d like to add logging to (you’re on your own here)
  • Access to the Assembly.cs file for said project
  • Access to the app.config or web.config file for said project
  • A place to store your logging files (I will be using C:\ in this example, but this is one area in which the documentation actually excels)

Implementation:

  1. Place the log4net dll somewhere that you can reference it easily.  I like to keep a Libraries folder around in most of my projects to hold any 3rd party dlls, but the choice is up to you.
  2. Add a reference to the dll in your project solution:
    • References
  3. Add the following code to the Assembly.cs file.  More documentation here:
    • // Configure log4net using the .config file
      [assembly: log4net.Config.XmlConfigurator(Watch = true)]
      // This will cause log4net to look for a configuration file
      // called TestApp.exe.config in the application base
      // directory (i.e. the directory containing TestApp.exe)
      // The config file will be watched for changes.
  4. Add the following section to the web/app.config file in the <configuration> node:
    • <configSections>
       
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
      </
      configSections>
  5. Create a new section in the web/app.config using log4net as the node name:
    • <log4net>
       
      <appender name="FileAppender" type="log4net.Appender.FileAppender">
         
      <file value="C:\logfile.txt" />
          <
      appendToFile value="true" />
          <
      layout type="log4net.Layout.PatternLayout">
           
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
          </
      layout>
       
      </appender>
       
      <root>
         
      <level value="DEBUG" />
          <
      appender-ref ref="FileAppender" />
        </
      root>
      </log4net>
  6. At the top of the class in which you want to implement logging, add the using log4net; directive.
  7. Define a static logger variable at the top of your class.  Something like this will work:
    • private static readonly ILog log = LogManager.GetLogger(typeof(Program));
  8. Start adding logging statements to your code, for example:
    • log.Info("Entering application.");
  9. Altogether then, your class might look something like this:
    • using System;
      using System.Collections.Generic;
      using System.Text;
      using log4net;

      namespace log4netDemo
      {
         
      class Program
         
      {
             
      // Define a static logger variable so that it references the name of your class
              private static readonly ILog log = LogManager.GetLogger(typeof(Program));

              static void Main(string[] args)
             
      {
                 
      log.Info("Entering application.");

                  for (int i = 0; i < 10; i++)
                 
      {
                     
      log.DebugFormat("Inside of the loop (i = {0})", i);
                 
      }

                  log.Info("Exiting application.");
             
      }
         
      }
      }

  10. Which would produce this output when run:
    • 2008-05-12 19:53:28,059 [11] INFO  log4netDemo.Program [(null)] – Entering application.
      2008-05-12 19:53:28,260 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 0)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 1)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 2)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 3)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 4)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 5)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 6)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 7)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 8)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 9)
      2008-05-12 19:53:28,280 [11] INFO  log4netDemo.Program [(null)] – Exiting application.

 

That really should be all there is to it.  Although I did find the lack of a simple, quickstart guide daunting, there is actually a lot of good documentation on the log4net site.  Particularly, if you want to use a different appender or read a more general introduction.

If you’re interested, I’ve zipped up a sample solution using the code above.  You can download it here.

Comments 7 Comments »

Our main application at work was primarily built using .Net 1.1.  That being said, most of the collection objects inherit from a base class that gives support for things like adding to, removing from, and enumerating through the collection.  We have since migrated the application to .Net 2.0 but there has been little incentive to go back and update these collections to use the support for generics that was added as part of the .Net 2.0 framework.

 

Recently I took on the role of lead developer for a smaller, internal project that will live independently from any of our other apps.  The fact that this app will not use any of the business objects or the same database meant that I was free to utilize whatever technology I thought best suited for the project.  Eventually, I settled on developing the application in the newly released .Net 3.5 framework using C# 3.0 mainly due to the fact that I was anxious to start using Linq (I know, probably not the most solid reason for choosing a platform, but it is a reason, and that’s really all I needed).  When I started building up my business object layer, I eventually came across the need for collections.  The base class that was ported over from .Net 1.1 would have been more than adequate, but I knew that if I wanted to use Linq, I would have to inherit from something that implemented the IEnumerable interface.  After looking around the web and playing around with a few different methods, I eventually decided that the easiest way to build up the collection would be to inherit from the List<T> generic class (where ‘T’ is the type of object that will live in the collection).

 

Here is an example using a widget object to populate a collection of widget:

 

The widget object:

public class Widget
{
   
/// <summary>
    /// The Widget ID
    /// </summary>
    public int WidgetID { get; set; }

    /// <summary>
    /// The Widget Name
    /// </summary>
    public string WidgetName { get; set; }

    /// <summary>
    /// The default public constructor.
    /// </summary>
    /// <param name="ID">The widget ID</param>
    /// <param name="Name">The widget Name</param>
    public Widget(int ID, int Name)
   
{
       
WidgetID = ID;
       
WidgetName = Name;
   
}
}

 

The widget collection:

public class WidgetCollection : List<Widget>
{
   
/// <summary>
    /// The default public constructor.
    /// </summary>
    public WidgetCollection()
   
{
       
Reload();
   
}

    /// <summary>
    /// Load the collection.  This would normally be done from the database.
    /// </summary>
    private void Load()
   
{
       
this.Add(new Widget(1, "Widget1"));
       
this.Add(new Widget(2, "Widget2"));
   
}

    /// <summary>
    /// Clear out the collection and reload it.
    /// </summary>
    public void Reload()
   
{
       
this.Clear();
       
Load();
   
}
}

 

This gives me the ability to then bind dropdowns within the program as well as the ability to manipulate the collection using Linq (which is what I was after all along).

 

So, how about you?  Is inheriting from List<T> a pretty standard way of building up collections, or have I stumbled upon one of those programming faux pas that more experienced developers know to avoid?

Comments No Comments »

This is my first post, so bear with me.

I’m currently working to create a website for the start-up software company Higher Symmetry Software. At the moment, Higher Symmetry has yet to officially release their first product, so in the meantime, we’re trying to determine a way to easily gauge user interest. I came up with the simple idea of creating an ASP.NET webform that takes in a user’s email address and generates an automatic email that will be sent to an email distribution list. So, my first post will focus on creating a form to generate and send an email using C# and System.Web.Mail.

The html (aspx) side is fairly simple. Just a form element with a textbox and a button. In an aspx page, that looks like this:

<form id="Form1" method="post" runat="server">
   
<div align="center" style="padding: 15px" id="submitemail" runat="server">
        Interested in Product X?
<br /><br />
        Enter your email address below to get updates as they become available!<
br /><br />
        <
asp:TextBox ID="txtEmailUpdates" Runat="server" style="width: 200px" /><br /><br />
        <
asp:Button ID="btnSubmit" Runat="server" Text="Submit" />
    </
div>
   
<div align="center" style="padding: 15px" id="emailsent" runat="server" visible="false">
        Thanks for your support!  We will keep you updated!
   
</div>
</form>

If you notice here, I’ve enclosed the main body of the form within one div and the success message within another div. I prefer this to using an asp.net placeholder control simply for the flexibility that div tags have with CSS. I’ll demonstrate how to show and hide these divs later in the post.

The code-behind page is a little more complex, but still fairly straightforward. First, import the libraries you’ll need. In this case, all you need are System and System.Web.Mail. Next, make sure that you have declared all of your controls (or have Visual Studio auto-generate them for you) and that your btnSubmit_Click method has been declared and created. In that method, you’ll need something similar to the following:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
   
string strTo = "you@email.com";
   
string strFrom = txtEmailUpdates.Text.Trim();
   
string strSubject = "Website submission";

    try
   
{
       
SmtpMail.SmtpServer = "smtp.yourserver.com";
       
SmtpMail.Send(strFrom, strTo, strSubject,String.Format("{0} is interested in Product X.", txtEmailUpdates.Text.Trim()));
   
}
   
catch( Exception )
   
{
       
//Do nothing — just let them assume they submitted the email
    }

    submitemail.Visible = false;
   
emailsent.Visible = true;
}


That should be it. To make things more consistent across the application, I like to put the smtp server and the email address in the web.config file, but it’s up to you.

Comments No Comments »