Wednesday, December 21, 2011

Precompile Web Application Project

If you have a website project, you have the option to precompile the website. So, the website startup (in IIS) will be responsive. But, for Web Application project, you don't have such precompile option and you will have to do it manually.

Steps to precompile your Web Application project:
  1. Publish your project by right click on the project name and choose Publish.
  2. Choose "File System" in the Publish Method and specify the location.
  3. Once the publishing has completed, run the "Visual Studio Command Prompt (2010)" from the Windows Startup menu.
  4. Then, type the following command and press Enter.
                    aspnet_compiler -p WebApp -v / WebAppPrecompile

The above command will precompile the "WebApp" locally without creating the Virtual Directory in the IIS.

Reference:
http://msdn.microsoft.com/en-us/library/ms227976%28v=VS.90%29.aspx

Monday, December 12, 2011

Embedding WebBrowser control in WinForm

This is not something new but very useful in embedding the WebBrowser control in WinForm:

http://notions.okuda.ca/2009/06/11/calling-javascript-in-a-webbrowser-control-from-c/

Pros:

  1. Multi-media mash up without much GDI calls - you can add nice images, sound and video in your WinForm without having to use GDI api to draw the nice effect.
  2. Able to utilize JQuery (or JavaScript) - this allows you to develop application that shares some of the library that you have developed between the WinForm and ASP.net.
  3. Able to do fancy menu without going through the WPF/Silverlight route - just use all the HTML and JavaScript that you have already learned.
  4. No more "can't built nice control" any more.

Cons:

  1. Over-used of the JavaScript and HTML in WinForm might create chaos. It increases the difficulties in debugging.
  2. You must posses HTML, JavaScript and C# skills. Of course, you must have the SQL skill as well.


Saturday, September 24, 2011

How to list all database objects in Sqlite database

Execute the following query and you will see all the table definitions and view definition.

select *
from sqlite_master


Reference:
http://www.sqlite.org/faq.html#q7 

Tuesday, September 13, 2011

Detecting the parent Form from Component class

Component is a class that allows you to build non-visual control. For example, Timer class. By the problem is that it does not have a intuitive way to get the parent control.

Below is the code that will get the parent control reference and save the reference during the design time. Please take note the following code will work when you are dragging a control from the Toolbox onto the Form. For those Component that has already dropped on the Form before you added codes below, it will not work.

private ContainerControl _containerControl = null;
        public ContainerControl ContainerControl
        {
            get { return _containerControl; }
            set { _containerControl = value; }
        }

        public override ISite Site
        {
            get { return base.Site; }
            set
            {
                base.Site = value;
                if (value == null)
                {
                    return;
                }
                
                IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (host != null)
                {
                    IComponent componentHost = host.RootComponent;
                    if (componentHost is ContainerControl)
                    {
                        ContainerControl = componentHost as ContainerControl;
                    }
                }
            }
        }

Thursday, September 8, 2011

Getting the Windows system information

In case you want to find out the Windows system information such as printer configuration or network configuration, you may have to learn the WMI (Windows Management Instrumentation).

.Net comes with System.Management.ManagementObjectSearcher class which helps in digging the system information.

To find out more about WMI, visit the following URL:

http://wilsonmar.com/1wmiwbem.htm

To download the tool on generating C# code, visit the following URL:

http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=8572

To see the example on how to use the WMI tool, visit the following URL:

http://www.c-sharpcorner.com/UploadFile/scottlysle/UsingWMI04052007222505PM/UsingWMI.aspx

Registering data provider at runtime

In .Net, you may either register new data provider in the app.config file or register the data provider programmatically.
static bool _has_reg_sqlite_provider = false;

        public static void RegisterSqliteProvider()
        {
            if (_has_reg_sqlite_provider)
            {
                return;
            }

            var dataSet = System.Configuration.ConfigurationManager.GetSection("system.data") as System.Data.DataSet;

            if ((dataSet != null)
                && (dataSet.Tables.Count > 0))
            {
                DataRow[] rows = dataSet.Tables[0].Select("InvariantName='System.Data.SQLite'");

                if ((rows == null)
                    || (rows.Length == 0))
                {
                    dataSet.Tables[0].Rows.Add("SQLite Data Provider",
                        "SQLite Data Provider",
                        "System.Data.SQLite",
                        "System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.74.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"
                    );

                    _has_reg_sqlite_provider = true;
                }
            }
        }

Saturday, July 16, 2011

Extension method (3)

You may use extension method to increase the code readability too. For example, we often ensure that the object instance return by some function is not null before using.

CustomerClass customer = GetCustomerObject();

if (customer == null)
{
   // do this..
}
else
{
   // do that..
}

Wtih the extension method feature in C#, you may declare a new method call IsEmpty() which looks like this:

public static bool IsEmpty(this object obj)
{
  return (obj == null);
}

Now, you may do with your new IsEmpty() method:

CustomerClass customer = GetCustomerObject();

if (customer.IsEmpty())
{
   // do this..
}
else
{
   // do that..
}

Aside from improving the code readability, why we have to declare such IsEmpty() method instead of using "x == null"? This is what you are going to gain if you are using VS2010. When you type "." after the variable and follow by "Is", VS2010 will shortlist the methods that starts with "Is". Press Tab key to auto-complete the method name and you may move on to other code. This definitely will shorten the development time.

Note: you may rename this function to IsNull() or whatsoever.

Thursday, July 7, 2011

Updating database structure

Problem:


How to patch the database structure when upgrading the program?

Solution:


1. Create a class using the 'plug and play' concept (please refers to this topic). This class contains all the SQL scripts to be executed.
2. Upon the application startup, check the database version and run all the necessary SQL script to update the database structure.

Class design:


1. DBUpdate class:
  • This class stores the necessary patch for the given version.
  • Attributes: db_version, release_datetime & sql_script.
2. DBUpdateList class:
  • This class contains the DBUpdate object instance and it is responsible for executing all the patches.
  • Attributes: release_datetime & DBUpdate class type (note: it's not required to instantiate this object or otherwise will take up some memory and slowing down the application startup).

Flow:


1) Get the last patch date/time that stores in the database.
2) Get the list of the patches that is newer than the value get from step 1.
3) Execute all the necessary patches against the database.
4) Get the newest date/time among the patches that has been executed.
5) Update the last patch date/time into the database.
The purpose of storing the last patch date/time is to avoid all the patches being run each time the application starts. So, the application startup performance will not be affected much.

Friday, June 24, 2011

Extension method (2)

In my previous article, I have created an extension method call StrToInt for String class. Now, the question is what if a string object instance is null value and it's calling the extension method? Will the program crash? The answer is NO.

Try this out:

string s = null;
int i = s.StrToInt();

Thursday, April 14, 2011

Extension method

This is a new feature that has been added to C# in C# 3.0. One of the usefulness of extension method is to shorten the codes that we used to write.

For example, we want to convert a string value to integer. Normally, we will write code like this:

int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }

Instead of doing this, we may already have declared a static function which will do the conversion like this:

public class MyClass
    {
        public static int StrToInt(string s)
        {
            int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }
        }
    }

So, we will write our code like this:

int i = MyClass.StrToInt("1234");

Now, with extension method, the data type conversion call will be shorten:

    public static class MyClass
    {
        public static int StrToInt(this string s)
        {
            int i = 0;
            if (Int32.TryParse(s, out i))
            {
                return i;
            }
            else
            {
                return 0;
            }
        }
    }

    public class Test11
    {
        public void MyTestMethod()
        {
           // We don't have to write like this anymore:
           //int i = MyClass.StrToInt("1234");

           // Now, we can do this:
            int i = "1234".StrToInt();
        }
    }

Wednesday, February 23, 2011

Dynamic sorting using Linq Expression

You may wonder how to avoid hard coding the sorting order in the list. Here is one of the solution using Linq Expression:

class MyClass
{
   public int age { get; set; }
   public string name { get; set; }
}

MyClass[] arr =
{
   new MyClass() {age = 10, name ="abc" },
   new MyClass() {age = 20, name ="xyz" },
   new MyClass() {age = 30, name ="cde" }
};


// create the parameter
ParameterExpression param = Expression.Parameter(typeof(MyClass), "i");

// create the property to be used base on the 
// type (ie, MyClass) in the param variable. 
// you may change the "name" to any other field.
Expression prop = Expression.Property(param, "name");

// construct the lambda expression.
Expression> lambda 
   = Expression.Lambda>(prop, param);

// compile it to a function.
Func compile = lambda.Compile();

// now, we can use the function by passing it 
// to the OrderBy() proc.
var v3 = arr.OrderBy(compile);

string s;
foreach (var item in v3)
{
   s = item.name;
}