h1

C# Singleton for Facade Pattern

August 7, 2011

While researching the facade pattern that can be implemented in similar way to HttpContext (in ASP.net), I came to a MSDN article that talks about implementing the singleton pattern in C#. It is fairly straight forward and works extremely well for what I needed for the project.

Here is the context class, which exposees the CMSManager (a factory class). The context manages the instantiation and destruction of the facade:

public sealed partial class CMSContext
{
	/// <summary>
	/// clutch object is used to prevent multiple access during the initialization
	/// </summary>
	private static object clutch = new object();
	/// <summary>
	/// actual instance of the CMSContext object
	/// </summary>
	private static volatile CMSContext uniqueInstance;

	/// <summary>
	/// instance of the CMSManager
	/// </summary>
	private CMSManager _cmsFacade = null;

	/// <summary>
	/// Gets the CMS facade.
	/// </summary>
	public CMSManager CMSFacade
	{
		get
		{
			return _cmsFacade;
		}
	}

	/// <summary>
	/// Prevents a default instance of the <see cref="CMSContext"/> class from being created.
	/// </summary>
	private CMSContext()
	{
		_cmsFacade = new CMSManager();
	}

	/// <summary>
	/// Gets the instance.
	/// </summary>
	public static CMSContext Instance
	{
		get
		{
			if (uniqueInstance == null)
			{
				lock (clutch)
				{
					if (uniqueInstance == null)
						uniqueInstance = new CMSContext();
				}
			}
			return uniqueInstance;
		}
	}

	/// <summary>
	/// Releases unmanaged resources and performs other cleanup operations before the
	/// <see cref="CMSContext"/> is reclaimed by garbage collection.
	/// </summary>
	~CMSContext()
	{
		if (_cmsFacade != null) _cmsFacade.Dispose();
	}

}


This context class simplifies the way my client application accesses the CMS subsystem. It only requires two lines of code to access the factory class.

CMSContext cms = CMSContext.Instance;

ContentFile f = new ContentFile();
f.FileName = "Test.txt";
f.FileSize = 10;
f.LastModified = DateTime.Now;

cms.CMSFacade.SaveContent(f);

One important note to achieve this simplicity, both context class and factory class should be autonomous; if there is any external dependency, it can make the client code messy.

h1

Getting the MAC and IP address in .net

March 27, 2011

It took me forever to find this information and the solution was extremely simple. The System.Net.NetworkInformation namespace provides network card information.

static void Main(string[] args)
{
  NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces().Where(a=> a.OperationalStatus.Equals( OperationalStatus.Up)).FirstOrDefault();
  string macAddress = networkInterface.GetPhysicalAddress().ToString();
  string clientIp = networkInterface.GetIPProperties().UnicastAddresses[0].Address.ToString();
}

h1

WCF REST 4 anonymous output

December 26, 2010

Using RESTful service is definitely the way to go. It’s practical and easier to consume. I always opt for simplicity when choosing a design approach and WCF REST template is definitely the hammer in my toolbox.

However, I came to a problem when trying to expose anonymous object as output. I would get a runtime “Request Error” whenever using object as the return type.

BACKGROUND: WCF requires strong return type which creates unnecessary complexity. It doesn’t make sense to create a return type for each of my WCF REST methods. I would rather go back to SOAP the old way. Beside WCF, I’ve always been creating REST service just using ASP.net which, in my view, is extremely easy. After a day of digging around the Google search, I found only bits and pieces of information. Then I came across System.ServiceModel.Channels.Message type which gave me an idea to create a string output inside the Message. It gives me the freedom to manipulate the output however I want.

So here are the steps to setup the project. First download the WCF REST Service template using the Extension Manager in Visual Studio 2010

Extension Manager

Just install the template provided by Microsoft

WCF REST 4 template

Create new project using the new template “WCF REST Service Application”. The template pretty much setup everything and it should give you the Hello World sample output when running it. The new template should be listed under Visual C# category. (you will notice the template is quite different from the WCF Service Application; in most of my works, I can do away with interface definitions; this makes it easier to read the codes without flipping between two different cs files)

Follow these steps to create a method to return a Message type that contains the anonymous object.

Add the following references in the Service1.cs file


using System.ServiceModel.Channels;
using System.Net;
using System.Web.Script.Serialization;

Add a new method called JSON_Anonymous()


[WebGet(UriTemplate = "/JSON")]
public Message JSON_Anonymous()
{
  WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.ContentType] = "application/json";
  var ret = new
  {
    Name = "John Doe"
    ,Title = "SVP Sales and Marketing"
  };

  return WebOperationContext.Current.CreateTextResponse(ret.ToJSON());
}

I added a ToJSON extension method to the cs file as well, to help simplify my code. ToJSON Original source was from Scott Gu’s blog


public static class JSONHelper
{
  public static string ToJSON(this object obj)
  {
    JavaScriptSerializer jss = new JavaScriptSerializer();
    return jss.Serialize(obj);
  }
}

Go ahead run the program and download the JSON output

WCF REST anonymous JSON output

The output should look like this

{
    "Name": "John Doe",
    "Title": "SVP Sales and Marketing"
}

h1

IsNumeric() function

December 2, 2010

A simple IsNumeric() function to validate numeric variables in javascript

    function IsNumeric(input)
    {
        input = input + "";
        return (input/1) == input && input.length > 0;
    }

h1

Decoding Numara Footprints special characters

November 24, 2010

My client wants to query and run report against the Footprints database, which is a Microsoft SQL server. It was simple enough until we noticed the data have some kind of encoding, a blank space will appear to be “__b”. This applies to all the records and fields. After contacting the support, I was given a list of all the encoding values.

To be able to decode the data in a query, I built an user-defined function to simplify the conversion for me. A quick and dirty solution. :)

Note: the collate clause tells the SQL server to compare string in case-sensitive manner.


CREATE function [dbo].[udf_decodeFootprintsStringValue] (@pFootprintValue varchar(2000)) 
returns varchar(2000)
as
	begin
		declare @pMappedValue varchar(2000)
		set @pMappedValue = replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(
							replace(@pFootprintValue COLLATE SQL_Latin1_General_CP1_CS_AS
								, '__' + char(66), '!')  --B
								, '__' + char(98), ' ')  --b
								, '__' + char(65), '+')  --A
								, '__f', '/')
								, '__' + char(117), '-') --u
								, '__4', '$')
								, '__' + char(71), '<')  --G
								, '__a', '''')
								, '__5', '%')
								, '__' + char(113), '"') --q
								, '__6', '^')
								, '__' + char(87), '{')  --W
								, '__t', '`')
								, '__7', '%')
								, '__' + char(119), '}') --w
								, '__' + char(109), '@') --m
								, '__8', '*')
								, '__' + char(67), '=')  --C
								, '__' + char(100), '.') --d
								, '__0', '~')
								, '__I', '|')
								, '__s', ';')
								, '__' + char(70), '\')  --F
								, '__' + char(77), ',')  --M
								, '__' + char(99), ':')  --c
								, '__' + char(81), '?')  --Q
								, '__' + char(112), ')') --p
								, '__' + char(101), ']') --e
								, '__' + char(80), '(')  --P
								, '__' + char(69), '[')  --E
								, '__3', '#')
								, '__' + char(103), '>') --g


		return @pMappedValue
	end


h1

Capture SOAP Envelope using ASP.net

November 23, 2010

I wanted to use the jQuery to post a 3rd party webservice call. First step is to understand the SOAP envelope. With soapUI, I was able to construct the SOAP envelope from the WSDL. However, the API involves complexType with objects inside nested arrays. The base envelope was not useful to me.

Since I’m not familiar with constructing complexType xml from scratch, I have to find an easy way to build the xml. The best route is to trace the exact SOAP call from my other .net application. So i built a simple ASP web application to capture the service call.

In the code behind, the ASP writes the data from Request.InputStream into a local file.

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (string o in Request.Params)
        {
            Response.Write(o + " : <span style='color:#a3a3a3'>" 
                 + Request[o] 
                 + "</span><br/>" 
                 + System.Environment.NewLine);
        }
        Stream file = File.OpenWrite(Server.MapPath("RequestStream.txt"));
        CopyStream(Request.InputStream, file);
        file.Flush(); 
        file.Close();

    }
}

found this code snippet to write stream data into a file


    public void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    } 

By changing the URL (to the url of this ASP site) on my other .net application, I was able to capture the content of the SOAP envelope.

h1

SQL Calendar table

November 22, 2010

The InsertCalendar procedure is written in a way that i can repopulate/ refresh an existing calendar table. Much of the logic was originally taken from this link

 


CREATE TABLE [dbo].[CORP_Calendar](
       [date] [datetime] NULL,
       [day of year] [int] NULL,
       [day] [nvarchar](30) NULL,
       [day of week] [int] NULL,
       [day of month] [int] NULL,
       [week] [int] NULL,
       [month] [int] NULL,
       [monthName] [nvarchar](30) NULL,
       [quarter] [int] NULL,
       [year] [int] NULL,
       [weekby7days] [varchar](7) NULL
)



ALTER Proc [dbo].[InsertCalendar]
as
/*
 * code from internet http://consultingblogs.emc.com/jamespipe/archive/2007/04/24/T_2D00_SQL-Calendar-table.aspx
 * to generate calendar table
 */
SET NOCOUNT ON

declare @start datetime, @end datetime
declare @no_of_Days bigint

set @start = '2000-01-01'
set @end = '2020-01-01'

set @no_of_days = datediff(dd,@start,@end) + 1

set rowcount @no_of_days
select identity(bigint,0,1) as dy 
into #temp 
from syscolumns a, syscolumns b
set rowcount 0

drop INDEX IX_CORP_Calendar on dbo.CORP_Calendar 

Truncate table dbo.CORP_Calendar
INSERT dbo.CORP_Calendar
select dateadd(dd,dy,@start) as [date] 
    ,datepart(dy, dateadd(dd,dy,@start)) [day of year]
    ,datename(dw, dateadd(dd,dy,@start)) [day]
    ,datepart(dw, dateadd(dd,dy,@start)-1) [day of week]
    ,datepart(dd, dateadd(dd,dy,@start)) [day of month]
    ,datepart(ww, dateadd(dd,dy,@start)) [week]
    ,datepart(mm, dateadd(dd,dy,@start)) [month]
    ,datename(mm, dateadd(dd,dy,@start)) [monthName]
    ,datepart(qq, dateadd(dd,dy,@start)) [quarter]
    ,datepart(yy, dateadd(dd,dy,@start)) [year]
       ,null as [weekby7days]
from #temp
drop table #temp

Create clustered INDEX IX_CORP_Calendar on dbo.CORP_Calendar ([Date])

update dbo.CORP_Calendar
set weekby7days = dbo.udf_GetWeek (date)

SET NOCOUNT OFF



 

 

CREATE TABLE [dbo].[CORP_Hour](
       [MilitaryHour] [int] NOT NULL,
       [Hour] [int] NOT NULL,
       [AMPM] [varchar](2) NOT NULL,
 CONSTRAINT [PK_CORP_Hour] PRIMARY KEY CLUSTERED 
(
       [MilitaryHour] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
)


MilitaryHour Hour AMPM
0 12 AM
1 1 AM
2 2 AM
3 3 AM
4 4 AM
5 5 AM
6 6 AM
7 7 AM
8 8 AM
9 9 AM
10 10 AM
11 11 AM
12 12 PM
13 1 PM
14 2 PM
15 3 PM
16 4 PM
17 5 PM
18 6 PM
19 7 PM
20 8 PM
21 9 PM
22 10 PM
23 11 PM

h1

Render DataTable as HTML Table

November 18, 2010

This is a fairly simple c# function to convert any DataTable into HTML table. This function works perfectly well with iqy file feeding tabular data into Excel.

    public static string ConvertDataTable2HTMLString(DataTable dt)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<html><body><table><thead><tr>");
        foreach (DataColumn c in dt.Columns)
        {
            sb.AppendFormat("<th>{0}</th>", c.ColumnName);
        }
        sb.AppendLine("</tr></thead><tbody>");
        foreach (DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            foreach (object o in dr.ItemArray)
            {
                sb.AppendFormat("<td>{0}</td>", Server.HtmlEncode(o.ToString()));
            }
            sb.AppendLine("</tr>");
        }
        sb.AppendLine("</tbody></table></body></html>");
        return sb.ToString();
    }

 

Here’s the sample iqy Excel file to query data that are in HTML table format

WEB
1
http://url/PATH/script.aspx

h1

c# extensions

March 21, 2010

c# Example found on the net, demonstrated how Dot Net 3 extensions are declared and consumed.

namespace myExtensionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] values = { 5, 6, 10 };

            bool isInArray = 7.In(values);

            string[] s_vals = { "5", "6", "10" };
            bool isInStringArray = "10".In(s_vals);

            string s = "Hello Extension Methods";
            int i = s.WordCount();
        }
    }

    //define extension methods within a static class
    public static class myExtensions
    {
        //'this' parameter is usually used on object where the method is applied to
        public static int WordCount(this string str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
        }
        public static bool In(this T o, IEnumerable items)
        {
            foreach (T item in items)
            {
                if (item.Equals(o))
                    return true;
            }
            return false;
        }
    }
}

Original materials from http://msdn.microsoft.com/en-us/library/bb383977.aspx

h1

Objective-C link to website

August 4, 2008

[[UIApplication sharedApplication] openURL:[[NSURL alloc] initWithString: @”http://www.mywebsite.com/”]];

Follow

Get every new post delivered to your Inbox.