Thursday, January 24, 2008

Generic Wrapper for Session variable in ASP.NET

I found a way to wrap around Session variable in ASP.NET. It provides a strong-type return type and make code much easy to understand.


Usage:

            GlobalAppParameter gp = GetSession<GlobalAppParameter>("gp", delegate {
                return GlobalAppParameter.NewGlobalAppParameter();
            });

Declare/implementation

        protected delegate T CallBack<T>();

        protected T GetSession<T>(string sessionName, CallBack<T> callBack ){

            T ret;
            if (Session[sessionName] == null)
            {
                ret = callBack();
                Session[sessionName] = ret;
            }
            else
                ret = (T) Session[sessionName];

            return ret;
        }

Tuesday, January 22, 2008

Order By Sub-query

In case you never heard of this, you can actually create a select statement in which the Order By clause can be a sub-query too.

SELECT BranchID,

( SELECT TOP 1 InstitutionName FROM Institution WHERE Institution.InstitutionID=FIServiceLocation.InstitutionID) InstitutionName

FROM FIServiceLocation

Order By (SELECT TOP 1 InstitutionName FROM Institution WHERE Institution.InstitutionID=FIServiceLocation.InstitutionID)

The feature actually is very useful for me in a project I am working on, since I wanted to be able to sort a computed field.

Wednesday, January 16, 2008

Inversion of Control Example Structuremap

I am experimenting with IoC for the first time today. There are number of open source library out there . I chose Structuremap since I was introduced the concept by Jeremy D. Miller who was the author of the software last year in DevTeach. After I search around on the Internet to try to find some tutorials on the how it works with minimal amount of code to demonstrate how it works without success, I dicided to write my own. Here is the code:

<?xml version= "1.0" encoding="utf-8" ?>
<
StructureMap >
 <
Assembly Name="ConsoleApplication4" />
 
<
PluginFamily Assembly= "ConsoleApplication4" Type="ConsoleApplication4.IScheduler " DefaultKey="MyFirstScheduler">
   
<
Instance Type= "Daily" Key="MyFirstScheduler" />
 
</
PluginFamily >
</
StructureMap>

using System;
using
System.Data;
using
StructureMap;
namespace
ConsoleApplication4
{
    [Pluggable( "Daily")]
    public class DailyScheduler : IScheduler
   
{
        public DateTime GetNextRunTime( DateTime currentTime)
        {
            return DateTime.Now;
        }
    }

    public interface IScheduler
   
{
        DateTime GetNextRunTime(DateTime now);
    }

    class Program
   
{
        static void Main(string[] args)
        {
            IScheduler s = ObjectFactory.GetInstance<IScheduler>();
        }
    }
}

Tuesday, January 15, 2008

Gridview paging within other data control

One approach to solve a programming problem is to re-create the problem with minimal amount of code and work on it. It has 2 effects on solving the problem. One is that it lets you focus on the problem without any distraction from other parts of the code which could be huge. The other one is that it shorten the code change and debug/test loop. You can almost get instantaneous feed back from your code changes.

Here is how I apply the principle. In my work project, I encounter a problem to paginate a GridView which is inside a data control. I am keep getting error message saying ""Object reference not set to an instance of an object.".

Reproduce the problem
So I start out to create the problem with minimal amount of code. The following code shows a repeater control and within the repeater control it display a GridView control which has pagination enabled. Upon page loading, it sets the datasource for the repeater and call the DataBind() method to update the repeater and its child controls. It works fine on the first initial page load, but fails when you click on the numbers that represents each page of the GridView.


   <asp :Repeater ID="Repeater1" runat="server">
      
<ItemTemplate>
          
< asp:GridView ID="GridView1" runat ="server" AllowPaging="True" EnableSortingAndPagingCallbacks ="True"
              
PageSize="2" DataSource=' <%#  ( (A) Container.DataItem).b %> '>
          
</asp:GridView >
      
</ItemTemplate>
   
</ asp:Repeater>

    protected void Page_Load(object sender, EventArgs  e)
    {
        if (!IsPostBack)
        {
             A a = new A();
            a.b = new  int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
            Repeater1.DataSource = new  List<A>(new A[] {a});
            Repeater1.DataBind ();
        }
    }
It is good sign that I am able to reproduce the problem with the minimal amount of code shown above without any Ajax, JavaScript, database access.

Tackle the problem
A quick search on the e-books that I have and on the Internet could not find any information on the topic. One related the article shows a technique to display GridView within a GridView is the closest that I can find. It uses 2 datasource controls and bind the child datasource at runtime. In the problem code above, I bind the datasource declaratively. Maybe declaration of child datasource only takes effect via the page loading not the subsequent page post-back. That is exactly how my test code fails.

So I quickly change the code as the following: (changes are in bold)

   < asp:Repeater ID="Repeater1" runat ="server" OnItemDataBound ="Repeater1_ItemDataBound">
      
<ItemTemplate>
          
<asp:GridView ID="GridView1" runat="server" AllowPaging ="True" EnableSortingAndPagingCallbacks="True"
              
PageSize="2"
OnDataBinding="GridView1_DataBinding" >
          
</asp:GridView>
      
</ItemTemplate>
   
</asp:Repeater>


    protected void Repeater1_ItemDataBound(object sender,  RepeaterItemEventArgs e)
    {
        GridView gv = ( GridView) e.Item. FindControl("GridView1");
        gv.DataBind();
    }
 
    protected void GridView1_DataBinding(object sender,  EventArgs e)
    {
        GridView gv = ( GridView)sender;
        gv.DataSource = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     }

Basically, I removed the declarative databinding for the GridView and intercept 2 events that will allow me to populate the GridView programmatically. The chain of events that fires are Repeater1_Databinding, Repeater1_itemDataBound, Gridview1_DataBinding. The last 2 events will repeat as many times as the amount of data in the repeater.

Now we have a solution and just need to port it to my work project.





MS SQL quirk

I used sub-query as column output quite often. As shown in the following command SQL command.

select (select top 1 a from b.c=d.c) e from d

However, if you query further based on the sub-query result e, the result is not defined, as shown in the following statement.

select (select top 1 a from b.c=d.c) e, (select top 1 f from g where g.h=e) i from d

The query will run successfully but the resulting data for i is not changing based on the value e which is correct even multiple rows are returned.

The solution is quite simple. We just need to replace the e with the sub-query it represents as shown below:

select (select top 1 a from b.c=d.c) e, (select top 1 f from g where g.h in (select top 1 a from b.c=d.c)) i from d

Thursday, January 10, 2008

Mole for Visual Studio



I came across a very useful tool called "Mole for Visual Studio" that allow you to visualize the data easily. The project that I am working right now has about 8 level deep in one ASP.NET page. It is hard to keep track of all the objects that created at different the levels. Mole for Visual Studio works like a charm.

Here is the link to the screenshot.

How to monitor text changes in an input box on a web page

I was assigned a task to implement something like Autocomplete control in ASP.NET Ajax Control Tool Kit with JavaScript. The only difference is that instead of displaying a drop drown list like what Autocomplete does, I need to display more rich content.

It took me a while to figure out how to monitor the input text changes in a text box. I created kyepress and mousedown and various other event handlers to start the process to monitor the input text box. It worked in some cases, but failed in others.

In the end, I have to take a look into the source code that implemented Autocomplete control released with Ajax Contrl Took Kit by Microsoft. The correct answer is to intercept focus, blur, and keydown events. In the past, it would not be possible because all the software is not open-sourced. The only solution is to read documentation and use trial and error approach.

Tuesday, January 08, 2008

Referencing type within a generic class

In the following code snippet, an enum class1Enum type is declared with in a generic class Class1<T>. In order to reference to class1Enum type, we have to instantiate the generic class by supplying its type as shown in the declaration of var1 and var2. Another catch is that, although the var1 and var2 are of the same class1Enum type, they are declared in  different classes namely  Class1<int> and Class1<string>, and therefore they are not the same.

    public class Class1<T>
    {
         public T t;
 
        public enum  class1Enum
        {
            a,
            b
        }
     }
 
    public class Class2
     {
        public Class1.class1Enum var; // compile error
 
         public Class1<int>.class1Enum var1;
         public Class1<string>.class1Enum var2;
  
        public Class2()
        {
            var1 = var2; // compile error 
        }
    }

My Sudoku Solver

My first published article about  Sudoku Solver in C# 3.0 back in 2006 when LINQ was still in public beta.

Monday, January 07, 2008

Enum Flags

The following code demostrates how to use enum type in c# as flags.

        [Flags]
        public enum  test
        {
            none = 0,
            a = 0x01,
            b = 0x02,
             c = 0x04,
            d = 0x08
        }
        static  void Main(string[] args)
        {
            test t =  test.none;
            Console.WriteLine(t);
 
            t = t |  test.a; //set bit a
            Console.WriteLine(t);
 
             if (t == test.a) 
                Console.WriteLine( "only bit a is set");
 
            t = t | test.b;  // set bit a
            Console.WriteLine(t);
 
             if ((t & test.a) != 0) //test to see if bit a is set
                 Console.WriteLine(" test bit a is set");
 
            Console .ReadKey();
        }

The implementation I was using is to use the BitArray which is very efficient. The good news is I implemented by using code generation which means I only need to modify the code generation templates and all my generated code will be benefiting. :)


Setting the timeout value when doing unit testing

It is actually quite easy to set the timeout for Microsoft Unit Test. It is shown as the following which set the timeout to 10 minutes:

[TestMethod]
[Timeout(600000)]
public void QuickSearchRegressionTestWithThread() {… }

Actually it the following link provides the comparison of all the fixtures of all the popular unit test suites for the .NET framework.