Tuesday, February 05, 2008

Is object assignment statement thread safe?

It really depends on the type of the assignment.

" The CLR guarantees that for types which are no bigger than the size of a native integer, if the memory is properly aligned (as it is by default - if you specify an explicit layout, that could change the alignment), reads and writes are atomic. In other words, if one thread is changing a properly aligned int variable's value from 0 to 5 and another thread is reading the variable's value, it will only ever see 0 or 5 - never 1 or 4, for instance. For a long, however, on a 32-bit machine, if one thread is changing the value from 0 to 0x0123456789abcdef, there's no guarantee that another thread won't see the value as 0x0123456700000000 or 0x0000000089abcdef. You'd have to be unlucky - but writing thread-safe code is all about taking luck out of the equation."

From link

It does not mention object reference assignment. However the size of object reference is always equal to the native integer which means on 32-bit machine the reference size should be 32 bits and on 64-bit machine the reference size should always be 64 bits, therefore it is thread safe.


Monday, February 04, 2008

Best practice for database version

I was always curious about how other people implement the database versioning in their software development process. Today I tumbled across the following article about best practice in database versioning.

The way I am doing it is quite strange forward and involves 2 steps.
  1. Create base-line database.
  2. Create and maintain a single change script file which will be checked  into source control.
Apparently it works well for us. The difference between the method mentioned in the article and my approach are (A) whether we create multiple files to maintain the changes in the source control (B)whether to create a separated table to maintain the current schema version. Everything else works the same way, including branching and merging.

Point A has no semantic difference.

For point B, it is not necessary because when you apply the script which has a version number in the source control (I am using SubVersion which will generate a unique repository-wide incremental number each time you make change(s) to the source repository and our build number is tied to this number), and therefore you know what is the database schema version after the script applies. If customer reports a problem with build 213, I know exactly what the database schema should be and all the source code that associated with this build.




Sunday, February 03, 2008

Session for ASP.NET

I ran across  this article about some hints and tips about session state server in production environment. It is not programming related but I think as a ASP.NET programmer should be aware of it if the site is high-traffic site that uses web farm. It also provides some links to cache server product. I think it is quite useful.

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.