Page10 - ASP.NET 2.0 Interview Questions

Q40. How do we enabling Caching for a DataSource Control?

A40. To enable caching for the SqlDataSource control (and also ObjectDataSource), set the EnableCaching property to true. You can specify the length of time (in seconds) to store an entry in the cache using the CacheDuration property. You can also set the CacheExpirationPolicy property to either Sliding or Absolute just as you can do from the cache API. Caching is only supported on the SqlDataSource control when the DataSourceMode property is set to "DataSet". For example, if you set CacheDuration to 5 and SlidingExpiration to Absolute, the SqlDataSource will retrieve data from the database on the first request to the page and store this data in the cache. For subsequent requests, the SqlDataSource will attempt to retrieve the cache entry to serve the request without going back to the original database. After 5 seconds (or perhaps earlier, if cache memory pressure is high), the cache entry will be purged and a subsequent request to the page causes SqlDataSource to go back to the database again (repeating the caching process with the new data).

If you instead set CacheDuration to 5 and SlidingExpiration to Sliding, the cached data will have its time-to-live periodically refreshed as long as the data source requests the cached data once every 5 seconds. If a page requests the cached data at least once every 5 seconds, and there is no cache memory pressure, the cached data effectively remains in the cache forever. On the other hand, if no requests are made for the cached data within a 5 second time period, then the cached item is purged and the next time a request occurs the SqlDataSource control will go back to the original database again.

The example below demonstrates caching with the SqlDataSource control. The TimeStamp column updates each time the query is executed, so you can see how often the data is retrieved from the database versus retrieved from the cache. Note that approximately every five seconds, the TimeStamp updates.

Inline Code Example of Caching...

<asp:DropDownList ID="DropDownList1" DataSourceID="SqlDataSource2" AutoPostBack="true"
        DataTextField="state" Runat="server" />
      <asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [state] FROM [authors]"
        ConnectionString="<%$ ConnectionStrings:Pubs %>" />
      <br />
      <br />
      <asp:GridView ID="GridView1" AllowSorting="True" AllowPaging="True" Runat="server"
        DataSourceID="SqlDataSource1" AutoGenerateEditButton="True" DataKeyNames="au_id"
          <asp:BoundField DataField="TimeStamp" HeaderText="TimeStamp" ReadOnly="True">
            <ItemStyle Font-Bold="True" />
          <asp:BoundField ReadOnly="True" HeaderText="ID" DataField="au_id" SortExpression="au_id" />
          <asp:BoundField HeaderText="Last Name" DataField="au_lname" SortExpression="au_lname" />
          <asp:BoundField HeaderText="First Name" DataField="au_fname" SortExpression="au_fname" />
          <asp:BoundField HeaderText="Phone" DataField="phone" SortExpression="phone" />
          <asp:BoundField HeaderText="Address" DataField="address" SortExpression="address" />
          <asp:BoundField HeaderText="City" DataField="city" SortExpression="city" />
          <asp:BoundField HeaderText="State" DataField="state" SortExpression="state" />
          <asp:BoundField HeaderText="Zip Code" DataField="zip" SortExpression="zip" />
          <asp:CheckBoxField HeaderText="Contract" SortExpression="contract" DataField="contract" />
      <asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT DatePart(second, GetDate()) As TimeStamp,

[au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] WHERE [state] =

        UpdateCommand="UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id"
        ConnectionString="<%$ ConnectionStrings:Pubs %>" CacheDuration="5" EnableCaching="True">
          <asp:ControlParameter Name="state" ControlID="DropDownList1" />
          <asp:Parameter Name="au_lname" />
          <asp:Parameter Name="au_fname" />
          <asp:Parameter Name="phone" />
          <asp:Parameter Name="address" />
          <asp:Parameter Name="city" />
          <asp:Parameter Name="state" />
          <asp:Parameter Name="zip" />
          <asp:Parameter Name="contract" />
          <asp:Parameter Name="au_id" />

Q41. How to do a language switch in the Masterpage?

A41. Declare a dropdown as usual in the master page. Instead of overriding the InitializeCulture() place the same code in the Application_BeginRequest event handler in the global.asax. It is very similar to InitializeCulture() in the sense that it occurs early and no controls are ready yet. We have a little problem though, now the control is declared in a template and its name and id attributes rendered differently.

Another collection like the form variables collection that is also not originally server collection is the cookies collection. I use the cookie but it can be any of the ways for cross page communication that do not depend on server controls, like profile, session, querystring etc. We cannot use a cookie to carry the culture name value which comes from the dropdown selected item value, because the culture would always be a step behind. It would be set early on but later the dropdown selection change it but the resources for the previous culture come up. So normally only the page containing the dropdown would be a step behind, but because the dropdown is in the master page it appears that the whole site is ALWAYS ONE STEP BEHIND.

If, however, in the cookie, we pass the control name (which is information that never changes, so we can never be behind), instead of the culture name( which we can never keep up with), and then use that key to get the form variable value, we have pieced ourselves a workaround.

in the master page:

<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="true"

      <asp:ListItem Value="en" Text="English" />
      <asp:ListItem Value="fr" Text="French" />
      <asp:ListItem Value="de" Text="German" />

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
   HttpCookie cookie = new HttpCookie("DropDownName");

In global.asax

void Application_BeginRequest(Object sender, EventArgs e){
      string lang = string.Empty;//default to the invariant culture
      HttpCookie cookie = Request.Cookies["DropDownName"];

      if (cookie != null && cookie.Value != null)
         lang = Request.Form[cookie.Value];

      Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);

Notice, there is absolutely no code in any of the content pages. Thats it ten lines of code and we are done for the whole site. This is not complete code, just a tip and trick of using master page and the .net event model to globalize code.

Q42. How to send a mail using System.Net.Mail?

(This question is answered by Ryan Olshan) Ryan Olshan's Blog

A42. Here is the code...



Class MailHelper
   ''' <summary>
   ''' Sends an mail message
   ''' </summary>
   ''' <param name="from">Sender address</param>
   ''' <param name="recepient">Recepient address</param>
   ''' <param name="bcc">Bcc recepient</param>
   ''' <param name="cc">Cc recepient</param>
   ''' <param name="subject">Subject of mail message</param>
   ''' <param name="body">Body of mail message</param>
   Public Shared Sub SendMailMessage(ByVal from As String, ByVal recepient As String, ByVal bcc As String, ByVal cc As

String, ByVal subject As String, ByVal body As String)
      ' Instantiate a new instance of MailMessage
      Dim mMailMessage As New MailMessage()
      ' Set the sender address of the mail message
      mMailMessage.From = New MailAddress(from)
      ' Set the recepient address of the mail message
      mMailMessage.To.Add(New MailAddress(recepient))

      ' Check if the bcc value is nothing or an empty string
      If Not bcc Is Nothing And bcc <> String.Empty Then
         ' Set the Bcc address of the mail message
         mMailMessage.Bcc.Add(New MailAddress(bcc))
      End If

      ' Check if the cc value is nothing or an empty value
      If Not cc Is Nothing And cc <> String.Empty Then
         ' Set the CC address of the mail message
         mMailMessage.CC.Add(New MailAddress(cc))
      End If

      ' Set the subject of the mail message
      mMailMessage.Subject = subject
      ' Set the body of the mail message
      mMailMessage.Body = body

      ' Set the format of the mail message body as HTML
      mMailMessage.IsBodyHtml = True
      ' Set the priority of the mail message to normal
      mMailMessage.Priority = MailPriority.Normal

      ' Instantiate a new instance of SmtpClient
      Dim mSmtpClient As New SmtpClient()
      ' Send the mail message
   End Sub
End Class



xml version="1.0"?>
         <smtp from="">
            <network host="" port="25" userName="yourUserName" password="yourPassword"/>


Home Prev Next