Thursday, June 28, 2012

Running different codes between debug mode and release mode

This is one of the compiler feature that is not widely used or not known by most of the programmers. For example, in ASP.net, you might want to use the full Java Script file in the debug mode. But, in the release mode, you might want to include the "light" version (or minified version). This is because the minified version requires lesser time for the browser to download it.

public void IncludeScript()
{
    Page pg = HttpContext.Current.Handler as Page;
    string js_url;
    string key = "jquery";

    if (!pg.ClientScript.IsClientScriptIncludeRegistered(key))
    {
#if DEBUG
       // for debug mode, include the full JavaScript.
        js_url = pg.ResolveUrl("~/js/jquery-1.7.1.js");
#else
       // for release mode, include the minified version.
        js_url = pg.ResolveUrl("~/js/jquery-1.7.1.min.js");
#endif

        pg.ClientScript.RegisterClientScriptInclude(pg.GetType(),
                                                    key,
                                                    js_url);
    }
}

Other situation where you might want to use this concept:

  • Set the default user name and password in debug mode.
  • Get and/or save the runtime value in debug mode.
  • Create a debug log while debugging the program.
  • Modifying or setting variable's value at debugging time.

Please take note that the compiler directive does not limit to ASP.net. It is meant for all kinds of project types.

Saturday, June 9, 2012

Invoking a static method through reflection

For example, you have a program that requires to download the updated version from the Internet through an updater program. And this updater program is a standalone EXE program which was shared among other software projects.

In the main program, you may invoke the method provided in the updater program by calling InvokeMember.

public static bool RequiresUpdate(out Version latest_veresion)
{
 latest_veresion = null;
 string url = GetUpdateUrl();
 string info_file_name = GetInfoFile();
 
 AppDomain app_domain = AppDomain.CreateDomain("AutoUpdate.exe");
 Assembly asm = app_domain.Load(s);

 // get the class.
 Type type = asm.GetType("AutoUpdate.CAutoUpdate");

 object[] param = new object[]
      {
       url,
       info_file_name
      };

 // execute the static function
 string[] need_update = (string[])type.InvokeMember("CheckUpdateInfo", 
       BindingFlags.Default | BindingFlags.InvokeMethod, 
       null, 
       null, 
       param);

 if (need_update != null
  && need_update.Length > 0)
 {
  string[] v = need_update[0].Split('=');
  if (v.Length > 1)
  {
   latest_veresion = new Version(v[1]);
   Version current_version = Assembly.GetExecutingAssembly().GetName().Version;

   if (latest_veresion > current_version)
   {
    AppDomain.Unload(app_domain);
    return true;
   }
  }
 }

 AppDomain.Unload(app_domain);

 return false;   
}