Fun to learn Design Patterns

I am reading this Head First Design Patterns and couldn’t help smiling and be astonished all the way when reading. It’s much interesting than I expected. I highly recommand every pattern fan to add this to your reading list.

I really like the Q&A part and those graphic insets. The chapter I am currently on is Abstract Factory and Factory Mathod Pattern. I heard they are different but never found any good and easier article to explain it to me.

Not so sure about the simpleFactory pattern the author joked, what’s the difference between it and repository(?) pattern.

Still reading……

About these ads

jQuery releases Javascript pain

I have a html page to display xml files from the same server. The reasons I didn’t use the server side script includes

  1. ruby needs rails, but I don’t want to create an application for this single page. I tried to run ruby as cgi, no success.
  2. maggiePie can make php eaiser, but I think it’s still kind of overkill for this simple use.

Then I turned to client-side javascript. At first I use this function to load xml file:

function loadXMLtoDIV(file, div_name) {

var xmlDoc = null;

var moz = (typeof document.implementation != ‘undefined’)
&& (typeof document.implementation.createDocument != ‘undefined’);
var ie = (typeof window.ActiveXObject != ‘undefined’);

if (moz) {

xmlDoc = document.implementation.createDocument(“”, “”, null);
xmlDoc.load(file);
xmlDoc.onload = function() { readXML(xmlDoc, div_name); };

} else if (ie) {

xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
xmlDoc.load(file);
readXML(xmlDoc, div_name);
}

}

It worked very well, and I like it until I tried use jQuery:

function XmlOnLoad( xmlData, divId ){

// Get the first 2 items
var jItems = jQuery(‘item:lt(2)’, xmlData);

var jDiv = $( divId );

// reset.
jDiv.html(”);

jItems.each(
function( ){
jDiv.append( $(this).find(‘pubDate’).text() + ‘ : ‘ +$(this).find(‘title’).eq(0).text() +’<br/>’);
}
);
}
function GetXMLData(file, divId){
$.get(file,{},
function(xmlData, status) {
XmlOnLoad(xmlData, divId);
} );

}

And another benefit from jQuery is, I can move those ‘behavior’ from the presentation part. This jQuery ‘onload’ function is to add an universal click event to all the itemlist class div. By doing this my html elements look much neater.

$(function(){

$(“div.itemlist”).each(

function(n){
var current = this;

$(“<a href=”>See latest items … </a>”).click(  function(event){
GetXMLData(   “#”+current.id); return false;}  ).appendTo($(this));
}
);

})

One thing I still don’t understand, if I tried to load too many xml file into the page elements, some xml files just missed. jQuery still doesn’t fix this problem. But coverting from loading to ajax using jQuery is so easy, so I didn’t spent too much time on it at all.

For those TDD fans, you want to look in this QUnit intro.

An IDE for Ruby: RadRails from aptana

Just tried this IDE for Ruby, I was having problem to install the plugin into Eclipse 3.2, then switched to new 3.4, everything works OK.

I have no experience on NetBeans, but some people said RaDRails is quicker, intelligent and easy to use. This the intelligence I got. But I tried to use it as an online help, it seems not all the methods can pop-up after the dot.

Later I realize I can use the build-in  “Ruby Interactive (RI)” or “Ruby Core API” view.

Comparison between RadRails and Netbeans.

Here is a poll showing RadRails is 3 times popular than NetBeans.

New vs. Override

A very good one to explain the difference between New and Override.

My feeling is, ‘New’ acts like a partial override, or not very stable override. In another word, it will call the base method under some circumstance you didn’t expect.

One typical example is, as shown in the post I linked in the beginning of this post, when you try to do the casting back to base class, the one in your ‘New’ method will completely back to the hidden one, while the override never do.

I will post more when I found more about this.

Add new item into array

A very simple request, I was surprised how hard csharp implemented it. At first I thought it should be as easy as this:

string[] myList = {“1″, “2″, “3″};
string[] newList = myList.Add(“4″);

But it turns out Array doesn’t have an Add() method. OK, my stupid way, copying…

string[] newList = new string[myList.Length + 1];
Array.Copy(myList, newList, myList.Length);
newList[myList.Length] = “4″;

I feelvery shameful to write those code out. Re-try conversion to ArrayList, I feel much better when I figured out the ArrayList constructor and Initialize block.

ArrayList newArrayList = new ArrayList(myList) {“4″};
string[] newList = newArrayList.ToArray(typeof(string)) as string[];

And, how about using string join?

string[] myList = {“1″, “2″, “3″};
string[] newList = {string.Join(“,”, myList), “4″);

Create multiple criteria to mock DataAcess in CSLABO

I posted before about using TypeMock to do mock data access in CSLABO. Today I am posting another way to mock dataaccess without using TypeMock.

First, I need to create IRepository<DTO> interface:

public interface IRepository<DTO>
{
DTO FindById(int id);
DTO Insert(DTO data);
void Update(DTO newData, DTO oldData);
void Delete(DTO data);
void DeleteById(int id);

Second, create my OrganizationRepository by implementing this IRepository<OrgarnizationDTO>.

Third, in my BO, add those 2 fetch methods:

private void DataPortal_Fetch(SingleCriteria<OrganizationBO, int> criteria)
{
DataPortal_Fetch(new RepositoryCriteria<OrganizationDTO>(new OrganizationRepository(), criteria));
}

private void DataPortal_Fetch(RepositoryCriteria<OrganizationDTO> repositoryCriteria)
{
var data = repositoryCriteria.Repository.FindById(
((SingleCriteria<OrganizationBO, int>)repositoryCriteria.Criteria).Value );

if (data != OrganizationDTO.NULL)
{
LoadFromDTO(data);
}
}

public class RepositoryCriteria<DTO>
{
public IRepository<DTO> Repository;
public CriteriaBase Criteria;

public RepositoryCriteria(IRepository<DTO> repository, CriteriaBase criteria)
{
Criteria = criteria;
Repository = repository;
}
}

Finally, The test code:

[Test]
public void CanFetchFromMoQRepository()
{
var mockRepository = new Moq.Mock<IRepository<OrganizationDTO>>();

// Id in MoQ matters. TypeMock doesn’t.
mockRepository.Expect(x => x.FindById(8172)).Returns(
new OrganizationDTO
{
Id = 1,
Name = “A test org name”
});

var o = DataPortal.Fetch<OrganizationBO>(
new RepositoryCriteria<OrganizationDTO>(
mockRepository.Object,
new SingleCriteria<OrganizationBO, int>(8172)
)
);

Assert.AreEqual(1, o.Id);
Assert.AreEqual(“A test org name”, o.Name);
}

The benefit of this solution is we are a little bit close to loose coupling, but later I figured out it’s still very hard to mock the Save() method. Had to back to TypeMock.

LinQ to SQL takes dynamic cretira

I am building a search window to enable user passing dynamic search expression to back end. The old way on those direct connect to database was kind of easy, just need to organize dynamic sql. What about ORM?

In NHibernate we can build criterion then pass to session to do GetByCriteria, I could not find the similar way in Linq to Sql until Dynamic Linq extension appeared on Scott Guthrie’s blog. It just is the one I want!

Scott did mention another choice about predicate builder, I think this is more about merge search result from linq2sql, say you have a lot of ‘Or’ logic in your search query.

I still have a minor problem, how can I let my UI know the column name? Current my BO’s property has no underscore, but the column name in database does. I’ve already used the ‘friendly name’ in Iproperty object by exposing the FieldManager.GetRegisteredProperties().

Do I need to declare another set of column name in my BO somewhere? Or do a mapping in my repository object before the actual linq query? After some time wasting, I decided to re-use this ‘friendly name’, with the under score in the property, those property still look very friendly.

There is a nice tutorial for DynamicQuery, notice how it do the lambda expression in join expression. Here is my result:


        public IEnumerable FindAllByCriteria(string criteria)
        {
            var dbx = DataContextFactory.GetDataContext();

            var dataSet = dbx.Organization_UVs.Where(criteria)
                // This relationship is done by dbml, it's not necessary here. Actually, this will create another join in query.
                //                .Join(dbx.Stakeholder_UVs, a=>a.Stakeholder_ID, b=>b.Stakeholder_ID, (a,b)=>a)
                .Join(dbx.Stakeholder_Name_UVs.Where(n=>n.Legal=="Yes"),
                    data => data.Stakeholder_ID,
                    nameData => nameData.Stakeholder_ID,
                    (data, nameData) => new OrganizationDTO
                            {
                                StakeholderId = data.Stakeholder_ID,
                                IncorporationNumber = data.Incorporation_Number,
                                OrganizationTypeCd = data.Organization_Type_CD,
                                OrganizationStatus = data.Organization_Status,
                                NumberOfMembers = data.Number_of_Members,
                                InitialIncorporationDate = data.Initial_Incorporation_Date,
                                IncorporationStatusDate = data.Incorporation_Status_Date,
                                ParticularsCertifiedDate = data.Particulars_Certified_Date,

                                // base data from stakeholder
                                Expired = data.Stakeholder_UV.Expired,
                                StakeholderType = data.Stakeholder_UV.Stakeholder_Type,
                                LastApprovalDate = data.Stakeholder_UV.Last_Approval_Date,

                                // Name
                                StakeholderNameId = nameData.Stakeholder_Name_ID,
                                Name = nameData.Last_Name,
                            }
                )
             ;

            foreach (OrganizationDTO data in dataSet)
            {
                yield return data;
            }

        }

Looking for Cookie, ForceClick?

I created a podcast which needs get file from an internet network drive provider. I found a good post explaining how to cheat this provider by passing WGet using a cookie option. But I was having a hard time to get this cookie from that site. I tried all kind of different options in wget, and curl, neither one works.

Last night, when I was doing the normal hunting for cookie, I realized this cookie is not generated by post-form or get-request, instead it’s generated by my clicking on the actual link. Javascript!?

Finally, I found that cookie is hidden in the page, as an setkey javascript function. Gee, what a high technology they are using to force user clicking the link when downloading.

During this procedure, I learned some very useful tips,

  1. An great add-on to firefox, Live Http header
  2. WGet, Curl advance options, to save cookie, save header, debug output, print server responce etc.

I also damaged my old Toshiba 4220 laptop by accident during this hunting. This old machine used to be my primary ruby and php coding workstation, but now with pcmcia slot broken, it’s too old to do any developing work any more, hunting for next one.