Friday, September 05, 2008

Error with Nant

It seems that the following error message can be fixed by create a new registry entry. I am not sure why it is missing.

Solution:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
"sdkInstallRootv2.0"="C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727"


Error message:
C:\wiki>c:\nant\bin\NAnt.exe svn.build
NAnt 0.86 (Build 0.86.2898.0; beta1; 12/8/2007)
Copyright (C) 2001-2007 Gerry Shaw
http://nant.sourceforge.net


BUILD FAILED

Failed to initialize the 'Microsoft .NET Framework 2.0' (net-2.0) target framewo
rk.

    Property evaluation failed.
Expression: ${path::combine(sdkInstallRoot, 'bin')}
                            ^^^^^^^^^^^^^^

        Property 'sdkInstallRoot' has not been set.

For more information regarding the cause of the build failure, run the build aga
in in debug mode.

Try 'nant -help' for more information



Monday, August 25, 2008

LizardTF : a much better alternative than Visual Studio TFS client

I highly recommend anyone whom works with TFS as his/her primary source control tool to give LizardTF a try. I especially likes the review sub-menu, 10 times better than TFS, since I sometimes making changes of a couple of hundreds files and can view the check-in items in a hierarchical view. Another reason is it categorized the items into 4 categories. IMHO Microsoft should hire the guy if they want to improve the usability of the product. :)

Personally, I use GIT while work offline to keep track of intermediate changes and update the TFS while a work item is done.

Tuesday, August 12, 2008

things that I do like in TFS

1. No shell integration. I do not understand why it is not a priority. I spend lots of time in Windows Explorer for adding, moving, deleting, and copying files. It is just impossible after I re-arrange a couple of folders and try to check-in the changes. No easy way to identify which files are added, moved, and deleted.

2. Bad integration with VS 2008. For example, it does not tell you if the file under the folder is modified until you expand the folder. Same apply for the project, you won't know if any file gets modified after you open/expand the project. It is not difficult thing to do, why it worked this way. No drag and drop support is another example. Lack of unified diff. I am not a mouse-clicker. I know I can get it from view pending change menu option. But what if I made 20 small changes to 20 files, I have to click through these 20 files to find out the changes I made.

3. No disconnect mode. I could not work offline, check-in the changes, and later synchronize with main server. Every operation needs to contact server. That explains why the performance is so slow and inconsistent via VPN. Sometimes it takes 15 seconds to open the property page of a project. It is extremely slow comparing VS 2008 without TFS installed. Luckly I have GIT installed on my local machine and used it keep intermediate changes and only update it when it is done.

I moved from SVN+TortoisesSVN+AnkhSVN, I felt the difference is day and night. In everyway, I felt the TFS is working against you not for you.

Things that so simple with SVN become impossible to do it or at least 10 times more difficult to do in TFS. Here is another example, I used a code generation tools that creates about 200+ .cs files which is part of the c# project. In SVN, every time I need to refresh the generated code, I just need to generate the code and refresh project by clicking the refresh icon under the Solution Explorer. Then I can then visually tell what files have changed since last check-out and I can do unified diff to find out all the updates. I do not think it is possible at all in TFS. What a shame!!!



Tuesday, July 15, 2008

How to extending default MSBuild script for Teambuild

I have been configuring and using Cruise Control .NET and NANT combination for my last project in my company. Everyone loves it, it takes only 10 minutes from the code check-in to generate the final deployable binaries. I even setup the an auto-deploy project so that when the latest code is generated, it will automatically deploy under the IIS. Everyone can monitor the project status via the little green icon in the system tray.

Since I was the person who was most familiar with compile/build process in the team, I undertook the task to setup a new build system and convert all existing projects into Team Foundation Server (TFS). Since I do not like hybrid solution, I set out to just use the MSBuild functionality. It was quite easy to configure the MSBuild agent. I did it with the following steps:

1. Install the Team Foundation Build from the TFS CD.
2. Make sure that you are granted access rights to Build Services via the Project Security dialog box.
3. Right-mouse click on the Builds and select Manage Build Agents and add a build agent that setup in step 1.
4. Right-mouse click on the Builds and select Add new Build Definition.
5. Under the Project File menu, you can have the TFS to create a default build file.
6. Complete the rest of menu options and click OK to save the changes.

Now you have a newly created build definition and you can launch it by right-mouse clicking and selecting Queue New Build. You should have the compiled binary files in the drop location in 5 minutes if your project is not too big.

The next thing comes is how to further configure it. Specifically there are 2 things I would like to do:

1. replace some place holder in the source files before compile
2. run the WISE setup module to create  final MSI files for distribution.

After a little bit digging in the Microsoft.TeamFoundation.Build.targets file, I found all the extension points that are available as the following. By create 2 targets (AfterGet and PackageBinaries) in the newly-created build definition file, I could archieve what I what to do here.



  <!-- Override this target to execute custom tasks before EndToEndIteration -->
  <Target Name="BeforeEndToEndIteration" />

  <!--
       Override this target to execute a task for customizing the build number and/or drop location.
       Make sure that the task outputs properties with the names 'BuildNumber' and/or 'DropLocation'.
    -->
  <Target Name="BuildNumberOverrideTarget" />

  <!--
       Override this target to execute a task for customizing the build number and/or drop location.
       Make sure that the task outputs properties with the names 'BuildNumber' and/or 'DropLocation'.
    -->
  <Target Name="BuildNumberOverrideTarget" />

  <!-- Override this target to execute custom tasks before clean -->
  <Target Name="BeforeClean" />

  <!-- Override this target to execute custom tasks after clean -->
  <Target Name="AfterClean" />

  <Target Name="BeforeCleanConfiguration" />
  <Target Name="AfterCleanConfiguration" />

  <!-- Override this target to execute custom tasks before cleaning an individual solution -->
  <Target Name="BeforeCleanSolution" />

  <!-- Override this target to execute custom tasks after cleaning an individual solution -->
  <Target Name="AfterCleanSolution" />

  <!-- Override this target to execute custom tasks before workspace initialization -->
  <Target Name="BeforeInitializeWorkspace" />

  <!-- Override this target to execute custom tasks after workspace initialization  -->
  <Target Name="AfterInitializeWorkspace" />

  <!-- Override this target to execute custom tasks before getting sources -->
  <Target Name="BeforeGet" />

  <!-- Override this target to execute custom tasks after getting sources -->
  <Target Name="AfterGet" />

  <!-- Override this target to execute custom tasks before labeling sources -->
  <Target Name="BeforeLabel" />


  <!-- Override this target to execute custom tasks after labeling sources -->
  <Target Name="AfterLabel" />


  <!-- Override this target to execute custom tasks before compilation -->
  <Target Name="BeforeCompile" />

  <!-- Override this target to execute custom tasks after compilation -->
  <Target Name="AfterCompile" />

  <!-- Override this target to execute custom tasks before the compilation of an individual configuration -->
  <Target Name="BeforeCompileConfiguration" />

  <!-- Override this target to execute custom tasks after the compilation of an individual configuration -->
  <Target Name="AfterCompileConfiguration" />

  <!-- Override this target to execute custom tasks before the compilation of an individual solution -->
  <Target Name="BeforeCompileSolution" />


  <!-- Override this target to execute custom tasks after the compilation of an individual solution -->
  <Target Name="AfterCompileSolution" />

  <!-- Override this target to execute custom tasks before associating changesets and updating work items -->
  <Target Name="BeforeGetChangesetsAndUpdateWorkItems" />

  <!-- Override this target to execute custom tasks after associating changesets and updating work items -->
  <Target Name="AfterGetChangesetsAndUpdateWorkItems" />


  <!-- Override this target to execute custom tasks before running tests -->
  <Target Name="BeforeTest" />


  <!-- Override this target to execute custom tasks after running tests -->
  <Target Name="AfterTest" />

  <!-- Override this target to execute custom tasks before the testing of an individual configuration -->
  <Target Name="BeforeTestConfiguration" />

 <!-- Override this target to execute custom tasks after the testing of an individual configuration -->
  <Target Name="AfterTestConfiguration" />

  <!-- Override this target to generate documentation. -->
  <Target Name="GenerateDocumentation" />

  <!-- Override this target to package all binaries for deployment. -->
  <Target Name="PackageBinaries" />

  <!-- Override this target to execute custom tasks before copying files to the drop location -->
  <Target Name="BeforeDropBuild" />

  <!-- Override this target to execute custom tasks after copying files to the drop location -->
  <Target Name="AfterDropBuild" />

  <!-- Override this target to execute custom tasks before the BuildBreak target -->
  <Target Name="BeforeOnBuildBreak" />

  <!-- Override the target to execute custom tasks after associating changesets on a build break -->
  <Target Name="AfterGetChangesetsOnBuildBreak" />

  <!-- Override the target to execute custom tasks before associating changesets on a build break -->
  <Target Name="BeforeGetChangesetsOnBuildBreak" />

  <!-- Override the target to execute custom tasks after associating changesets on a build break -->
  <Target Name="AfterGetChangesetsOnBuildBreak" />

  <!-- Override this target to execute custom tasks before work item creation -->
  <Target Name="BeforeCreateWorkItem" />

  <!-- Override this target to execute custom tasks after work item creation-->
  <Target Name="AfterCreateWorkItem" />



Tuesday, March 18, 2008

GWT(google Web Toolkit)

Recently I was doing feasibility study of implementation GWT for our next project.

The tool kit allows programmers write plain Java which be compiled into JavaScript for rich web front-end application. There is a Java to JavaScript compiler will compile the Java code to JavaScript while the library that comes with the tool kit will hide the any browser quicks for you. The resulting JavaScript code will only be load once on the client and only the data will be dynamically requested by the JavaScript code. I think it is wonderful programming model.

The issue I am running into is that since Javascript has so called Same Origin Policy . It prevents any scripts that try to request data from any servers other than the server that the scripts are loaded.

It is not much a problem for the GWT, the front-end development server happens to be the same back-end server if you are using built-in RPC calls. For me, I was going to use Microsoft IIS as my development back-end server. Since I am going to use Eclipse with GWT plugin as my front-end development environment, the JavaScript will be loaded from my front-end development server and will not be able to request any data from back-end server on a different port (it will violate the Same Origin Policy).

To work around the problem, I use a tool called Fiddler which allows you to modify the request on the fly. What you need to do it just download and install the software from the web site. Upon launching the Fiddler UI, press CTRL-R to open customized script editor (it can also be open via menu Rules | Customize Rules... ). Locate a function call OnBeforeRequest and insert the following lines:

        if (oSession.HostnameIs("MYAPP")) {
            if (oSession.PathAndQuery.StartsWith("/search")){
                oSession.host = "www.google.ca";
            }
            else {
                oSession.host = "127.0.0.1:8888";
            }
       
        }

It is quite self-explanatory. It basically says that if the host name is MYAPP, then rewrite the host name based on the requesting URL. In the example, if the URL is starting with "/search", it will send the request to "www.google.ca" otherwise it will send requests to localhost port 8888. It needs to customized to suit your needs.

After you set it up, you can now requesting paging via Internet Explorer (unfortunately it works only on IE). Try the following:


This will overcome the Same Origin Policy restriction for you since your JavaScript and back-end server will all appear as it originated from the same server.

It has the following drawbacks.
1. It does not work on Firefox.
2. The breakpoint has no effect if you invoking the page via the proxy. (I do not know why?)








Friday, February 22, 2008

Microsoft Web UI

Microsoft has so many web technologies to do the same Web UI AJAX thingy. It does not even funny. Here is the (not exhaustive) list :

Sometimes it is a tough decision to make, especially they are still new and you have to overcome some quirks that are not very well-documented. I used the ASP.NET/AJAX in my most recent project. It turned out that in order to write a AJAX control extender you have to learn a whole framework/library in a completely different language (JavaScript). What a nightmare to maintain the code.


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.





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.