May 28, 2010

Define entity from "view"

When you have Entity that mapping to more than one table in a database. You probably have options to do the mapping.

The first option is defined import all the tables into the StorageModels, but not ConceptualModels, define you entity without mapping, then manually edit the edmx file and to define the mapping. Because the entity mapping is manual, you need to define the CRUD manually. You can use store proc to do that.

<EntitySetMapping Name="DummyExes">
              select value EFTestModel.DummyEx(p.Id, p.c1, p.c2, c.c3)
              from EFTestModelStoreContainer.Dummy as p
              left join EFTestModelStoreContainer.DummyEx as c
              on p.Id = c.DummyId

The second option is defined a view in database, import that view and mapping to your entity. Because database view are normally treated readonly, you can define CRUD operation using stored proc, just like QueryView. Or you edit edmx file, cheat the ef runtime to think the view as talbe, then define insteadof trigger to do the update.

May 25, 2010

supporting state management for poco object in object context

var entry = context.ObjectStateManager.GetObjectStateEntry(poco);

For the Entity Framework to create the change-tracking proxies for your POCO classes, the following conditions must be met,

1. The class must be public, non-abstract, and non-sealed.

2. The class must implement virtual getters and setters for all properties that are

3. You must declare collection-based relationships navigation properties as
ICollection<T>. They cannot be a concrete implementation or another interface
that derives from ICollection<T>.

May 19, 2010

Functional aspect of c#

Two generic delegate in c#, makes c# look more like a functional language, they are Action<T>, Func<T1, T2, ...>. The functional feature let you easily express your algorithm, without using the traditional design pattern. These delegates can be compared with function in javascript, and lamda in other language. For example,

interface IStrategy
   void Execute(object o);

Using design pattern, we have to write a more code to aggregate different strategies. But using Action<T> is more succinct.

Action<object> oldAction = ... ;//
Action<object> newAction = (o) => { Console.Write("preAction"); oldAction(o); Console.Write("postAction"); }

If we want to go a step further, we can use function(lamda, delegate) to create functions. For example:

Func<Action<object>, Action<object>> createFunc = (func) => 
   return (o) => { 

Action<ojbect> newAction = createFunc(oldAction);

Functional language is not new, Javascript is a functional language, and it has been doing this for a long long time. The power functional programming is that you can easily define new function easily, so that you can get interesting result of the new function.

May 15, 2010

Return statement in javascript

return expression;

If there is no expression, then the return value is undefined. Except for constructor, whose return value is this

Throw error

//"throw" is not limited just throwing Error, basically, you can throw anything.

//but normally, you are supposed to 

throw new Error(reason);
throw {name: exceptionName, message:reason};

Array in javascript

Technically, array in javascript is not really array in the context of other language like c#, it is more like a dictionary, the index is actually used as a key of an entry in the dictionary, like to the following.

var a = [];
a[0] = "fred";
alert(a["0"] == a[0]);

It is unique in that it has a length property, when you push an new item, array can automatically increase its length. It is also unique in that it support traditional for statement like for (i=1; i< a.length; i++) { ... }. Because Array is also an object so we can also use statement like "for ( var i in x), but it is not recommended because it defeat the purpose of array.

On the other hand, we can simulate the array feature for normal object. jQuery also use the technique like the following, so that jQuery object looks like an object, but it is not.

var push = [].push;
var y = {};, 100);
alert(y.length); //1
alert(y[0]); //100

To delete an array, do not use "delete array[index]" use array.splice(index, 1);

supplant function

var template = '<table border="{border}">' +
    '<tr><th>Last</th><td>{last}</td></tr>' +
    '<tr><th>First</th><td>{first}</td></tr>' +

var data = { first: "Carl", last: "Hollywood", border: 2 };

mydiv.innerHTML = template.supplant(data);

if (typeof String.proptotype.supplant !== 'function')
     String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g, 
                function(a, b) {
                  //a is $0, b is $1 (match 1)
                   var r = o[b];
                   return typeof r === 'string' ? r : a;

number, string , boolean conversion

var n = 1;
var s = "" + n; //number to string
n = +s;  //string to number
n = Number(s); //

//to convert to boolean

May 13, 2010

javascript split string into array by space


jQuery queue and deque

You queue a serial of function, then run the function in a serial.

   var area = document.getElementById("area");

         $.queue(area, "test", function (fn) { alert("hello"); fn()});

         $("#test").click(function () {
             var data = $.dequeue(area, "test");

triming leading and trailing whitespace in javascript

var result = text.replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" )

String.prototype.trim = function () {
    return this.replace(
        /^\s*(\S*(\s+\S+)*)\s*$/, "$1"); 

May 12, 2010

What is javascript

Here is how Douglas Crockford defined javascript

Javascript is a functional language with dynamic objects and familiar syntax.

In his definition, he stressed the most important feature of javascript is functional language(scheme), secondary important feature is dynamic objects(self), the last part is familiar syntax(java). The familiar syntax tend to new javascript developer think that javascript is easy language, but it is not. To really unleash the power of javascript, it is necessary to have deep understanding of functional feature and dynamic objects.

adding a new memeber to all objects in javascript

function Person(){}

var root = Object.prototype;
root.say = function () { alert("hi"); }
var p = new Person();

How to tell type of an object in javascript

We can use typeof, instanceof, and constructor to tell type of an object. But they have different effect. The "typeof" operator will return "object" for all custom types . "instanceof" will return true, if the object's constructor is in the list of constructor hierarchy. "constructor" will return the top constructor in the constructor hierarchy. Below is some test code

function Person() {}
function Developer(){}
Developer.prototype = new Person();

var dev = new Developer();

assert( typeof dev == "object");
assert( dev instanceof Developer);
assert( dev instanceof Person);
assert( dev.constructor == Person);
assert( dev.constructor != Developer);

a merge function

function merge(root){
  for ( var i = 0; i < arguments.length; i++ )
    for ( var key in arguments[i] )
      root[key] = arguments[i][key];
  return root;

May 7, 2010

position property

In css the position properties, such as top, left, right, bottom is auto by default, one miss conception is that they are 0. Which is not the case. So when you change from positon values (static, relative; absolute, fixed) without setting the top/left/right/bottom, there should be no change, except that absolute and fixed value will disable the margin merge.