Notify Database changes to ASP.NET pages

In the old times there were two ways of getting notifications from the database into the ASP.NET pages.

  1. writing to a file (simply create or delete an empty file) in a specific location where a CacheDependency can listen to and callBack a method on change.
  2. implement an HttpHandler that gets the notification with a parameter of what is changed, and let the database send an http request to the IIS server on a trigger.
I am sure there could be worse methods but even these two have a lot of complications in a secured architecture with high performance requirements, like we have these days.

Fortunately, since SQL-Servet 2000, there is a new component implemented into SQL-server called Service Broker that act on changes in tables that are marked to be notified on change. Internally they write to a specific table mentioning about the change.
In order to configure a database for Service Broker you can call a statement like this:
Use Northwind
ALTER DATABASE Northwind SET ENABLE_BROKER
For more information about Service Broker see the MSDN.
Next, you need to set the ASP.NET to recieve the notification via dependencies. To do so , you need to add the command object to the dependency:
// Create the dependency.
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
// Add a cache item that will be invalidated if one of its records changes
// (or a new record is added in the same range).

Cache.Insert("Employees", ds, empDependency);
To start the notification on application service you need to add the following to the Global.ascx.cs in Application_Start
SqlDependency.Start(connectionString);
It is a good practice to stop the notifications on Application_End
SqlDependency.Stop(connectionString);
Once this is implemented, you can get the notifications through the OnChange event of the SqlDependency class.

Localizing ASP.NET Tips

There are two kind of localizations:

  • Local resources are specific to a page.
  • Global resources are shared throughout the site

If your site contains many folders, you might have an App_LocalResources subfolder in each folder of your site.

<asp:Button ID="ButtonFind" runat="server" Text="Find" CssClass="submitButton" meta:resourcekey="ButtonFindResource1" />

<asp:Localize ID="LabelTitle" runat="server" Text="Customer Lookup" meta:resourcekey="LabelTitleResource1"></asp:Localize>

The Text property of the Button control is to aid the developer at design time.

ASP.NET will use the key to find and match on any property that might be set inside the resource file as meta:resourcekey.<PropertyName> or ButtonFindResoure1.Text:

<data name="ButtonFindResource1.Text" xml:space="preserve">

     <value>Find</value>

</data>

<data name="ButtonFindResource1.Tooltip" xml:space="preserve">

     <value>Click this to start the search action</value>

</data>

Accessing a Local resource in C# could be done as follows:

Textbox1.Text = GetLocalResourceObject(“Textbox1.Text”).ToString();

Accessing a shared global resource in C# could be done in one of the two followings:

Textbox1.Text = Resources.ResourceFileName.Textbox1Text;

Textbox1.Text = GetGlobalResourceObject(“ResourceFileName”, “Textbox1Text”) as string;

The methods GetGlobalResourceObject  and GetLocalResourceObject can come handy when the resources does not exist at compile time and might be provided as a separate dll at runtime.

Show an object instance as an xnl on your page

This sample code demonstrates how to show an instance of an object in XML format on a page. It encodes the xml serialized string and dumps it as a code into a placeholder.
    public void ShowXmlObject<T>( T instance)
    {
        var ms = new MemoryStream();
        System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, Encoding.Unicode);
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        serializer.Serialize(writer, instance);
        writer.Flush();
        ms.Position = 0;
        var reader = new StreamReader(ms);
        LogCode(HttpUtility.HtmlEncode(IndentXml(reader.ReadToEnd())));
    }
    public string IndentXml(string xml)
    {
        var p = xml.LastIndexOf(“?>”);
        if (p > 0)
            xml = xml.Substring(p + 2);
        var doc = new System.Xml.XmlDocument();
        doc.LoadXml(xml);
        var settings = new System.Xml.XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = ”  “;
        settings.NewLineChars = “rn”;
        settings.NewLineHandling = System.Xml.NewLineHandling.None;
        var  sbOutput = new StringBuilder();
        var writer = System.Xml.XmlWriter.Create(sbOutput, settings);
        doc.Save(writer);
        writer.Close();
        return sbOutput.ToString();
    } 
    public void LogCode(string message)
    {
        placeResult.Controls.Add(new Literal() { Text = "<pre><code>" + message + "</code></pre>" });
    }

jQuery.Ajax versus Server-side event handler

This sample demonstrates two ways of getting address from the server: using server-side event handler versus calling jQuery.Ajax

The following is the markup that provides two fields with javascript call on the change event. It also provides a button that is wired to a server side methode:

     <div>

         <h3> Address Test</h3>

         tabbing from the textboxes will verify if calling the webservice is required.

         <table  width="100%"><tr><td><table><tr>

                             <td> Huisnummer *</td>

                             <td><div class="FieldContainer">

                                     <asp:TextBox  runat="server"  ID="textboxHousenumber"  ClientIDMode="Static"

                                         CssClass="TextField TextField02" onchange="VerifyAddress();"

                                         ValidationGroup="KlantAddress" />

                                 </div>

                             </td></tr><tr>

                             <td> Postcode *</td>

                             <td><div  class="FieldContainer">

                                     <asp:TextBox  runat="server"  ID="textboxPostcode"      ClientIDMode="Static"

                                                 CssClass="TextField TextField02"  

                                                 MaxLength="7"  onchange="VerifyAddress();"

                                                 ValidationGroup="KlantAddress" 

                                                 />

                                 </div>

                             </td></tr>

                     </table>

                   Server side call:<br  />

                     <asp:Button  ID="Button1"  runat="server"  OnClick="ShowAddress"  Text="Get Adres"  ToolTip="CustomerDataController"  />

                     <asp:Label  runat="server"  ID="lblAddress"  />

                   

 

Assume we have a we DBLLayer that provides an address or throws an exception.
The event handler would be something like this:

 

     /// <summary>Server side event handler</summary>

     public  void  ShowAddress(object  sender, EventArgs  e)

     {

         try

         {

             var  adres = DBLayer.GetAddress(textboxPostcode.Text, textboxHousenumber.Text);

             ShowAdres(adres);

         }

         catch  (Exception  ex)

         {

             LogError("Error :- "  + ex.Message);

         }

     }

 

And the Javascript will look like this:

 

     function  VerifyAddress() {

         // This method is calling the ShowAddress only if both parameters are filled in.  

         $("#<%=lblAddress.ClientID %>" ).text("" );

         var  postcode = $("#<%=textboxPostcode.ClientID %>" ).val();

         var  huisnummer = $("#<%=textboxHousenumber.ClientID %>" ).val();

         if  (postcode && huisnummer && parseInt(huisnummer) > 0) {

             $("#<%=lblAddress.ClientID %>" ).text("calling the server" );

             var  data = "{ postcode:’"  + postcode + <span’ , huisnummer: "  + huisnummer + " }" ;

             jQuery.ajax({

                 type: <span’ ,

                 contentType: <span’application/json;’ ,

                 data: data,

                 dataType: <span’ ,

                 url: <span’ ,

                 success: OnGetAddressComplete,

                 error: OnErrorReceived

             });

         }

     }

     function  OnErrorReceived(xhr, ajaxOptions, thrownError) {

         var  message = jQuery.parseJSON(xhr.responseText);

         $("#<%=lblAddress.ClientID %>" ).text(

             "ERROR ("  + xhr.status + ") – "  + message.Message);

     }

     function  OnGetAddressComplete(result) {

         // display the result

         var  adres = result.d;

         $("#<%=lblAddress.ClientID %>" ).text(

             adres.Straat + <span”  +

             adres.Huisnummer + <span’,’  +

             adres.Postcode + <span”  + adres.Plaats);

     }

And finally the webservice will be like:

 

     [System.Web.Services.WebMethod ()]

     public  static  Adres GetAddress(string  postcode, string  huisnummer)

     {

         if  (!IsPostcode(postcode))

             throw  new  Exception ("Invalid Postcode." );

         int  hNr = 0;

         if  (!Int32 .TryParse(huisnummer, out  hNr))

             throw  new  Exception ("Invalid house number." );

         var  result = DBLayer .GetAddress(postcode, huisnummer);

         if  (result == null )

             throw  new  Exception (" Unknown address." );

         return  result;

     }

    

     public static bool IsPostcode(string  zipcode)

     {

         var  ZipcodeRegex = @"^[1-9][0-9]{3}[a-zA-Z]{2}[\s]*$" ;

         Regex  r = new  Regex (ZipcodeRegex, RegexOptions .IgnoreCase);

         Match  m = r.Match(zipcode);

         return  m.Success;

     }

    

How do I secure my browser – Part

I came across a web address that has phishing software. It was www.secure-logins.com. I figured out that this is not the only address in tis domain that has the worm, any address ending to the same domain is doing the same harm. So I had to find a way to stop all the requests going from my browser (or even better from my house) to this domain. This is what I did:

I. Tell your browser never go to that domain.
II. let your router know that this domain should be filtered.

Although the second way is enough to stop the worm but I thought some people might not have the feature in their router to do that, so I also mentioned the first one.


1. In the Internet Explorer go to Menu Tools->Internet Options and when the Internet Options pops up click on the Security tab.
2. You will see different zones. The important zone is : Restricted sites. Click on it.
3. Once you selected the Restricted sites click on the Sites button. This will pop up another window called Restricted Sites which holds a list of sites that you don’t want your browser coincidently or willingly go there.
4. In th text box under “Add this site to the zone:” type the following:
*.secure-logins.com
5. Press the Add button and you will see that the address is added to the list
6. Press the Close button and you will be back to the Internet Options.
7. Click OK,
that’s it

My router is a D-Link and have an option to filter any requests going to a specific address from any machine at my home. You should check your router’s website which is often to e accessed by http://192.168.0.1
In the Advanced menu you will find a link to go to Website Filter. When you get there you will see an empty list where you can add your preferences. The ‘Website Filter‘ option allows you to set up a list of Web sites you would like to deny through your network.
Add the same address there:

thats all.

Common Buses and their Max Bandwidth

Nice article from: http://networking.ringofsaturn.com/PC/pciexpress.php

Bandwidth
PCI Express in all it’s flavors: 1x, 2x, 4x, 8x, 16x and 32x all have much greater bandwidth than basic PCI.

Common Buses and their Max Bandwidth
PCI 132 MB/s
AGP 8X 2,100 MB/s
PCI Express 1x 250 [500]* MB/s
PCI Express 2x 500 [1000]* MB/s
PCI Express 4x 1000 [2000]* MB/s
PCI Express 8x 2000 [4000]* MB/s
PCI Express 16x 4000 [8000]* MB/s
PCI Express 32x 8000 [16000]* MB/s
IDE (ATA100) 100 MB/s
IDE (ATA133) 133 MB/s
SATA 150 MB/s
Gigabit Ethernet 125 MB/s
IEEE1394B [Firewire] 100 MB/s

Persistor of a Serializer

We had this situation in my last project where we wanted to have some of our objects to get easily serialized into a specific table. Therefor we had to add up to the Serializer an new generic class that uses the Serializer to get the sream to put into a table.
In this example we have several classes like Article, Order, etc. and we wanted to give them a specific addition that would implement the Save and Load for all these classes. So we wanted to have something like this :

[Serializable]
public class Article : Persistor

and then later use it as follows:

// Read the last saved Article filter
private Article filter = Article.Load();


// and do something with it and finally save it back to Database

this.filter.Remove(e.Item.Key);

this.filter.Save();

Well, to achive that we implemented the Persistor class as follows:


using System;
using System.Collections.Generic;

/// <summary>
/// Provides the persistance methods for the filter classes.
/// It reads and writes the content in an xml format into the Filter table
/// </summary>
/// <typeparam name="T">The type of the filter. This type should derive from Persistor&lt;T&gt; and have an empty constructor</typeparam>
[Serializable]
public class Persistor<T>
where T : Persistor
<T>, new()
{
/// <summary>
/// Saves this filter as the default filter for the current user.
/// </summary>
public void Save()
{
// Serialize the current filter instance
Serializer<T> serializer = new Serializer<T>();
string xml = serializer.Serialize(this as T);

// The filter class is a data class that handles the saveing of a record
Data.Tables.Filter filter = Persistor<T>.LoadFilter(true);

// Actual save to database
filter.Value = xml;
filter.Save();
}

/// <summary>
/// Loads the default filter for the current table and user.
/// </summary>
public static T Load()
{
Tables.Filter filter
= Persistor<T>.LoadFilter(false);

// Deserialize
T currentFilter = null;
if (filter != null && !string.IsNullOrEmpty(filter.Value))
{
Serializer
<T> serializer = new Serializer<T>();
currentFilter
= serializer.Deserialize(filter.Value);
}
else
{
currentFilter
= new T();
}

return currentFilter;
}

/// <summary>
/// Loads the Filter for the current user and table from the database.
/// </summary>
protected static Tables.Filter LoadFilter(bool createNew)
{
string tableId = typeof(T).Name;
int userId = UserContext.Current.User.ID;

// Load current filter, if available, otherwise create a new filter instance.
Tables.Filter filter = Tables.Filter.GetForUserTable(userId, tableId);
if (filter == null && createNew)
{
filter
= new Data.Tables.Filter();
filter.UserID
= userId;
filter.TableID
= tableId;
}

return filter;
}
}

Cmdlets Extending Windows PowerShell

Coming across a nice article in MSDN about Extending Windows PowerShell With Custom Commands that I paste a short overview of it here :

 

There are some pretty significant differences between a Windows PowerShell cmdlet and commands in other standalone shell environments. For instance,

·         a cmdlet is an instance of a Microsoft® .NET Framework class; it is not a standalone executable.

·         Cmdlets generally output objects rather than text and should not format their output.

·         A cmdlet processes its input objects from an object pipeline rather than from a stream of text.

·         A cmdlet should not parse its own arguments and it should not specify a presentation for errors.

·         Finally, cmdlets are record-oriented and generally process a single object at a time.

 

To declare a .NET class as a cmdlet, you attribute the class with the CmdletAttribute attribute (which is the only required attribute for any cmdlet). When you specify the CmdletAttribute attribute, you must specify a verb and noun name pair, which will be used as the name of the cmdlet. This should describe what the cmdlet does and what sort of resource the cmdlet works with.

 

To declare parameters for a cmdlet, you must first define the properties that represent the parameters. To inform the Windows PowerShell runtime that a property is a cmdlet parameter, you add a ParameterAttribute attribute to the property definition.

 

In order to use these new cmdlets, you need to add them to the Windows PowerShell environment. Windows powerShell has the ability to dynamically add cmdlets to the session via a snap-in. To avoid potential confusion with MMC snap-ins, a Windows PowerShell snap-in is called a PSSnapIn.

To create a PSSnapIn, you need to write a bit of code that will perform two tasks. First, it provides identification for your snap-in so it can be distinguished from other snap-ins installed on your system. Second, it provides information for properly installing the snap-in and for creating the appropriate registry entries to allow Windows PowerShell to find the assembly.

Characteristics of a Leader

The following is coted from the book Analyzing Requirements and Defining Solution Architectures.

Finding Effective Leaders

For the person in charge of putting together a project team, the first task is to decide who will work on the project. This seemingly simple (but more often complex) decision can dramatically affect the project’s outcome.

Finding leaders within an organization is not a difficult process. By definition, leaders are recognized by those they work with. It’s important to remember that we are talking about leaders here, not bosses. Every organization has its share of managers, directors, and so on, but the hierarchical structure of an organization does not determine who the true leaders are. Actions and characteristics, rather than job titles, identify leaders.

Why do we need leaders? Because we have so many followers. It’s important to realize that labeling people as leaders and followers does not imply a value judgment. We must have leaders to be successful, but we must also have followers. Leaders provide direction for the team. Followers get the work done. The team needs to strike a balance between its leaders and followers. It must decide what to do and then must do it, so both leaders and followers are equally important and valuable. An absence of either leaders or followers will hinder the project’s success.

Certain characteristics are present in many leaders. Common qualities of leaders include:

  • Understanding and meeting the needs of others.
  • Communicating well with groups and individuals.
  • Earning the respect of internal and external customers.
  • Displaying commitment to well-defined purposes.
  • Making a positive difference.
  • Having confidence in his or her abilities.
  • Practicing good problem-solving skills.
  • Helping others to develop their skills.

Many people will read this list and say, "I do those things." More people will read this list and say, "I intend to do those things." But being a leader also means knowing the difference between intent and impact. When measuring their own success, people measure their intent; when measuring other people’s success, they measure their impact. The impact that leaders have on others may or may not be their intent, and leaders’ intent may not have the impact they were striving for. The proper way to measure people’s leadership skills is by the impact they actually have, not by their intent. We can summarize this concept by saying, "Other people’s perceptions are reality."

Total Participation in Design

Jim McCarthy summarizes the concept of total participation in design in Dynamics of Software Development:

The goal in any product design is to have the best ideas become the basis of the product. Everybody on the team should be working to accomplish that goal.

Each role participates in the generation of the Functional Specification because each role has a unique perspective of the design and tries to ensure that the design meets their role’s objectives, as well as the project team’s objectives.