Tuesday, June 23, 2009

Json.NET and Its Usage (1)

Json.NET is an open source project by James Newton-King. I have used this framework in my project in the past months and I am really enjoying its simplicity and power.

I mainly use this framework to convert objects or instances to an Json string or XML string, vice visa. The framework provides many classes but I only use a very small set of them. For my purpose, what I need its classes related serialization and de-serialization. Based on my practice and experience, I wrote a wrapper class with several methods for my usages. I like to wrapper Json.NET framework is based on the following reasons:

  • To hide Json.NET from its clients or users. As a result, users will not see Json.NET or need to add reference to Json.NET. All my projects need is to reference to my wrapper class.
  • To provide a clean and simplified set of methods for my usages. This relates to the previous reason. Users will not see rich and complicated Json.NET framework.

Basicaly, I use Json.NET for the following usages:
  • Configuration file for applications; and
  • Simplify my overrides of ToString() methods for classes.


Microsoft .Net provides framework for configuration. By default, you can have configuration in XML files like app.config or web.config. The problem is that the configuration file is very restrict in sense of its structure. You have to follow its XML structure to put your settings there. The most annoying thing is that when you save some settings, whatever comments you used as reference will be gone.

I like to write configuration in any way I would like. With Json.NET, this is possible. The configuration file can be either Json string or XML string in a file. Both of them can be easily converted or mapped to an instance of a class, called as configuration class. For example, I load my XML configuration file by using TextReader class as XML string. Then I convert it a Json string. From Json string, I use Json.NET to deserialize it to an instance of my confiugration class.

In case I need to make changes of some configuration settings, I use XMLDocument and Parser classes to make changes in XML string and leave other parts not touched. Finally I save the XML string to my configuration file.

For my purpose of overriding ToString() methods, before Json.NET I had to write hard codes to format property values to a string. This is really inconvenient. If I make changes of property names, I have to remember to change my ToString(); otherwise, my ToString() is unsynched. I do need to override ToString() when I need to debug my codes into a log file. With Json.NET, I can simply to serialize instance of this to a Json string. The serialization takes care of all the properties in a nice Json style. This is really very handy!

I'll continue to discuss my wrapper class in detail in my next blog.

Read More...

Thursday, June 18, 2009

Google's aBowman

This is a very interesting gadget from Google. I was search in Google this evening. Then I was asked to sign in to Google. After I signed in, I quickly got to aBowman page.

Gadgets >> Hamster



I was using Firefox with this web page. I found this hamster. There is Get & Share section under the gadget, such as send email and blogger. I tried to send email and add to blogger, but I could not type in any words in the text area. Not sure why. Anyway, I copied the link to Safari and everything is working there. It is much faster when I am in Safari. However I could not use Vimperator in
Safari.

Read More...

Saturday, June 06, 2009

Dependency Injection and StructureMap (5)

In my preview articles, I have covered most commonly cases to describe dependency mappings. In this article, I'll conclude this series with chained registry strategy.

For many applications, there may be a lots of relationships between interfaces and implementations. You could define all those DMs in one Registry DSL library. However, I prefer to break them into several libraries and chain them together. The advantage of this strategy is to make the DM library easy to maintain and reusable.

The key in StructureMap Regisry DSL is to define a customized class based on Registry. Therefore, in each chained library, you should define your DMs in one or more Registry classes. The root library of the chain will call all the other libraries to get lists of Registry instances and add them to StructureMap framework.

For example, I have a console application, called as MyConsoleApp, which needs an implementation instance of IProcessControler. I'll create a SM library, SMForMyConsoleApp to define the DM, and it only defines the mapping relationship: how to create or map implementation class to IProcessController. The implementation class may need other implementations for other interfaces such as IDataReader, IDataProcessor and IDataWriter, but those mappings are from other chained libraries, where implementation mappings are defined.

The SMForForMyConsoleApp has two classes:

public static class SMForMyConsoleApp {
private static _registered = false;
public static void Initialize()
{
if (!_registered )
{
IEnumerable<Registry> listRegs = SMResgiry.GetRegs();
ObjectFactory.Initialize(x =>
{
// Get registry list from other Registry classes
// and add them to x
// ...

foreach (Registry reg in listRegs)
{
x.AddRegistry(reg);
}
}
}
}

public static T GetInstance<T>() where T: class
{
T instance = default(T);
if (typeof(T) == typeof(IProcessController>))
{
instance = ObjectFactory.GetInstance() as T;
}
return instance;
}
}


internal class SMRegistry: Registry {
// CTOR
public SMRegistry() {
// define the DMs
}

public static IEnumerable<Registry> GetRegs()
{
List<Registry> list = new List<Registry>();
// Add registry from other chained registry
// ...

list.Add(new SMRegistry()); // finally add this instance
return list;
}
}


The class SMForMyConsoleApp has two static methods. Initialize() is used to add all Registry instances to StructureMap framework. This method should be called in MyConsoleApp to initialize mappings. The second method GetInsance() is used to get mapped instance, for IProcessController in this example, and then start the process.

Other chained SMxxx libraries have similar structure. In this way, the console application's mapping library does not need to know the complete mapping relations. It will let sub/chain libraries to do the mapping. You can see, this is a very clean strategy with great flexibilities.

Read More...

Tuesday, June 02, 2009

Finishd iPhone classes on iTunes by Standford U

Today I finished all the 16 classes, as well as some lectures by guests on iTunes. Not sure if there are any more coming or not. Anyway, it is really good program. It does provides very clear and overall picture about iPhone development. It helps me a lot to understand Cocoa and Object-C.

With many years of .Net development experience, I have to relate some aspects to .Net C#. Cocoa and Object-C are really interesting framework and it looks very powerful. I really like their unique features.

For example, objective-C is a dynamic type language. You can add or define properties or methods dynamically and you can call on methods without worry their existence. Calling a method on nil will not cause any exception. Of course, it is controversial issue, as the instructor mentioned. No exception may bring some bugs. You expect some results but nothing happening. However, xCode and some tools are available to help to detect all those issues.

Another great feature is the delegates in Cocoa and Objective-C. They look like methods defined in an interface in .Net, but they can be optional. SEL is a great will to describe delegates and it is widely used to describe and detect their availabilities. Delegate is a way to delegate actions to objects to inject actions instead inheritance. This provides valuable flexibility to delegate class or object to take responsibilities.

Cocoa framework provides many functions, classes and controls which makes Mac and iPhone development much easy with great features. Cocoa and Object-C works well C codes. This provides much wide range of APIs and tools from open-source world, or you can build tools and libraries based on them.

I have been watching those class shows in the past weeks, one show a day during business days and two shows on weekends. Now I finished all of them. It is time to roll my sleeves up and start a new adventure in Mac & iPhone development.

Read More...

Tuesday, May 26, 2009

iPhone Dev Classes by Stanford U

In the pass week, I have been watching iPhone Application Programming classes offered by Stanford University. I read a news on AppleInsider about Free Stanford iPhone dev podcasts downloaded 1 million times. Then I started the course.

Now I have watched 9 classes, one day a class during week days and two classes one day last weekend. It is really good program. I started to learn iPhone programming last year. I got iPhone SDK 2.0. I went to Apple's Dejavascript:void(0)veloper web page on iPhone. During evenings, I have read all the SDK documents and tried to use XCode to study some example applications. All those laid great foundation for me. This makes much easy for me to understand Object-C and Cocoa. I think after completion of the course, I am ready to put my hands on iPhone applications. I am really exited about this new journey!

Read More...

Monday, May 18, 2009

Dependency Injection and StructureMap (4)

In addition to the methods of dependency mapping described in my previous blog, SM provides several other alternative methods to describe the DM.

I use two common methods to specify how instances are created. One is IsThis() and another is ConstructedBy(). The first method takes one parameter as instance and the later one takes function name as parameter. The function returns an instance. Of course, you may create an instance and pass it by the first method. However, the instance must be a none-null instance, while the second method with function may return a null as DM.

For example, if ILog's mapping to instance is a LogToFile class:

public class LogToFile {
public LogToFile(
string file,
TextWriter standardOutput,
TextWriter errorOutput) { ... }
}


In the Registry class' CTOR, the DM then is described as:

internal class SMRegistry : Registry
{
private Configuration _config;
public SMRegistry(Configuration config)
{
_config = config;
ForRequestedType<ILog>().CacheBy(InstanceScope.Hybrid).
TheDefault.Is.ConstructedBy(GetLog);
...
}
private ILog GetLog()
{
ILog instance;
TextWriter writer1 =
_config.StandardOutput ? Console.Out : null;
TextWriter writerErr =
_config.ErrorOutput ? Console.Error : null;
instance = new LogToFile(_config.logFile,
wrtier1, writer2);
return instance;
}
}

where config is an instance of Configuration class which is loaded from an XML file. The LogToFile class CTOR takes a file name as log file name, and additional two TextWriter parameters as standard output and error output. The private function GetLog() is passed to ConstructedBy() to map an instance of ILog.

The above Registry can also be coded in this way:

internal class SMRegistry : Registry
{
private Configuration _config;
public SMRegistry(Configuration config)
{
_config = config;
ForRequestedType<TextWriter>.CachedBy(InstanceScrop.Hybrid).
TheDefault.Is.ConstractedBy(GetTW()).
WithName(LogToFile.StandardOutPutName);
ForRequestedType<TextWriter>.CachedBy(InstanceScrop.Hybrid).
TheDefault.Is.IsThis(Console.Error).
WithName(LogToFile.ErrorName);
ForRequestedType<ILog>().CacheBy(InstanceScope.Hybrid).
TheDefault.Is.OfConcreteType<LogToFile>().
ConstructedBy(GetLog);
...
}

private ILog GetLog()
{
return new LogToFile(_config.LogFile,
ObjectFactory.GetNamedInstance<TextWtiter>(
LogToFile.StandardOutPutName),
ObjectFactory.GetNamedInstance<TextWtiter>(
LogToFile.ErrorName));
}

private TextWriter GetTW()
{
return
_config.StandardOutput ? Console.Out : null;
}
}

This example shows how to use IsThis() method for an instance. LogToFile.StandardOutputName and LogToFile.ErrorName are constants defined within LogToFile class.

Here you can see SM's Registry DSL provides much flexible way to describe DMs.

Read More...

Another Example of Fluent Interface

As in my previous blog posts, Fluent Interface pattern makes codes very simple and easy to read. The key point of FI is to define a class with methods returning a type of the class itself. As a result, you can continue to call its methods to manipulate data within the class. I have seen this pattern in jQuery and Dojo.

Normally, we define a class with a constructor to initialize its data members when an instance is created, and all those data members are not editable or no setters are defined. As a result, the class has its limitation only for one set of cases. If you want to define different set of data with manipulation by methods, you have to recreate objects again.

With FI pattern, here is another example to define a class to handle various data cases. Instead of passing data through CTOR, you can set data by using a method and the the return type of the class is the class itself, for example:

class MyFICalc {
private int _result;
private int _leftVal;
private int _rightVal;

public MyFICalc SetData(int val1, int val2) {
_leftVal = val1;
_rightVal = val2;
return this;
}

...
}


An instance is created by its default CTOR and data are set by the method SetData(). The method SetData() return a reference to itself. With this structure, further methods on data are defined to get expected result.

For example, I define a set of calculations:

  int  Add() {
return _leftVal + _rightVal;
}

int Subtract() {
return _leftVal - _rightVal;
}

int Multiply() {
return _leftVal * _rightVal;
}


Here are some example of uses:

int result;
MyFICalc calc = new MyFICalc();
result = calc.SetData(2, 3).Add(); // 5
result = calc.SetData(300, result).Subtract(); // 295
result = calc.SetData(result, 4).Multiply(); // 1180

Of course, this is a very simple example. In practice in one of data reading from database case, I have used FI in this manor in a loop for each row to set data and then continue to update data based on business logic. In this way, I would not need to constantly create instances. I just reuse my instance to set data and to get my result.

Read More...

Wednesday, May 13, 2009

Dependency Injection and StructureMap (3)

SM uses Fluent Interface(FI) to describe dependency mapping relationships. The FI description is to read and straightforward. You may find out various ways to describe the dependency mapping(DM) relationships. Personally, I prefer to use FI in the following format:

[For a required type].[Use a cache mechanism].[Map to a specific type]

The first part is normally for an interface type, but it can be concrete class type. The caching method is an enum type. It covers almost all the cases such new instance per request, singleton, one instance within a thread, HttpContext, HttpSession and more, see SM's documentation on Scroping and Lifecycle Management for detail information.

For the example case as described in the previous blog, here are the codes to describe ILog dependency mapping:

public class SMRegistry : Registry
{
public SMRegistry (
Configuration config)
{
ForRequestedType<ILog>().
CacheBy(StructureMap.Attributes.InstanceScope.Singleton).
TheDefault.Is.OfConcreteType<Logtofile>().
WithCtorArg(LogToFile.CtorArgFile).EqualTo(config.FileName).
WithCtorArg(LogToFile.CtorArgLogFlags).EqualTo(config.LogFlags);
...
}
}

Where config is an instance of Configuration class. This instance contains configuration (loaded from xml file) to be passed to concrete instances.

ILog interface is mapped to class LogToFile. This class CTOR takes two primitive string parameters one for file name and another as log flags. Here you can specify the primitive parameters using WithCtorArg(...).EqualTo(...) pattern. Notice that the parameter name in WithCtorArg has to be exactly as same as the one used in the CTOR and it is case-sensitive. I prefer to define a public const in CTOR's class.

I want to skip the dependency mappings for IDataReader, IDataProcessor and IDataWriter. You can image continuing to do similar mappings for them. I'll discuss how to use SM's Registry to do mappings in a structured chain manor.

Now let's look at how to define DM for IProcessControl to a concrete class in the SMRegistry' CTOR:

    ForRequestedType<IProcessController>().
CacheBy(StructureMap.Attributes.InstanceScope.Hybrid).
TheDefault.Is.OfConcreteType<ProcessController>().
WithCtorArg(ProcessContoller.CtorArgID).EqualTo(config.ID);

That's it. Recall that ProcessController's CTOR has five parameters, but only one is primitive type. Other four are instances as interface types. Those interfaces can be defined in a similar way as ILog. As a result, SM has the knowledge to inject concrete instances for those interface parameters. As I said before, you don't need to create instances in your application, you just tell SM the DMs and how. SM will inject instances for you.

If a CTOR's parameter has one concrete class parameter, you can still implement the similar way to do DM. I'll explain it later.

Read More...

Sunday, May 10, 2009

Dependency Injection and StructureMap (2)

As I mentioned in my previous blog, Registry DSL is a recommended way to configure DI mappings by StuctureMap. StructureMap introduces Registry class which is normally used as a base class for customizing DI mapping definitions.

To start up, you need to define a class with Registry class as base. In the class' constructor, what you need to do is just to define dependencies. In StructureMap terms, the dependencies are defined as mapping PluginFamilies to Plugins. PluginFamilies are normally interfaces, but they can be any classes. Plugins, on the other hand, are plug-able classes corresponding to PluginFamily interfaces or classes. Here is a simple example:

internal class SMRegistry : Registry
{
public SMRegistry()
{
ForRequestedType<IProcessController>().
CacheBy(StructureMap.Attributes.InstanceScope.Singleton).
TheDefault.Is.OfConcreteType<Processcontroller>();
}
}

As you can see, the pattern is very simple and easy to read: for a required interfase or class, specify a cache mechanism, and the mapped class. StructureMap uses Fluent Interface patten to define dependencies. The above codes map IProcessController interface to a concrete class ProcessController. This class is ready for use. As in my previous blog example, the class can be loaded as a Registry instance by ObjectFactory.Add() method.

After the loading, SM has the knowledge of how to create concrete class ProcessController for IProcessController. You would not need to worry about when and how to create the concrete instance in your application. SM and Registry takes care of when and how. Since interfaces are used in your application, the application does not aware the implementation classes and what they are. This decoupling strategy allows you to focus on business logic implementation and makes it so easy to to update implementation libraries or to plug in a different implementation class without compiling your whole application. To update or fix bugs implementation classes or libraries, only those classes or libraries need to be compiled; to plug in different implementations, only the customized Registry class or libraries need to be recompiled.

The above example is based on the assumption that the class PocessController has only one default construtor, i.e., the constructor with no parameters. How about the cases with parametrized CTOR? SM provides similar Fluent Interface APIs for you.

For example, the following codes show the ProcessController class' CTOR with several parameters, and a LogToFile class which is used as a parameter:

public class ProcessController : IProcessController
{
public ProcessController(
int id,
ILog log,
IDataReader dataReader,
IDataProcessor dataProcessor,
IDataWritter dataWriter)
{ ... }
...
}
public class LogToFile : ILog
{
public LogToFile(
string file,
string flags)
{...}
...
}

I'll show you how to use SM to define their dependencies in a Registry class in the next blog.

Read More...

Wednesday, May 06, 2009

Dependency Injection and StructureMap (1)

Recently I have been working a project with DI and StructureMap. The concept is not new but StructureMap was new for me. I did not take too long for me to understand how to use it, and soon I fall in love with SM.

The application is kine of reading data, processing data and finally writing data. The data are mostly from database such as Microsoft SQL or Oracle db. The processing part is based on business requirement. The destinations of data various from database, text files, emails or reports. There are many process in the same pattern. Then I decided to break the process into three parts as interfaces: IDataReader, IDataProcess and IDataWriter. On top of these three is the manager IProcessController. For different applications, this pattern can be repeated again and again by injecting implementation parts.

I did some research on DI framework. There are many great frameworks available, such as Spring.Net, Castle Project's Windsor Container, and Microsoft's MEF. All of them are open source frameworks. However, I find out that SM is only focused on DI and it does it very well.

I first tried it based on XML configuration. It is really straightforward. However, soon I found out that there is a better way to do it: Registry DSL(domain specific language) to make mapping between interface and class(actually it can also do for class to class). Think the Registry DSL as XML configuration, even it is done in .Net such as C#. Not only this provides a mush secure mapping, but it also provides much powerful ways to achieve DI which would be very hard to do in XML. Since the mapping is done within assembly, I think the performance should be much better than loading XML configuration files. According to SM, Registry DSL is a recommended way to configure DIs.

XML configuration files contains only PluginFamilies and Pugins logic. I also do the DI configuration in a separate assembly library project. My application can only see the interface libraries, domain class libraries, some commonly used libraries such as tools and .Net framework libraries, and the Registry DSL library:



The above is a slide show in my presentation on a demo case. ProcessDemoSM is the SM engine to load DI mappings to SM framework. ProcessDemoSM library sees all the interfaces and the libraries where implementation classes to be mapped. The application does not know the concrete classes. This makes the swap of implementations much easy and simple!

With the xxxSM project, there two basic classes, for example, SMForDemoApp (public class) and SMRegistry (based on Registry and internal class, ie, not visible to the outside of the assembly). Here is the example of SMForDemoApp class:

using StructureMap.Configuration.DSL;
public static class SMForDemoApp
{
private static bool _registered;
private static Configuration _configuration;
public static void InitializePlugins(
string configFile)
{
if (!_registered)
{
// Get configurtion information
_configuration = GetConfigInstance(configFile);
// Create Registry from this assembly
Registry registry = new SMRegistry(_configuration);
ObjectFactory.Initialize(x =>
{
x.AddRegistry(registry);
}
);
}
}

T GetInstance<T>() where T: class
{
T instance = null;
if ( typeof(T) == typeof(IProcessController) )
{
instance = ObjectFactory.GetInstance();
}
return instance;
}
}

The static class contains two private data members. _registered is straightforward. This guaranties SMRegister class is created only once. Within the class, it will load all the DI mappings to SM framework. The second one is a customize Configuration class. The class contains all the application information which are needed for instantiating implementation classes. In this example case, I store the configuration information in a file, eitehr JSON or XML file.

The interface InitializePlugins() is used to load Registry instances to SM framework. Here MSRegistry is derived from Registry class.

The method GetInstance<T>() returns an instance of generic type from SM framework. I make this method as generic so that if you need more than one types of instances, you can use this method.

The SM assembly is only referenced in this project. In my application, I don't need to add SM reference any more. I only need to add reference to this project or library. This library is like a wrapper class. It provides enough interfaces to instantiate DIs mappings to SM framework and method to get required instances back. Normally T type is by interface. A client or user does not what implementation class is mapped to. If you need to do different mapping, the only change is this library. You may think this library as SM's XML mapping file.

Here is an example in my console application, SMForDemoApp.

static main(string[] args)
{
SMForDemoApp.InitializePlugins();
IProcessController controller =
SMForDemoApp.GetInstance<IProcessController>();
controller.Start();
}

The console application is very simple. It gets an instance of IProcessControler and
calls Start() method to start process. The DI mapping is done within SMForDemoApp which relies on SM to load mapping. In the implementation class(IProcessController) uses many interface instances as well. SM will magically create instances for you, and all the instances will be injected to your implementation classes through constructor or property. You would not need to worry about how to create instances and pass instances in your implementation classes. You just concentrate on your implementation business logic.

The next thing I'll talk is about Registry class. SMRegistry class is based on SM's Registry class. In my next blog, I'll continue on the SMRegistry class.

Read More...

Wednesday, April 29, 2009

Fluent Interface Updated

This is a update on Fluent Interface patter based on my previous blog. The update is based on a much simplified interface for generic domain object.

First, I defined the following interface:

public interface IDomainObjReaderFluent<T> where T: class
{
IDomainObjFluent ReadData(int byIndex);
IDomainObjFluent ReadData(string byName);
T GetObject();
}


The interface defines two ways to read data, by index or by name. For the example of Employee class, the implementation class is:

class EmployeeReaderFluent : IDomainObjReaderFluent
{
private IDbReader _reader;
private int _id;
private string _name;
private DateTime _dob;
//...
public EmployeeReaderFluent<Employee>(IDbReader reader)
{
_id = 0;
_name = null;
_bod = DateTime.Now;
_reader = reader;
}
IDomainObjReaderFluent ReadData(int byIndex)
{
if ( byIndex == EmployeeConst.IdIndex )
{ _id = _reader.GetInt32(byIndex); }
else if ( byIndex == EmployeeConst.NameIndex )
{ _name = _reader.GetString(byIndex); }
else if ( byIndex == EmployeeConst.BODIndex )
{ _bod = _reader.GetDateTime(byIndex); }
//...
}
// ReadData(string byName) skipped ...
Employee GetObject() {
return new Employee(_id, _name, _dob, ...);
}
}


In the implementation of the interface for a domain object, the class has complete knowledge of how each field is retrieved from IDbReader or a data reader. In other words, it will be up to the implementation class to decide how to get data from the data reader. The data reader instance can be passed in through its CTOR.

Here is an example of its usage:

Employee empl = new
EmployeeReaderFluent<Employee>(myDbReader).
ReadData(EmployeeConst.IdIndex).
ReadData(EmployeeConst.NameIndex).
ReadData(EmployeeConst.BodIndex).
...
GetObject();


where myDbReader is an instance of IDbReader, and EmployeeConst is a class with only constants of index values for each field. I prefer to use const class to embedded literal constants.

Read More...

Tuesday, April 21, 2009

StructureMap and Fluent Interface

Recently I have been working a project to process data. The case is very simple. It reads data from database, process data and finally out put data to either database or text file. I have worked on the similar scenario for many cases. This time, I decided to design a generic pattern for developing similar type applications.

Based on past experience, I think I need a dependency framework for decoupling components and integrating various implementations of interfaces into a specific application. StructureMap got my attention. After about one investigation, I really like this framework. It is just for DI but very powerful. One interesting feature of this tool is its code-based registration to map DIs, which is based on Fluent Interface.

After reading the definition and examples of Fluent Interface, I really like its readability feature. Just coming up to my mind, I envision its implementation of mapping database element to domain object.

For example, the following is a domain class as Employee:

public class Employee {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public datetime BOD { get; set; }
public float Salary { get; set; }
}


My employee reader interface is based on Fluent Interface like this:

interface IEmployeeReaderFluent {
IEmployeeReaderFluent ReadID(IDataReader);
IEmployeeReaderFluent ReadFirstName(IDataReader);
IEmployeeReaderFluent ReadLastName(IDataReader);
IEmployeeReaderFluent ReadBOD(IDataReader);
IEmployeeReaderFluent ReadSalary(IDataReader);
Employee GetObject();
}


And the implementation class is defined as:

class EmployeeReaderFluent : IEmployeeReaderFluent {
private Employee = new Employee();
IEmployeeReaderFluent ReadID(IDataReader reader) {
Employee.ID = IDataReader.GetInt32(
IDataReader.GetOrdinal("ID"));
}
IEmployeeReaderFluent ReadFirstName(IDataReader reader) {
Employee.FirstName = reader.GetString(
reader.GetOrdinal("FirstName"));
}
IEmployeeReaderFluent ReadLastName(IDataReader reader) {
Employee.LastName = reader.GetString(
reader.GetOrdinal("LastName"));
}
IEmployeeReaderFluent ReadBOD(IDataReader) {
Employee.BOD = reader.GetDateTime(
reader.GetOrdinal("BOD"));
}
IEmployeeReaderFluent ReadSalary(IDataReader) {
Employee.Salary = reader.GetFloat(
reader.GetOrdinal("Salary"));
}
Employee GetObject() { return Employee; }
}


Example of the usages:

IEmployeeReaderFluent employeeReader = 
new EmployeeReaderFluent()
.ReadID(reader)
.ReadFirstName(reader)
.ReadLastName(reader)
.ReadBOD(reader)
.ReadSalary(reader);
Employee employeeObj = employeeReader.GetObject();

Read More...

Monday, April 13, 2009

Yahoo YUI Reading Blinds

Yahoo YUI Reading Blinds is a very nice browser tool based on JavaScript and YUI. Recently I tried to dig out more about this tool by looking its codes. Here are some of my findings.

First, the tool is based on a group of JavaScript codes. It is very long one like this:

javascript:var%20x=%20function(){var%20h=document.createElement('script');h.src='http://yuiblog.com/assets/readingblinds.js';h.type='text/javascript';document.getElementsByTagName('head')[0].appendChild(h)}();


This long line of codes does not have spaces. The spaces are actually specified by "%20" in codes. Then I break the codes in a nice format like this:

javascript:var x= function(){
var h=document.createElement('script');
h.src='http://yuiblog.com/assets/readingblinds.js';
h.type='text/javascript';
document.getElementsByTagName('head')[0].appendChild(h)
}();


In stead of putting this codes to toolbar, I added this tool as a new bookmark to my bookmark (I am using Vimperator and there is no toolbar visible). From the bookmark, I click on this. It works fine with reading blinds visible on top and bottom, very nice! I like this reading blinds more than others (you may find other reading blinds on web). It works well with with mouse movement and vertical scroll bar.



The only problem I had was that my Vimperator caches all the keystrokes. I could not use s, l, and b keys for smaller, larger and toggle. Vimperator blockes them to the tool. Fortunately, Vimperator has a "PASS THOUGH" mode to let all the keys passed: Control-Z.

This tool actually injects YUI JavaScript codes into the page: loading YUI scripts into <head> area. The scripts then adds top and bottom <div>s as blinds. In addition to that, it adds key and mouse event to move blinds.

I further hacker this tool to change the URL to the script src to my local Mac's Sites folder like this:

...
h.src='http://localhost/~[username]/YahooYUIReadingBlinds/readingblinds.js';
...


I added this to another bookmark as "YUI Reading Blinds Local Scripts". It works great! Since I download the readingblinds.js to my local site, I then made some changes to figure out how it works and to test its features with different settings. It was really fun to work with this tool.

The reading blinds will become darker if you click on the tool more than once. With FireBug enabled, I noticed that the scripts are injected more than once.

To get rid of this reading blinds, just refresh the web page. The original web page is reloaded and the JavaScript inject is gone.

The reading blinds does not work with https web URLs since https URL is an encrypted HTML protocol and no JavaScript injection are allowed.

This tool is a very good example to enhance web page display by using JavaScript injection!

By the way, I feel much easy to read web pages and my eyes are more relaxed with this great tool for a long period of time, especially with the browser maximized. I think this may protect screen as well.

Read More...

Friday, April 10, 2009

Code Syntax Highlight

toolsThe main reason I prefer to use Blogger than WordPress is that Blogger allows me to customize my blog layout with customized scripts and css styles in my blog template. For example, I have some blogs with source codes in C#, JavaScript, HTML, and SQL. It is very easy to include codes in a blog, by using <pre> tag. However, to highlight syntax, you need to sepcify style or to use css class style. Blogger provides this feature for free but you have to pay for this feature at WordPress.

Here are the steps I use to highlight my code syntax:

  1. Add some style to my blog HTML. This can be done through Blogger's Layout|Edit HTML. Check the Expand Widget Tempates to get the whole HTML layout settings and save it as backup before you make any changes.



    Add css classes (defined in { and } area) will be used to highlight code syntax.

  2. Generate HTML codes for my codes. I like to use some web's tools to get the job done. The tool I use is ASP.Net's forum page. I use this forum's post new topic editor to write/past my codes from its Source Code widget. The widget supports several languages which covers my areas. Those snap-shots are examples how I get my codes to HTML.

    1. Click on Source Code widget button




    2. Type in my codes




    3. Click OK to close it.

    4. Click on Edit HTML widget button




    5. Edit or copy the HTML codes



    6. Copy section HTLM codes between <pre ...> and </pre>


    Note: you may notice that ASP.NET's HTML codes contain some css classes. I added those classes to my Blogger's HTML template.

  3. In my blog entry, I paste the HTML codes to my blog. Normally I put the HTML codes between div tags. If the codes are not too long, I use the div with border. If the codes are too long, then I use a div with fixed height so that codes are within a block with scroll bar available to view codes.

    You can see those HTML tags by viewing section of codes (right click a selection of text).


There are many good tools available for syntax highlighting such as Google's syntaxhighlihter, SHJS, HIGHLIGHT.JS, and Highlight. The problem is that most of those tools are for people who have web server. I only have hosted web server like Blogger or WordPress. I cannot put any of my codes and css style files to the server. Blogger provides a way to embed css styles, but I would not want too many css definition codes there. It is just hard for me to maintain.

That's why I like to use ASP.NET's tool to get HTML codes with classes. Another great advantage of ASP.NET's widget is that it will be able to convert some special HTML codes such as > and <.

Read More...

Saturday, April 04, 2009

SQLite Manager Add-on for Fixfox

toolsI found a very handy tool: SQLite Manager an add-on for FireFox. I have been using another application called as SQLite Database Browser in my Mac for my SQLite databases. FireFox add-on actually is much better than the application, at least from the UI.

For example, the UI provides Database Settings for database generic settings and UIs for Views, Indexes and Triggers. The table UI layout is also much better than SQLite Browser.



I have not tried this one in Windows yet. I think it should work without any problem.

Read More...

Sunday, March 29, 2009

Dojo Chart Library

I read an article about Dojo Now With Chart Tools by Mattew Russell, the author of the book Dojo The Definitive Guide by O'Reilly.

The article lists several demos on generating charting by Dojox.charting library. I then started to copy the codes to an HTML file. Instead of loading Dojo libraries to my local computer even I have a personal web site on my Mac, I used xDomain reference to Google's Dojo CDN library. In this way, I don't need any web server and I can send this demo HTML to my colleagues to share it. My colleagues at my work really enjoyed it.

This demo does not only lists original JS codes. I enhanced the charts with different CSS styles and colors. It is so easy to do that. In addition to that, I allocate an 600x600 area at top as an area for chart and list my demos a UL list underneath it. This arrangement needs to clean the area for any chart previously displayed. The Dodo library does not provide APIs to clean chart. I finally found a way to clean it: simply removing all the childen nodes in the area. Even this one works, but it is not recommended. An Dojo insider pointed out this method does not clean all the objects created for the chart. I posted my question to StackOverflow and Dojo's forum.

My previous blog also mentioned the issue about xDomain reference. All these were really challenges for me since I am new in Dojo. I have not done much development in Dojo. However, the demo and enhancements let me learn a lots.

Here is my demo on Google's Code.

Read More...

Saturday, March 28, 2009

FireBug and xDomain Reference for JS APIs

Last week I read a very interesting article on Dojo's charting library. There are some demo codes in the web page. Instead of downloading Dojo's library to my local computer web site, I choose to use CDN fashion to load Dojo library from Google's CDN. This method is called Cross Domain Resource Reference or xDomain Reference.

In this way, I don't even need a web server. I just use VI to write an HTML file with JavaScript and Dojo API calls. That's the basic of web application: HTML + JS. I dropped the HTML file to my browser (FireFox) and it worked right away.

However, for the same codes which I found them in Dojo's ToolKit web page, one of feature does not work. It is the animation of curve chart. This feature is added by calling Magnify() API function to the chart. Behind sense, animation parts are created to each point. In the Dojo's web page, the magnification works fine but not in my HTML.

I spent about one day's time finally I figured it out. What I missed is to add the following codes to the head section of HMLT:

<head>
...
<script type="text/javascript">
...
dojo.require("dojo.fx");
...
</script>
</head>


FirBug helped me to find this one out. When I checked my HTML source codes in FirBug, the script loading section shows the loaded source codes in FireBug window. However, for the xDomain reference HTML page, the source codes are partially and they are displayed as one very very long line like this:


As you can see how hard to read when I copied the codes to VI:



Fortunately, the same codes are available on DojoToolKit web page, where Dojo's library files are not xDomain references. They are in the same domain. By using FireBug to take a peek inside the web page, I found the Magnify.js source codes are in nice layout:



By the way, I also tried to get source codes directly from Google's CDN web site, for example, Dojo.xd.js. It also displayed as a very very long line. But I went to DojoToolKit's web page to load the source code from their domain, I was prompt to save or open js. The download js file is in nice layout format. Here it reveals that CDN is not only for fast downloading, the size of the file is also very small. All the unnecessary codes such as line breaks are removed!

Read More...

Sunday, March 22, 2009

Using CTE in TSQL

Last week I found CTE (Common Table Expressions) when I posted a question to StackOverflow. CTE is an ANSI SQL-99 standard and it was added to Microsoft SQL Server 2005.

For me, it was new. I applied answers to my TSQL codes and then I really like it. It is so simple and readable. With its recursive power, I resolved my issue in a couple lines of codes. Today I further googled out more information about this and here are some links with good view of CTE:


Another example I tried was to replace T-SQL cursors by using both CTE and a table variable:
DECLARE @row INT;
DECLARE @rowMax INT;
DECLARE @myTable (
id INT IDENTITY(1,1) -- key with auto creament
name VARCHAR(100),
dt DATETIME );
-- Using CTE to select data into @myTable
WITH CTE_Temp(name, dt) AS
(
-- SELECT to hold a temp set of data
SELECT tagName as name, dt FROM myTagTable
WHERE version = 0;
)
INSERT INTO @myTable (name, dt) -- Insert to @myTable
SELECT name, dt FROM CTE_Temp;
SELECT @row = MIN(id), @rowMax = MAX(id)
FROM @myTable;
WHILE (@row <= @rowMax)
BEGIN
-- do someting about data in @myTable
SET @row = @row + 1; -- move to next row
END

Of course, this can be done with SELECT INTO FROM statement. This is just an example to use CTE to hold a section of data from a base table.

The power of CTE is its unique feature: recursiion. Within the WITH block, you can define two basic queries: base or anchor query and recursive query. Here is an example of Split like function to split a string by delimiter into a table as return:
CREATE FUNCTION [dbo].[udf_Split]
(
-- Add the parameters for the function here
@p_StringList NVARCHAR(4000),
@p_Delimiter NVARCHAR(512) = ';'
)
-- Return table definition
RETURNS @Results TABLE (
position int NOT NULL,
item NVARCHAR(MAX)
)AS
BEGIN

-- Use WITH statement with recursive power
WITH Pieces(pn, start, stop) AS
(
-- start from 1, 1, stop(=CHARINDX())
SELECT 1, 1, CHARINDEX(@p_Delimiter, @p_StringList)
UNION ALL
-- next to update pn, start and stop values
-- by recursive call

SELECT
pn + 1,
stop + 1,
CHARINDEX(@p_Delimiter, @p_StringList, stop + 1)
FROM Pieces
WHERE stop IS NOT NULL AND stop > 0
)
-- Test the result
-- SELECT * FROM Pieces;

INSERT INTO @Results
SELECT
pn, -- as position
SUBSTRING(@p_StringList, start,
CASE WHEN stop IS NOT NULL AND stop > 0
THEN stop-start
ELSE LEN(@p_StringList) END)
AS s -- as item by using SUBSTRING() function to get sub string from Pieces
FROM Pieces;

RETURN;
END

Read More...

Saturday, March 14, 2009

Use sp_who2() to Get Current Log-in User Information

Recently I have been working on Microsoft SQL Server 2005 to resolve some security issues. One question was to get the current log in user information.

As usual, when I cannot find an answer in 10 minutes, I post my request to StackOverFlow web site. I posted my question early in a morning before I went to my work. Quickly I got several answers when I arrived to my office by biking. I tried all of them and found out sp_who2, a undocumented stored procedure by Microsoft SQL Server, is the tool to get information I need. By using this tool, actually I can find out who is using the SQL server anytime. For example, if a critical data refreshing or migration job is scheduled, I could add this tool to find out if there is any user access to SQL server and send out warning emails if any one there, before the job is about executing.

It is very easy to user SP:

EXEC sp_who2;

The SP returns a list of log in users in a table view if you use Microsoft SQL Server Management Studio's query. However, I only want to see related column information and filter users by WHERE and ORDER BY clauses. Then I found out a way to define a table and output the result to a variable table like this:
DECLARE @retTable TABLE (
SPID int not null
, Status varchar (255) not null
, Login varchar (255) not null
, HostName varchar (255) not null
, BlkBy varchar(10) not null
, DBName varchar (255) null
, Command varchar (255) not null
, CPUTime int not null
, DiskIO int not null
, LastBatch varchar (255) not null
, ProgramName varchar (255) null
, SPID2 int not null
, REQUESTID INT
)
INSERT INTO @retTable EXEC sp_who2
SELECT Status, Login, HostName, DBName, Command,
CPUTime, ProgramName, BlkBy AS [Last CMD Time] -- *
FROM @retTable
--WHERE Login not like 'sa%' -- if not intereted in sa
ORDER BY Login, HostName;

To view all the user information, you need to login as sa or user with sa administrative privileges. Otherwise, you may only see yourself or limited information.

Read More...

Thursday, March 05, 2009

Using EXEC() AT Continued

My previous blogs on this topic demonstrate a way to use EXEC(...) AT ... to pass through a query to a linked server. The performance of this method is much better than a T-SQL query directly with the linked server. I tried it with an very big Oracle database table with great speed.

Today, I found another very interest issue with this pass-through query method. If the execution on the remote server has any error such conflict with constrains or wrong field name, the execution does not stop. The errors will be thrown at the end of execution. For example, the following codes will be executed completely:

DECLARE @sql NVARCHAR(MAX);
DECLARE @myCount INT;
-- Initialize setting
SET @myCount = -1; -- Initailize it
-- Build sql query

SET @sql = N'
BEGIN
SELECT COUNT(*) INTO :myCount
FROM owner.myTable
WHERE id1 = '
+ CAST(@id AS VARCHAR) + N';
END;'
;
-- id1 is an incorrect field name
EXEC (@sql, @myCount OUTPUT) AT linedOracleServer;
PRINT 'Count: ' + CAST(@myCount AS VARCHAR);
-- Prints Count: -1 Not stopped!


I tried similar codes with T-SQL directly using the lined server:
DECLARE @myCount INT;
-- Initialize setting
SET @myCount = NULL;
-- Use T_SQL query
SELECT @myCount = COUNT(*)
FROM linkedOracleServer.owner.myTable
WHERE id1 = 1;
-- NO prints, syntax error right away!
PRINT 'Count: ' + CAST(@myCount AS VARCHAR);


I found this interesting problem when I run a stored procedure with EXEC() AT to update value on Oracle side. It runs fine but today I found one error at the end of execution. The SP did not stop. Finally I figured out there were several violations of constraints. Since the whole stored procedure was completed and no exception to stop the program, the continuous codes set flags to mark insertion successful in another log table.

I tried to run a test scheduled job with this problem SP. The job log does indicate exception and step failure. However, the SP was executed completed.

EXEC() AT is a good way to leverage a remote server's full power; however, you have to be very careful about the process. Test your codes thoroughly before putting it into production. Another way may be to schedule a job to run the codes. If there is any failure, rollback any changes.

Read More...