Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, May 08, 2014

.Net var (C#) Almost Everywhere, One Exception

Starting from .Net 3.0, Microsoft introduced type var in C#, as a simply way to binding strongly type. This is a very convenient way to define variables. Basically, .Net will be smart enough to infer correctly data type. It makes code maintenance and update much easy and no need to change data type in case variable types changed. I like it very much and use var almost everywhere.

However, recently I found one case this var is not able to infer explicit data type. In the case of dynamic delegate, you have to use explicit delegate type:


var myDelegate = delegate(int valueA, int valueB) { return valueA + valueB; };

.Net cannot infer what delegate type is for myDelegate. You have to use the explicit delegate type in this case:

delegate int SumOfTwoValues(int v1, int v2);
SumOfTwoValues myDelegate = delegate(int valueA, int valueB) { return valueA + valueB; };


I found this interesting exception when I was sharing my knowledge about delegate with my co-worker.

Read More...

Saturday, February 04, 2012

How to create a login page using ASP.NET MVC 3 Razor

I am back to MVC project. I used MVC for web application long time ago when it was still in Microsoft Patterns & Practice development. Now it is part of .Net 3.5 and 4.0 framework and all the classes and templates are available in Visual Studio 2011.

I need to add a Login page to my project. The way I did in my ASP.Net is quite different from the way in MVC. Since MVC has been changed a lot in terms of structure and framework, I have to learn MVC again. The MVC templates created by Visual Studio 2010 do not have Login feature. Fortunately, I found this tutorial on Youtube in short time:

The tutorial example is what I want.  It seems very easy to add Login page to MVC project.

First, add restriction in web.config file with Location element:

<configuration>
   <location path="">
      <system.web>
         <authorization>
            <deny users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

The above will disable access to all the pages in the site.  Then add authentication element for login page in web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Login/Login.aspx" timeout="120" />
</authentication>

In order to ensure the authentication in other web pages, a cooky is added before redirect to other forms on server side, as an indication been authenticated (part 3):

FormsAuthendication.SetAuthCookies(key, persistent);

In the place where log out is implemented, the following code is used to clear the cookie (part 4):

FormsAuthendication.SignOut();

That's all the basics.

In addition to those steps, the tutorial explains master page in MVC, which is in the Views->Shared folder. Different master pages can be specified (part 4). One interesting thing in MVC is that cs and html are all in one source code file as cshtml extension.

The tutorial also explains some very basic concepts in MVC:
  • Router structure in Global.assax (part 1)
  • Model for a view (part 5)
  • Get and Post actions mapping to View's methods

Read More...

Sunday, January 15, 2012

Two ASP.Net Tips

I will be on vacation to China and be back on Jan 15, 2012. Since the Blogger is not accessible from China, I have to schedule my blog so that I will keep my promise to write at least one blog per week. This blog is a scheduled post.

This is note on two tips I found in ASP.Net.

Bind Field with Object Method


It is very common to bind a field to an object's property value. However, I find out one case that I prefer to bind a field with the object's method. The advantage of binding to a method is that I can pass parameter values in. I found a solution from SO.

Here is my example:

<asp:RequiredFieldValidator 
ID="RequiredFieldValidator1" 
runat="server" 
ControlToValidate="txtValue1"
Visible='<%#((MyData) Container.DataItem).RawValueAvailable(1) %>'
ErrorMessage="Value cannot be empty">*
</asp:RequiredFieldValidator>

I need to add required validation control with a condition if there is value for the bound object.  The above example sets Visible with the method "RawValueAvailable(..) of the bound object of MyData.  It works great.

Set Login Timeout


By default ASP.Net authentication has a timeout of 30 minutes. This timeout looks like that it can be customized. I found an answer from SO. Here is an example:

<system.web>
  <authenticationmode="Forms">
    <formstimeout="50"/>
  </authentication>
  <sessionStatetimeout="60"  />
</system.web>

Setting the forms timeout to something less than the session timeout can give the user a window in which to log back in without losing any session data. However, I think that client side cached data will be gone if redirect is called. For example, if a user enters several data into a data grid view, the changed data may be lost if login timeout is passed. There may be a way to provide warning for saving data by using Javascripts.

References

Read More...

Tuesday, January 03, 2012

Interesting Discovery of float.Parse()

I found some thing really interesting about float.Parse() method. Normally, I thought this parse method should be able to convert any numeric string to a float value, as long as it does not cause overflow. However, I found that it does not really faithfully do the conversion. If the string value is too small or too big, you may lost some precision in value.

Here I tried to narrow down this issue to a test program:

private static void TestFloat() {
  for (int index = 1; index &lt; 10; index++)
  {
      string val = string.Format("{0}.123456", new string('8', index));
      float f = float.Parse(val);
      string sF = f.ToString();
      string sF1 = f.ToString("0.000000");
      Console.WriteLine(@"string value: {0}(len: {5}); float value: {1}(len: {6}-{7});
string to float.Tostring()    {0}=={1}? {3};
string to float.Tostring(xxx) {0}=={2}? {4}",
       val, f, sF1, val.Equals(sF), val.Equals(sF1), val.Length, sF.Length, sF1.Length);
  }
}

The result is very surprising:


string value: 8.123456(len: 8); float value: 8.123456(len: 8-8);
  string to float.Tostring()    8.123456==8.123456? True;
  string to float.Tostring(xxx) 8.123456==8.123456? True
string value: 88.123456(len: 9); float value: 88.12346(len: 8-9);
  string to float.Tostring()    88.123456==88.12346? False;
  string to float.Tostring(xxx) 88.123456==88.123460? False
string value: 888.123456(len: 10); float value: 888.1235(len: 8-10);
  string to float.Tostring()    888.123456==888.1235? False;
  string to float.Tostring(xxx) 888.123456==888.123500? False
string value: 8888.123456(len: 11); float value: 8888.123(len: 8-11);
  string to float.Tostring()    8888.123456==8888.123? False;
  string to float.Tostring(xxx) 8888.123456==8888.123000? False
string value: 88888.123456(len: 12); float value: 88888.13(len: 8-12);
  string to float.Tostring()    88888.123456==88888.13? False;
  string to float.Tostring(xxx) 88888.123456==88888.130000? False
string value: 888888.123456(len: 13); float value: 888888.1(len: 8-13);
  string to float.Tostring()    888888.123456==888888.1? False;
  string to float.Tostring(xxx) 888888.123456==888888.100000? False
string value: 8888888.123456(len: 14); float value: 8888888(len: 7-14);
  string to float.Tostring()    8888888.123456==8888888? False;
  string to float.Tostring(xxx) 8888888.123456==8888888.000000? False
string value: 88888888.123456(len: 15); float value: 8.888889E+07(len: 12-15);
  string to float.Tostring()    88888888.123456==8.888889E+07? False;
  string to float.Tostring(xxx) 88888888.123456==88888890.000000? False
string value: 888888888.123456(len: 16); float value: 8.888889E+08(len: 12-16);
  string to float.Tostring()    888888888.123456==8.888889E+08? False;
  string to float.Tostring(xxx) 888888888.123456==888888900.000000? False

To my discovery, the parsed result lost its precision, 9 out of 10!

I found this issue when I tried to take an input string from a text box, convert it to a float value and finally save to database.  My tester found that the results are not consistent when value is too big. At the beginning I did not believe it, but after I repeated the case, I found the bizarre result.  Finally I realized the issue is caused by Parse() method.

Any way to get around this issue? It seems there is no way to save the exactly value to database. Even I can save the value as a string to database, eventually, it may reach a point that database will present the value as xxxEzz format, which may lost precision when the value is retrieved back.

It looks like that we have to limit values to be entered, to a realistic range. Then handle the value from UI to database or vice visa.


This blog is published by schedule.

Read More...

Sunday, December 18, 2011

Using LDAP to Authenticate Windows Users

Here are some my programming notes about using LDAP library to authenticate Windows Users.

This request came from my ASP.Net project, which is hosted on intranet IIS server. The first login page is to authenticate Windows users in the company.  I need a library to do the job.  I tried some codes created long time before, but I found that the codes is not completed.  The authentication works only in Visual Studio, but not at an IIS server after deployment. I need to fix the issue.

I found that there are many ways to do that.  One is based on our existing codes with Novel.Directory.Ldap library, another on System.DirectoryServices. I tried both in one test console application.

Here some some references and constants used in the console application:

using System;
using Novell.Directory.Ldap;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using AD_LdapConnection = System.DirectoryServices.Protocols.LdapConnection;
using ND_LdapConnection = Novell.Directory.Ldap.LdapConnection;
using System.Net;
...
private const string LDAPHOST = "xxxx.yy.zzzz.com";
private const int LDAPPORT = 389;
private const string DOMAINNAME = "yy";
private const string CN_NAME_SUFIX = "@yy.zzzz.com";

Novel.Directory.Ldap


The first one is base on Novel.Directory.Ldap:

private static bool Authenticate(string username, string pwd)
{
  bool bRet = false;
  bool connected = false;

  // connect to LDAP server
  ND_LdapConnection ldapConnLogin = new ND_LdapConnection();
  try
  {
    Console.WriteLine("Start authenticating...\nConnecting to {0}, port: {1}",
      LDAPHOST, LDAPPORT);
    ldapConnLogin.Connect(LDAPHOST, LDAPPORT);
    connected = ldapConnLogin.Connected;
    if (connected)
    {
      Console.WriteLine("Connected: {0}", connected);

      string cn = string.Format(
        "{0}{1}", username, CN_NAME_SUFFIX);
      Console.WriteLine("Binding with {0}", cn);
      ldapConnLogin.Bind(cn, pwd);
      bRet = ldapConnLogin.Bound;
      Console.WriteLine("Bound: {1}", bRet);
    }
  }
  catch (Exception ex)
  {
    string msg = string.Format(" Error message or code: {0}", ex.Message);

    Console.WriteLine(msg);
    bRet = false;
  }
  finally
  {
    if (ldapConnLogin != null && connected)
    {
      ldapConnLogin.Disconnect();
    }
    ldapConnLogin = null;
  }

  return bRet;
}

This methods depends on ldap host name, port number, and cn name(in a format like email address in our company). One thing interesting is that the exception thrown from the binding call are error codes in Message, and no implementation of ToString() method.

System.DirectoryServices


The second method is Microsoft .Net library APIs in System.DirectoryServices. The following codes are much simpler and works in the same way to authenticate a Windows user:

private static bool Authendicate2(string domain, string userName, string password)
{
  bool validation = false;
  try
  {
    Console.WriteLine("Authenticating user by AD library...");
    var ldc = new AD_LdapConnection(
        new LdapDirectoryIdentifier(LDAPHOST, false, false));
    NetworkCredential nc = new NetworkCredential(userName, password, domain);
    Console.WriteLine("Created credencial object.");
    ldc.Credential = nc;
    ldc.AuthType = AuthType.Negotiate;
    Console.WriteLine("Binding credencial...");
    ldc.Bind(nc);
    // user has authenticated at this point, as the credentials were used to login to the dc. 
    Console.WriteLine("Binding credencial is done.");
    validation = true;
  }
  catch (Exception ex)
  {
    Console.WriteLine("Exception: {0}", ex.Message);
    validation = false;
  }
  return validation;
}

References

Read More...

Thursday, December 08, 2011

In the past weeks I have been working on an ASP.Net web site application. I tried to use my ILog and LogToFile initially. However it failed miserably. ASP.Net web pages are based server and client architecture pattern. The IIS Server does not know when the web page on client side will call back. This means that I cannot keep the log file opened forever. I tried to close the log file for each message log.  I found that I could not keep the same log file since my log file name is in a patten like mylog_yyyymmdd_hhmm.log. The sever side will open another log file since the file name is kept on the server side. I could remove minutes out, but I don't like it. Therefore my original library for logging messages is not good for web site applications.

Further investigating the sever side class codes, I found that on the IIS server, writing to a text file is not allowed. I tried to write to a folder out of inetpub folder, such as C:\Log, still it is not writable.  I may be able to figure out by change IIS application pool permission, but I don't that's may cause security holes.

I had to take different strategy to log messages. I changed my log helper class to write messages to a SQL server database. This actually works fine. I realize that there are some drawbacks about this. As I mentioned in the above analysis, I cannot keep database connection open all the time. So I have to close connection for each log.  This results a very slow logging process since the database connection has to be opened and closed constantly. But it works fine.  In order to improve performance, I used delegate for log message so that if log setting is off, no db connection operation at all.  The second good practice is to use a pair methods of BeginDBLog() and EndDBLog() to allow database connection open for several log processes.

Here are some class data members in DBLog class:

# region Data members
private static DBLog _log;
private IDbService _db;
private SQLQuery _sqlQuery;
private DBLogConfig _config;
# endregion

Since the instance of DBLog is singleton, I use a method to control the instance creation. The pair methods are used for keep the instance of IDbService alive:

public static DBLog GetInstance(DBLogConfig logConfig)
{
  if (_log == null)
  {
    _log = new DBLog(logConfig);
  }
  return _log;
}

#region CTOR
private DBLog(DBLogConfig config)
{
  _config = config;
  _sqlQuery = new SQLQuery(_config.StoreProcedureName);
}
#endregion

public void BeginDBLog()
{
  if (_db == null)
  {
    if (_config != null)
    {
      _db = new DBService(_config.DBConnection,
        _config.SQLOrOracle ?
        DBService.DBType.MicrosoftSQLServer :
        DBService.DBType.OracleServer);
    }
  }
}

public void EndDBLog()
{
  if ( _db != null )
  {
    _db.Close();
    _db = null;
  }
}

Here are methods for logging messages:

public void LogMessage(string flags, LogType logType, string msg)
{
  LogMessage(flags, logType, delegate() { return msg; });
}

public void LogMessage(string flags, LogType logType,
    LogHelper.GetMessageDelegate getMessageDelegate)
{
  if (IsLogSet(flags, logType) && getMessageDelegate != null)
  {
    bool close = false;
    if (_db == null)
    {
      BeginDBLog();
      close = true;
    }
    string msg = getMessageDelegate();
    if (!string.IsNullOrEmpty(msg))
    {
      if (_sqlQuery.Parameters.Count > 0)
      {
        _sqlQuery.Parameters.Clear();
      }
      bool sqlOrOracle = _config.SQLOrOracle;
      DateTime dt = DateTime.Now;
      if (msg.Length > MAX_LENGTH)
      {
        msg = msg.Substring(0, MAX_LENGTH - 1);
      }

      _sqlQuery.Parameters.Add(SQLQuery.GetParameter(sqlOrOracle,
        _config.ParameterDate, dt));
      _sqlQuery.Parameters.Add(SQLQuery.GetParameter(sqlOrOracle,
       _config.ParameterLogType, logType.ToString()));
      _sqlQuery.Parameters.Add(SQLQuery.GetParameter(sqlOrOracle,
        _config.ParameterApplication, _config.ApplicationName));
      _sqlQuery.Parameters.Add(SQLQuery.GetParameter(sqlOrOracle,
        _config.ParameterMessages, msg));
      _sqlQuery.Parameters.Add(SQLQuery.GetParameter(sqlOrOracle,
        _config.ParameterSiteID, _config.SiteID));

      int result = _db.ExecuteSqlNoneQueryCommand(_sqlQuery, CommandType.Text);
    }
    if (close)
    {
      EndDBLog();
    }
  }
}

Notes: the above codes depend on my DotNetCommonLibrary and a class of DBLogConfig for database configuration.  The configuration class is a simple class with property getters and setters for database type, stored procedure name, and parameter names, as well as related configuration values.

Read More...

Saturday, December 03, 2011

Read Password from Console

Yesterday I was write codes to test my class for user Windows authentication. The simple console app will take user name and password as input. I would like password from console input like *** from a text box. By googling search, I found the following codes. They works as expected.

The example codes are very simple. Actually I tried to search from Console class in Visual Studio, and I found ReadKey method. I did not figure out how to get input from this method, since the keys from the methods are all in caps. Then I searched the web and found this solution. Sharing is great!

public static string ReadPassword() {
  Stack<string> passbits = new Stack<string>();
  //keep reading
  for (ConsoleKeyInfo cki = Console.ReadKey(true);
      cki.Key != ConsoleKey.Enter; cki = Console.ReadKey(true)) {
    if (cki.Key == ConsoleKey.Backspace) {
      //rollback the cursor and write a space so it looks backspaced to the user
      Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
      Console.Write(" ");
      Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
      passbits.Pop();
    }
    else {
      Console.Write("*");
      passbits.Push(cki.KeyChar.ToString());
    }
  }
  string[] pass = passbits.ToArray();
  Array.Reverse(pass);
  return string.Join(string.Empty, pass);
}

Reference

Read More...

Friday, November 11, 2011

Add Customization to Web.config

I have not touched ASP.NET project for about one year.  Now I am back to a new ASP.NET project. Even though it is not too hard to pick it up and add my new skills and extensions to the project, I have to constantly refer to the project I worked before.  For sure, I would not like to copy the same structure and design into the new project.  The project is a .NET 2.0 based ASP.NET, but I am planning to update it to .NET 4.0 ASP.NET MVC 3 in the next stage, most likely next month or next year, if my contract extension would pass.

One thing I like to add is customized configuration.  I prefer to define my configuration out side of web.config, because there are so many special nodes designated to ASP.NET project or web site. I know there is a way to add customized nodes there, but I want to re-use my pattern to parse XML doc with my library.

At least I have to add one node in web.config. This is very easy:

<configuration>
  <!-- application specific settings -->
  <appSettings>
    <add key="MyConfigurationFile" value="config/MyConfiguration.xml" />
  </appSettings>
  ...
</configuration>

The above entry defines an application-wide setting named MyConfigurationFile with the string value config/MyConfiguration.xml, the configuration xml file in the web site folder config. With this setting, I can get the xml file like:

string file = ConfigurationSettings.AppSettings("MyConnfigureationFile");
file = string.Format("{0}{1}",
    AppDomain.CurrentDomain.BaseDirectory, file);
...

Reference

Read More...

Thursday, October 27, 2011

Procedures in Oracle Server and SQL Server

Recently I have been working on a project to provide data for a third party application, called ParcView. The PV is used to view data source from OPC and databases. The requirement of one data source is from Oracle database.

PV provides a system configuration of SQL templates for data source in data, current, tag list and tag information, four major areas (some others are rarely used).  I have done a lots for SQL database server, and some of Oracle database. Based on the recommendation, if the template SQL scripts are too complicated, it is recommended to use stored procedures as a way to provide data.

In SQL SP, data source can be directly returned by using SELECT statement.  However, in Oracle, this type of return is not available.  What I found is that all the data row set has to be returned by a OUT parameter SYS_REFCURSOR type. This makes it is impossible for me to implement in the same way as I did for SQL server before.

I have tried another way, view with parameters. Basically, a package is defined with functions and procedures. They are in a structure of property: get in function and set in procedure.  A local variable in the package as a storage for property values.  Then the view references to the functions are parameter.  Before calling the view, a PL/SQL command exec is called first.  This strategy is back to he none-SQL query problem.  PV does not have a way to call it. As a result, this strategy hits the dead wall again.

It is really hard for me to put scripts on database server side. The lesson I learned is that the PV should problem a kind of interface based APIs to allow plugin components.  Now I recall that the provider of PV does have a way to add customized data source, but we have to ask the company to write codes to do it. They will charge for the service.

Maybe I should ask the computer to provide a component to allow customized plugin to provide data source.


Read More...

Saturday, October 15, 2011

Extension Class: LogHelperExt

I wrote a helper class for logging text messages long time ago. Recently I tried to write a document and demo project about using this helper class.  During the writing process, I found that the helper class can be further enhanced.

The helper class provides some static methods for writing a message string. One of  basic method takes several parameters, with ILog instance as its first parameter.  I realized that actually this instance is not needed to be passed in since this is a singleton instance. Why should I pass it every time? I started to simple this method.  The strategy I took is to add another helper class, called as LogHelperExt. I tried to avoid to change LogHelper because this class has been used in many places.

The new helper class contains much simple APIs. The first one is Initialize:

public class LogHelperExt {
  private int m_Spaces;
  private int m_indents;

  public static ILog Logger { get; private set; }
  public static LogHelperExt Instance { get; private set; }

  private LogHelperExt() : this(0)
  {
  }

  private LogHelperExt(int indents)
  {
    m_Spaces = 0;
    m_indents = indents;
  }

  public static LogHelperExt Initialize()
  {
    return Initialize(null, 0);
  }

  public static LogHelperExt Initialize(ILog log)
  {
    return Initialize(log, 0);
  }

  public static Initialize(ILog log, int indents)
  {
    if ( Instance == null )
    {
      Instance = new LogHelperExt(indents);
      Logger = log;
    }
  }
  ...
}

The Initialize method is to pass ILog instance in. This method is normally used once. An additional indent value is passed for a new feature of indenting spaces for logged messages.

The commonly used API for writing messages is as followings:

public LogHelperExt WriteMessage(string flags, LogType logType, GetMessageDelegate getMessage)
{
  if (getMessage != null )
  {
    LogHelper.WriteMessage(Logger, flags, logType,
        delegate()
        {
          return string.format("{0}{1}",
            m_Spaces > 0 new string(' ', m_Spaces) : "",
            getMessage):
        }
  }
  return this;
}

This interface is much cleaner than before. Notice that the API method is an instance method with data type of the class itself. I intended to design this class in this way, fluent interface pattern, so that I can chain the calls just in one line.

The indention and un-indention feature are added to this class:

public LogHelperExt Indent() {
  m_Spaces += m_indents;
  return this;
}

public LogHelperExt Unindent {
  m_Spaces -= m_indents;
  if ( m_Spaces < 0 )
  {
    m_Spaces = 0;
  }
  return this;
}

With above changes, I will use LogHelperExt for logging messages. Here is the example I wrote in my demo project:

class DemoClass {
  public void TestMethod()
  {
    LogHelperExt.Instance.WriteMessage("d", LogType.Debug, "Enter TestMethod").Indent();
    ...
    LogHelperExt.WriteMessage("d", LogType.Debug, "Test message");
    ...
    LogHelperExt.Instance.UnIndent().WriteMessage("d", LogType.Debug, "Leaving TestMethod");
  }
}

Read More...

Saturday, October 01, 2011

Json.Net Issue: does not support namespace in XML

Yesterday I had a talk to a developer at work. She came from the same city as my hometown where I was grown up. She was working on a project to import thousands of XML files SQL database. I recommended my dotNetCommonLibrary.dll, where I have a wrapper class for Json.Net.  The wrapper class provides several APIs to convert XML string to an instance of a class and vice versa.  I have used this feature to convert many application XML configuration settings to instances.

However, when I saw her XML files, I noticed that those XML files contains namespaces, which are used in XML nodes as prefix. I had never tried those types of XML documents before. Today I tried a simple XML file with a namespace for testing. Unfortunately, it looks like that Json.Net converter does not support XML with namespaces.

Example of XML with namespaces:

<?xml version="1.0" encoding="UTF-8" ?>
<Root>
  <b:Log xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' >
     ...
  </b:Log>
</Root>

I think this type XML files are very common. I have to find out a way to remove namespaces and use only local names in XML notes for instance mapping by Json.Net

It was a good talk. At least I find my wrapper class has to provide an API to remove namespaces from an XML string.

References


Read More...

Sunday, September 25, 2011

My Collection of Programming Podcasts

Podcasts are important information resources I have in the past years. I listen and watch for those audio and video podcasts during slices of my time, on the way to and from work, lunch time, weekends, and anytime available for me such rest time during camping.

Basically, I sync my Apple mobile devices at lest once a week through iTunes. Here are the collection of podcasts I have right now:

Audio/Video podcasts:


  • CNET: Buzz Out Loud (Tech news)
  • DailyAppShow (iOS device app reviews, videos)
  • GeekBeatTV (Tech video show)
  • Hanselminutes (.Net tech news/programming)
  • HerdingCode (.Net programming)
  • iPone/iPad/Android App Reviews by CrazyMikesapps (videos)
  • jQuery for Designers - screencasts and turotirals (videos)
  • CNET: Loaded (videos)
  • Mac Geek Gab
  • the Maccast for Mac Geeks by Mac Geeks
  • MacMost Now - Mac and iPhone Tips and Tutorials (videos)
  • MacTalk
  • Macworld podcasts
  • .Net Roks!
  • ScreenCastsOnline Free Version (videos)
  • Tech NightOwl
  • Today in iOS Podcast - The Unofficial iOS, iPhone, iPad and iPod Touch News and iPhone Apps Podcast
  • Typical Mac User Podcast
  • WebBeastTV(HD) (videos)
  • Wired's Garget Lab Video Podcast (videos)
iTunesU:

  • UCDavids University of California: Introduction to iPhone Application Development (fall 2009)
  • Stanford Univierty: Developing Apps for iOS (spring, fall 2010, summer 2009)
  • RWTHAACHEN University: iPhone Application Programming WS 09/10
  • Apple: iPhone Getting Started Videos (08)
  • University of Utah: iPhone Programming Association - Audio
  • Apple Developer Connection: iPhone Tech Talk World Tour (09)
  • Apple: iPhone Tech Talks (07)
  • WWDC 08, 09, 10, 11
Above list is only the one for my programming and tech news information and updates. In addition to that, I also have a wide range of other topics and areas I listen and watch on daily basis, as you can see in my screen snap-shots.

Read More...

Sunday, August 28, 2011

Open/Closed Principle: Delegate Example

In object-oriented programming, the open/closed principle is a very important principle. Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Recently I tried to summary some commonly used components in a serials of documents. I found that I have used delegate in my LogHelper class. This reminds me about my OCP.

I was not intended to use delegate as a way to extend my log feature. I was using it to avoid building a message string but not actually used for logging. I thought it will be nice to use a pointer to function which returns a string. So that the function would be called dynamically only if logging is enabled.

public delegate string GetMessage();

public static class LogHelper {

public void WriteMessage(
ILog log, string flag, GetMessage getMessage)
{
if (log != null && getMessage != null
&& log.IsLogSet(flag))
{
var msg = getMessage();
log.write(msg);
}
...
}


Here is an example of the usage:

LogHelper.WriteMessage(log, "d", delegate() {
return string.format("MyObject: {0}",
myObject.ToString());
};



As shown in above example, user can build a simple or complicated string for logging. Since the building codes are in a dynamic delegate. The delegate will only be called when the log flag "d" is enabled.

I think that my design of LogHelp class is a typical way to OCP. Here is another example to use the same method to enable indention and un-indention for messages:

class DataProcess {
private int m_indention = 0;

private void LogMsg(bool indent, GetMessage getMsg)
{
if ( getMsg == null )
{
return;
}

if (indent)
{
m_indention+= 2;
}
else if ( m_indention > 0 )
{
m_indention -= 2;
}
else
{
m_indention = 0;
}

LogHelper.WriteMessage(log, "d", delegate() {
return string.format("{0}MyObject: {1}",
new String(' ', m_indention),
getMsg());
};
}
...
}




Read More...

Saturday, June 25, 2011

CoffeeScript and .Net Nancy Framework

Last week when I listened to my podcasts, two projects got my attention. The firs one is from HerdingCode podcast 114 about: Trevor Burnham on CoffeeScript. This is light language in clean syntax that can be compiled into JavaScripts, in one to one relationship.

The second one is from HansellMinutes on 6/16/2011: Nancy, Sinatra and Exposion of .Net Micro Web Framewor. The Nancy project was introduced on Nov 28th, 2010. The blog site Elegent Code posted a blog about this podcast as well on Jun 28, 2011.

Read More...

Sunday, May 22, 2011

Create Shortcut in C#

Last week I was working on a case to provide support for an application users. The application has two executables: one is app's main exe like app.exe and another one is for app's update like appUpdate.exe. For this update, we need to add a shortcut on clients machine desktop pointed to appUpdate.exe.

Like a typical shortcut, the one I need to put on client PCs has several settings: target, start in, run mode, icon and comments.



I tried to create a shortcut on my box first. Aftert that, I tried to copy this shortcut file (lnk) to a remote PC. It did not work. It seems that the lnk file some information are embedded in the file. When it is not in the machine where it was created. The machine name appears in the target.

I need a way to create a shortcut on fly. That's why I went to .net to create a simple console app do the job. This time SO helped me with an excellent open source library from a QA: ShellLink.cs. Within the source codes, there are actually two files I need: ShellLink.cs and FileIcon.cs. The library contains a wrapper class for Windows APIs. It is very straight forward.

The only change I made is to add a class level flag for any changes in shortcut properties. If any setter changes a value, this flag is true. Then I'll only save chances for the shortcut if any of properties are changed.

public class ShellLink : IDisposable {
private bool mChanged = false;
....
public string Target {
get { .... }
set { if (!value.Equals(Target)) {
mChanged = true;
....
}
....
}

Read More...

Saturday, February 12, 2011

.Net Project to Copy Excel Data

In the past weeks, I have been working on a project to copy Excel data between worksheets. The source worksheet contains some formulas with links to other worksheets and add-ins. The problem is that the API functions defined in add-ins take long time to get data from a remote service. When there are hundreds and even thousands of rows in Excel, it will take to long time to refresh data. That's the reason to have a scheduled job to copy the daily data from source excel file to another one with only values. Since the output put excel file contains only values, the show time is much responsive.


The project was initially created in .Net by using Microsoft.Interop.Excel, which is a warper class for Excel COM components. This is the first time I saw this namespace and real case usage. Basically, with this namespace and classes there, you can create Excel application, open existing or create new workbook, create or get worksheet.

I found that it is very powerful and interesting to do almost the same work in .Net project as you do interactively with Excel in Windows. For example, if the source excel file contains some links, you can ignore those links and rebuild them in .Net. You can reset excel cell data value and simulate special copy and paste to copy only values to another worksheet.

I updated the project to move many hard-coded settings out to a configuration file so that the tool will be more generic. The goal of the tool is to copy values from an excel file to another one. The figuration contains those settings:
  • Input and output excel files;
  • The links in both input and output files to be rebuilt;
  • Data values to be set in input file. Those values are in range object of an excel worksheet object. The values are strings or Excel formulas;
  • The range of data to be copied in the input file and destination range in the output file;
  • Page layout settings: display grid lines, window display headings, page area and line breaks.
I found one setting is very helpful. You can set excel object visibility so that you can debug your codes by viewing Excel status. With this debug feature, I found many bugs or wrong settings in the existing codes.

The project is almost rewritten to become a more generic tool with configurable feature. I used this not only resolve the original required excel report issue, but it has been used in many other cases. However, personally, I don't think doing the excel work in .Net is a practicable. The excel classes are to easy to be broken. When the project becomes a more generic tool, many unseen issues have not been tested. I don't want to spend too much time to fix issues. The coupling data and report to Excel is too much pain.

Read More...

Saturday, October 23, 2010

.Net Debug Class (3)

Implementation Class: DianosticsDurationHelper

To calculation duration between two debug calls, I created an implementation class: DianosticsDurationHelper. In addition to two public properties in the base class, the implementation class provides a few public methods.


As you can see, the duration helper class has very simple APIs. One method Indent() is used for indentation or un-indentation, and one method for debug a message. The duration calculation is done within the class.

As discussed above, the calculation is done through delegates. Two private methods are defined here. One is for obtaining the current date time value, and another for calculating the duration value. Those methods are used as delegates to the base class calls.

private DateTime GetDateTime()
{
return DateTime.Now;
}

private string CalculateDuration(DateTime dt, DateTime poppedValue)
{
float duration = (float)((new TimeSpan(dt.Ticks - poppedValue.Ticks)).Hours) * 3600.0f +
(float)((new TimeSpan(dt.Ticks - poppedValue.Ticks)).Minutes) * 60.0f +
(float)((new TimeSpan(dt.Ticks - poppedValue.Ticks)).Seconds) +
(float)((new TimeSpan(dt.Ticks - poppedValue.Ticks)).Milliseconds) / 1000.0f;
return string.Format(" duration: {0:N2}", duration);
}

The remaining part of the duration helper class is as followings:

internal class DianosticsDurationHelper : DianosticsHelperBase<DateTime>
{
public DianosticsDurationHelper(string className) : base(className)
{
}

public DianosticsDurationHelper DebugMessage(string message)
{
base.debugMessageBase(message);
return this;
}

public DianosticsDurationHelper Indent()
{
return DebugIndent(true);
}

public DianosticsDurationHelper UnIndent()
{
return DebugIndent(false);
}

private DianosticsDurationHelper DebugIndent(bool indent)
{
if (indent)
{
base.debugIndent(GetDateTime);
}
else
{
base.debugUnindent(GetDateTime, CalculateDuration);
}
return this;
}
...// private methods used as delegates, see above.
}

Usage Examples

In many of projects, I used this duration class to get duration time between the begging and end of each call. Here are some example codes.

[STAThread]
static void Main() {
// customize indent string to --
DiagnosticsDurationHelper.IndentString = "--";
MyForm mainForm = new MyForm();
Application.Run(mainForm);
// ...
}

// MyForm.cs
class MyForm : Form {
// some helper methods using duration helper class
private DianosticsDurationHelper _debugHelper =
new DianosticsDurationHelper("MyForm");
// other data members
// helper methods to use the debug instance
private void DebugMessage(string message) {
_debugHelper.DebugMessage(message);
}

private void DebugMessage(string message, bool indent) {
if (indent) {
_debugHelper.DebugMessage(message).Indent();
}
else {
_debugHelper.UnIndent().DebugMessage(message);
}
}
// use debug helper methods to log duration...
private void MyForm_Load(object sender, EventArgs e) {
DebugMessage("MyForm_Load", true);
// ...
DebugMessage("Some information...");
// ...
DebugMessage("MyForm_Load", false);
}
// ...
}


By the way, in my helper class and base class, I tried to use fluent interface pattern for APIs. As you can see, the usage of those APIs is much fluent and clean.

To get the debug result in my Visual Studio's output console, I run my application in debug mode. Alle debug strings will be in the output console. Here are some results:

--[ 10/18/2010 11:21:58 AM ] MyForm::MyForm_Load
----[ 10/18/2010 11:23:58 AM ] DBGateway::DBGateway
...
----[ 10/18/2010 11:23:58 AM duration: 0.02 ] DBGateway::DBGateway
--[ 10/18/2010 11:22:58 AM ] MyForm::Some information ...
...
--[ 10/18/2010 11:21:58 AM duration: 0.22 ] MyForm:: MyForm_Load

Here is the source codes with an example.

Read More...

Sunday, October 17, 2010

.Net Debug Class (2)

My debug class contains one base class. Let's see the structure of the base class.

DianosticsHelperBase Class

My debug class is a simple base class, DianosticsHelperBase:


The above class picture shows all the public properties and protected helper methods for derived classes. Let's discuss the design of the base class.

Layout Format of Debug Message

The main purpose of the debug class is to print or log messages. The message consists two key parts: timestamp and message, with additional optional parts: context, indent, and calculated value.

The context is used as a convenience to identify message's context, for example, a class or module name could be used to mark debugged messages within the context.

Indentation is a nice feature to layout debug messages. The indentation and un-indentation are done through two method calls. DebugIndent() and DebugUnindent(). The indentation string can be set by the static property InentString. Null or empty string can be set to IndentString to disable indentation, or other strings to customize an indentation string, such as "—". The default indent string is a string of two spaces:

private static string _indentStr = "  ";

The base class provides another nice feature to calculate a value between two points. This is done by providing delegates to method calls: DebugIndent() and DebugUnindent(). If null delegates are passed to the calls (parameters), no calculation will be donem, thus disable the calculated value feature.

The layout format of debug messages is set by the static property Format of the base class. The default layout is:

//indent, timestamp, calculatedValue, context, message
private static string _format = "{0}[ {1}{2} ] {3}::{4}";

Constructor

Typically, an instance of the debug class is a member of a class where debug messages will be logged by the instance within its internal codes. A context string for the instance is set through the base class CTOR. The context of the debug instance is set in its creation time.

private string _context;
private string _calculatedValue;

public DiagnosticsHelperBase(string context) {
if (context != null) {
_context = context;
}
else {
_context = "";
}
_calculatedValue = "";
}

Helper Methods

A message is logged or output by the protected method debugMessage. In this method, a message is formatted as a string and output to a media. In the following codes, the output is passed to Output console in the Microsoft Visual Studio.

private string _context;
private string _calculatedValue;
private static bool _logMessage = System.Diagnostics.Debugger.IsAttached;

protected DiagnosticsHelperBase<T> debugMessage(string message) {
if (_logMessage)
{
System.Diagnostics.Debug.Print(
string.Format(_format, getIndent(), DateTime.Now,
_calculatedValue, _context, message));
_calculatedValue = "";
}
return this;
}

private string getIndent() {
string sVal = "";
if (_indent > 0)
{
int i = 0;
do
{
sVal = string.Format("{0}{1}", sVal, _indentStr);
i++;
} while (i < _indent);
}
return sVal;
}

The method checks _logMessage before further logging messages. This flag is set by Syste.Diagnostics.Debugger.IsAttached. If the build is in release mode, this flag will be False, as a result, no calls to log messages.

The concept of a calculated value is based on the consideration of calculating a value between two debug points, for example, a duration time value between the beginning and the end of a method call. This is done within the base class by two method calls: debugIndent() and debugUnindent(). How a value is obtained and how the calculated value is done are provided by passing delegates as parameters to those method calls. This provides a flexible way to generate calculated values such as duration, memory usage, disk free spaces and so on.

protected DiagnosticsHelperBase<T> debugIndent(GetValue<T> pushedValueDelegate) {
if (_logMessage)
{
if (pushedValueDelegate != null)
{
T value = pushedValueDelegate();
_debugDts.Push(value);
}
_calculatedValue = "";
_indent++;
}
return this;
}

protected DiagnosticsHelperBase<T> debugUnindent(GetValue<T> fromValueDelegate, GetCalculatedValue<T> calculatedValueDelegate) {
if (_logMessage)
{
if (calculatedValueDelegate != null && fromValueDelegate != null)
{
T value2 = _debugDts.Pop();
T value1 = fromValueDelegate();
_calculatedValue = calculatedValueDelegate(value1, value2);
}
if (_indent > 0)
{
_indent--;
}
}
return this;
}

All the methods in the base class are protected. They are only available for a derived class to implement specific debug usages. For example, the following duration helper class is an example for logging messages with duration information.

Read More...

Monday, October 11, 2010

.Net Debug Class (1)

I wrote a blog on debug or logger class in Objective-C about couple months ago. Actually, that class was based on my prevous .net debug class. It has a feature to print debug information in a nice indention layout, which was extended to my Objective-C class. I think my .Net is very useful, at least for me, and it is more generic, with an additional feature to calculate a value between paired messages(indent and un-indent).

Background Story

I was assigned to a task to resolve a painful slow performance issue of a .Net Windows application project. I did not spend much time to understand the complete business logic of the application. I went to the issue directly. What I did was to create a debug class to print out time and duration of each method or event call. Based on that information, I then focused on the longest duration calls to find out ways to improve the performance issue. The task was finished in very short period of time and the performance was greatly improved. My debug class is a very generic and useful tool. I have used this in my other projects with great success. With this experience and design, I created a similar logger class in Objective-C when I started iPhone development.

The intension to create this debug class is mainly based on three considerations. First is to generate debug message with duration information for each method or event call. This is the main reason and it is very easy to do. This could be done without a class. However, I would like to have debug message in a consistent format or indention. A class can encapsulate the implementation and provide unified interface. This second consideration actually was trigged by System.Diagnostics.Debug class, which has a nice property IndentLevel and a method Indent.

The third consideration is the maintenance. Since the debug calls are spread out all over the places in a project, it will be really hard to clean up them when the project is finally released. I would like to keep the debug feature or codes in my project without removing them, but also have least impact on its performance. As you will see, I have introduced delegates and early checks to avoid unnecessary calls if debug is disabled.

Delegates Used in the class

I like to use delegates as a way to pass custom implementation to my class. The first advantage is that it follows Open/closed-principle. It opens for extension or plug-in, but close my class for any modifications. The second advantage is to improve performance. Delegates normally used as parameters. They are pointers to functions or methods. If a delegate is not called for execution, its internal codes will never be evaluated. The following delegates are defined:

public delegate T GetValue<T>();
public delegate string GetCalculatedValue<T>(T value1, T value2);

The first one is a delegate to get a value. The delegate provides a way to let client to define his/her implementation to get a value. For example, for duration case, a delegate can be defined just returning a value of DateTime.Now.

The second delegate is for calculate a value based two parameter values, from value1 to value2.

Read More...

Saturday, June 19, 2010

Detect Window Form Application Status

notesLast month, I was working, actually fixing bugs to resolve exceptions, and to improve performance, on an application which is a Windows Form application. One feature client wants is to query data from a SQL server periodically and refresh the UI with the retrieved data. The data may not be changed, but there was no inelegance to know if there was change. Therefore, the UI refresh was enforced because clients want to get the most recent data.

During the process to refactory codes to enhance/optimize SQL queries, I realized that clients wants the more recent data because they want to see any changes when the application is in running. There are many cases this kind of refreshing is actually not necessary. For example, when the window form is minimized, or the OS Windows is locked. In many cases, clients just left the application running after their work. Windows is locked, but the application had still been pulling data from the SQL server.

Then I proposed a optimized strategy to stop the data pulling when the UI is not available, either minimized or Widnows is locked. My suggestion was accepted.

Checking Application Status

To find out the Window from's status is very easy. This can be done by checking form's property WindowState. Here are the codes in a Timer's cycle event:

private void timer1_Tick(object sender, EventArgs e) {
if (IsWindowFormActive()) {
// set interval to max
timer1.Interval = int.MaxValue;
Cursor c = this.Cursor;
this.Cursor = Cursors.WaitCursor;

RefreshDataAndViews();

this.Cursor = c;
// save the last update timestamp to timer's tag
timer1.Tag = DateTime.Now;
// if the window is locked, min or inactive, OnPaint() will not be called.
this.Invalidate();
}
else
{
timer1.Interval = int.MaxValue;
}
}

private bool IsWindowFormActive() {
bool bRet = ( !_windowIsLocked && this.WindowState !=
FormWindowState.Minimized &&
this.Visible && this.Enabled);
return bRet;
}

When the Window Form's state is minimized, Windows is locked or the form is not visible, the timer's interval is set to the maximum number of integer. All the status checking is done within the method IsWindowsActive.

Find out If Windows is Locked

There is one class level variable _windowsIsLocked as a flag for Windows lock status. To set this flag, an event is added within the form's CTOR:

class MainForm {
private bool _windowsIsLocked;
...
// CTOR
public MainForm()
{
...
SystemEvents.SessionSwitch +=
new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
...
}
...
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
_windowIsLocked = true;
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
// cause OnPaint event called where timer is reset
_windowIsLocked = false;
}
}

Enable Timer When Application Back to Normal Running Status

When the timer's interval is set to the maximum value of integer, how to bring the timer back to the required cycle interval, such as 2 minutes(120000 milliseconds)? The trick is to overwrite form's OnPaint method.

Make sure the base method is called first. This even is the most intensively called event. Whenever the form is activated, clicked, re-sized or moved, OnPaint will be called. Therefore, it is recommended to avoid any lengthy codes in this method. For my case, what I need to do is to reset the timer's interval if the application is back to normal:

protected override void OnPaint(PaintEventArgs e)
{
try
{
base.OnPaint(e);
int interval = NORMAL_REFRESH_INTERVAL;
object timerTag = Timer1.Tag;
// check if the tag was set?
if (timerTag != null && timerTag.ToString().Length > 0)
{
DateTime dt = (DateTime)timerTag;
long ticks = DateTime.Now.Ticks - dt.Ticks;
TimeSpan ts = new TimeSpan(ticks);
// Is this time interval since last refreshing too long?
if (ts.TotalMilliseconds > 1.5 * (double)interval)
{
// secons to start the next timer cycle
interval = QUICKREFRESH_INTERVAL_AFTERAWAKE;
}
// Reset the timer's interval
Timer1.Interval = interval;
}
}
catch { }
}

There is a try and catch blocks and exceptions are ignored. I had several cases of crashes when OnPaint was introduced. Since there are not critical codes there, I just ignore any exceptions from this event.

Read More...