200 OK
201 Created
204 No Content
205 Reset Content
206 Partial Content
400 Bad Request
401 Unauthorized
404 Not Found
405 Method Not Allowed
403 Forbidden
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
411 Length Required
413 Requested Entity Too Large
414 Requested URL Too Long
415 Unsupported Media Type
500 Internal Server Error
502 Bad Gateway
501Not Implemented
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
Saturday, November 8, 2008
Thursday, November 6, 2008
Inheritance using Closures and Prototypes
example for Closure:
function Car(name)
{
this.Name = name;
this.Drive = Drive;
}
function Drive(){}
function SuperCar(name)
{
//implement closure inheritance
this.inheritsFrom = Car;
this.inheritsFrom(name);
//add new method
this.Fly = Fly;
}
function Fly(){}
example for Prototyping:
function Car(name)
{
this.Name = name;
}
Car.prototype.Drive = function()
{
document.write("My Name is " + this.Name + " and I am driving
");
}
SuperCar.prototype = new Car();
SuperCar.prototype.constructor = SuperCar();
SuperCar.prototype.Fly = function()
{
document.write("My Name is " + this.Name + " and I am flying
");
}
function SuperCar(name)
{
Car.call(this,name);
}
function Car(name)
{
this.Name = name;
this.Drive = Drive;
}
function Drive(){}
function SuperCar(name)
{
//implement closure inheritance
this.inheritsFrom = Car;
this.inheritsFrom(name);
//add new method
this.Fly = Fly;
}
function Fly(){}
example for Prototyping:
function Car(name)
{
this.Name = name;
}
Car.prototype.Drive = function()
{
document.write("My Name is " + this.Name + " and I am driving
");
}
SuperCar.prototype = new Car();
SuperCar.prototype.constructor = SuperCar();
SuperCar.prototype.Fly = function()
{
document.write("My Name is " + this.Name + " and I am flying
");
}
function SuperCar(name)
{
Car.call(this,name);
}
Function as variable
In Javascript, function is first-class object, which is mean that a function is regarded as a data type which the value can be saved in local vaiables, passed as paramenters and assigned.
Keep in mind the javasript objects is understanding as collection (key value)pairs.
JavaScript doesn't support the notion of private memebers as C#, but we can simulate the functionality by ising variables inside the function. by declared the variable using keyword "var" instead of "this", thus acting like private members. Variables can, however, be accessed by closure functions.
Keep in mind the javasript objects is understanding as collection (key value)pairs.
JavaScript doesn't support the notion of private memebers as C#, but we can simulate the functionality by ising variables inside the function. by declared the variable using keyword "var" instead of "this", thus acting like private members. Variables can, however, be accessed by closure functions.
Tuesday, November 4, 2008
JavaScript Object (base) Oriented Programming
allowing runtime type reflection
allowing OOP advantage--- classes, interfaces, inheritance , emulate c# as much as possible.
Reflection comes from the important class -- Type
JavaScript Functions includes arguments, constructor and prototype
call and apply methods apply to function
allowing OOP advantage--- classes, interfaces, inheritance , emulate c# as much as possible.
Reflection comes from the important class -- Type
JavaScript Functions includes arguments, constructor and prototype
call and apply methods apply to function
Array.addRange() ---- is add item to array
Array.addRange() ---- is add item to array
var a= [1,2];
var b= [3,4];
Array.addRange(a, b) ---- add b array to a
for(var i in a) ---- the result will be 1,2,3,4
Array.clone() --- is shallow copy : only copy the reference but the objects being referenced are not copied
array.push --- push the item on the top of the stack
array.pop -- pop method pops up the item at the top of the stack
var a= [1,2];
var b= [3,4];
Array.addRange(a, b) ---- add b array to a
for(var i in a) ---- the result will be 1,2,3,4
Array.clone() --- is shallow copy : only copy the reference but the objects being referenced are not copied
array.push --- push the item on the top of the stack
array.pop -- pop method pops up the item at the top of the stack
Sunday, November 2, 2008
Client Delegates
Function.createDelegate(),
Steps create client delegate:
1) create client delegate by using Function.createDelegate(this, functionName)
2) add the new delegate into $addHandler(this, newDelegate)
3) access the window object, write the function
example:
function pageLoad() {
var clickDelegate = Function.createDelegate(this,onButtonClick);
$addHandler($get('btnTest'),'click',clickDelegate);
}
function onButtonClick()
{
alert(String.format("this code is funning on {0} {1}", Sys.Browser.name, Sys.Browser.version));
}
Steps create client delegate:
1) create client delegate by using Function.createDelegate(this, functionName)
2) add the new delegate into $addHandler(this, newDelegate)
3) access the window object, write the function
example:
function pageLoad() {
var clickDelegate = Function.createDelegate(this,onButtonClick);
$addHandler($get('btnTest'),'click',clickDelegate);
}
function onButtonClick()
{
alert(String.format("this code is funning on {0} {1}", Sys.Browser.name, Sys.Browser.version));
}
Client-page lifecycle
Sys.Application object lifecycle:
init, load, unload
1) When browser starts: Sys.Application object start initializing the MS Ajax library's runtime. firle the init event, initialized and instantiated all the client components.
2)Sys.Applicaton fires the load event.
3) when user mavigates away from the page or reloads page, the unload event of the window object intercepted by Sys.Application
init, load, unload
1) When browser starts: Sys.Application object start initializing the MS Ajax library's runtime. firle the init event, initialized and instantiated all the client components.
2)Sys.Applicaton fires the load event.
3) when user mavigates away from the page or reloads page, the unload event of the window object intercepted by Sys.Application
Wednesday, August 27, 2008
LINQ with DirectionInfo
DirectoryInfo di = new DirectoryInfo(@"d:\");
var dirQuery = from dir in di.GetDirectories()
orderby di.Name
select new { fName = dir.Name};
foreach(var folderName in dirQuery)
{
ListBox1.Items.Add(folderName.fName);
}
var dirQuery = from dir in di.GetDirectories()
orderby di.Name
select new { fName = dir.Name};
foreach(var folderName in dirQuery)
{
ListBox1.Items.Add(folderName.fName);
}
Tuesday, August 26, 2008
LINQ to XML
LINQ --- Language Integrated Query
LINQ to Objects (to APIs)
LINQ to XML
LINQ to SQL (Relational database)
New namespace System.Xml.Linq includes a series of new LINQ to XML objects that make working with xml easier:
1) XDocument instead of XmlDocument
XDocument xdoc = XDocumnet.load(@"d:\HPCTO");
query xml:
XDocument xdoc = XDocument.Load(@"D:\HPCTO\Pavilio.xml");
var query = from ConfigGroup in xdoc.Descendants("ConfigGroup")
select new
{
ProductDescription = ConfigGroup.Attribute("Description").Value
};
foreach (var item in query)
{
Response.Write(item);
Response.Write("
");
LINQ to Objects (to APIs)
LINQ to XML
LINQ to SQL (Relational database)
New namespace System.Xml.Linq includes a series of new LINQ to XML objects that make working with xml easier:
1) XDocument instead of XmlDocument
XDocument xdoc = XDocumnet.load(@"d:\HPCTO");
query xml:
XDocument xdoc = XDocument.Load(@"D:\HPCTO\Pavilio.xml");
var query = from ConfigGroup in xdoc.Descendants("ConfigGroup")
select new
{
ProductDescription = ConfigGroup.Attribute("Description").Value
};
foreach (var item in query)
{
Response.Write(item);
Response.Write("
");
Thursday, May 1, 2008
disable tracking in DataContext
You can disable the tracking ability by setting ObjectTrackingEnabled to false.
Disabling object tracking also prevents you from subitting updates to the data.
Disabling object tracking also prevents you from subitting updates to the data.
Monday, April 28, 2008
How Deferred Execution Works
Query operators provide deferred execution by returning decorator sequences.
Calling where merely consts the decorator wrapper sqequence, holding a reference to the input sequence, the lambda expression and any other arguments supplied.
---- c# 3.0 In a Nutshell
When query operator acutally querying the array through the where decorator
Calling where merely consts the decorator wrapper sqequence, holding a reference to the input sequence, the lambda expression and any other arguments supplied.
---- c# 3.0 In a Nutshell
When query operator acutally querying the array through the where decorator
LINQ Comprehension Queries
Besides Lamda Express in Queries, c# provides a syntactic shortcut for writing LINQ queries : Comprehension Query, this statement always starts with a from clause and ends with eithere a select or group clause.
Extention Methods(C# 3.0)
Extension Methods : extend new methods without altering the definition of the original type. the extension method must be a static method of a static class, where the this midifier is applied to the first parameter.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("foo".IsCapitalized());
Console.ReadLine();
}
}
public static class StringHelper
{
public static bool IsCapitalized(this string s)
{
if (string.IsNullOrEmpty(s)) return false;
return char.IsUpper(s[0]);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("foo".IsCapitalized());
Console.ReadLine();
}
}
public static class StringHelper
{
public static bool IsCapitalized(this string s)
{
if (string.IsNullOrEmpty(s)) return false;
return char.IsUpper(s[0]);
}
}
Nullable types
sting s = null;
int? i = null // ok nullable type
translates to:
Nullable i = new Nullable()
int? i = null // ok nullable type
translates to:
Nullable
Anonymous Methods
To write an anonymous method, include the delegate keyword followed by a parameter declarationa dn then a method body:
First create a delegate Transformer:
delegate int Transformer (int i);
call square:
Console.WriteLine(square(5));
First create a delegate Transformer:
delegate int Transformer (int i);
- Transformer square = delegate(int x){return x * x;};
- this statement can be simplied to :
- Transformer square = (int x ) => {return x * x;}
- OR
- Transformer squere = x => x* x;
call square:
Console.WriteLine(square(5));
Wednesday, April 23, 2008
partial classes and parital methods (C# 3.0)
Partial classes can't have the same members and constructor can't have the exactly same arguments. And must reside in the same assembly.
partial class may contain partial methods, the partial method must be void and are implicitly private.
partial class may contain partial methods, the partial method must be void and are implicitly private.
3.0 Object Initializers
Simply the process to initialize:
public class Bunny
{
public string Name;
public bool LikeCarrots;
public Bunny(string n)
{
this.Name = n;
}
}
Bunny b1 = new Bunny { Name = "stupid", LikeCarrots = false };
Bunny b2 = new Bunny("foo") { LikeCarrots = true };
public class Bunny
{
public string Name;
public bool LikeCarrots;
public Bunny(string n)
{
this.Name = n;
}
}
Bunny b1 = new Bunny { Name = "stupid", LikeCarrots = false };
Bunny b2 = new Bunny("foo") { LikeCarrots = true };
Passing by value vs Passing by ref
Passing by Values has two situations , it's by default (no parameter modifider)
1) passing by value type
2)passing by reference type
Passing by Reference has two situations one param modifier is ref, another is out
1) passing by value type
2)passing by reference type
Passing by Reference has two situations one param modifier is ref, another is out
Stack vs Heap
Stock is a block of memory for storing local variable. The storage automatically grows and shrinks as a function is entered and exited.
Heap is a block of memory in which objects reside.Whenever a new object is created, it is allocated on the heap, and reference to that object is returned. During a program's execution, the heap starts filling up as new objects are created. The runtime has a garbage collector that periodically deallocates objects from the heap, so your computer does not runt out of memory. An object is eligible for dealocation as soon as nothing references it.
------ C#3.0 In A Nutshell by Joseph & Ben
Heap is a block of memory in which objects reside.Whenever a new object is created, it is allocated on the heap, and reference to that object is returned. During a program's execution, the heap starts filling up as new objects are created. The runtime has a garbage collector that periodically deallocates objects from the heap, so your computer does not runt out of memory. An object is eligible for dealocation as soon as nothing references it.
------ C#3.0 In A Nutshell by Joseph & Ben
Best statement value types vs reference types
Value types comprise most build-in types(all numeric types, the char type and bool type), custom struct and enum types
Reference typs comprose all class, array, string delegate and inferface types.
Value types content is simply a value,
Reference type comtains Reference and object, when assigning a reference type variable copies the reference, not the object instance. This allows multiple variables to refer to the same object.
Reference type can be assigned null, value type can't.
Value type takes exactly the sum of memory of their fields takes.
Reference type takes object plus and reference memory, object meeory takes the sum of fields memory plus Oject metadata memory.
Reference typs comprose all class, array, string delegate and inferface types.
Value types content is simply a value,
Reference type comtains Reference and object, when assigning a reference type variable copies the reference, not the object instance. This allows multiple variables to refer to the same object.
Reference type can be assigned null, value type can't.
Value type takes exactly the sum of memory of their fields takes.
Reference type takes object plus and reference memory, object meeory takes the sum of fields memory plus Oject metadata memory.
Tuesday, April 22, 2008
yield return iterator
IL creates a state engine to retain their state and don't have to go through the pain of maintaining state in coding:
private static IEnumerable GetData()
{
for (int i=0; i <5; i++)
yield return i ;
}
when call GetData() function, will receive a new incremented integer.
private static IEnumerable
{
for (int i=0; i <5; i++)
yield return i ;
}
when call GetData() function, will receive a new incremented integer.
Load xml into XElement and loop through xElement
string url = Server.MapPath("Books.xml");
XElement x = XElement.Load(url, LoadOptions.PreserveWhitespace);
IEnumerable<xelement> authors = x.Descendants("author");
foreach (XElement author in authors)
{
Response.Write(author.Value + "<br />");
}
Here is XML file :
<?xml version="1.0" encoding="utf-8" ?><books><book><title>LINQ in Action</title><author>Fabrice Marguerie</author><author>Steve Eichert</author><author>Jim Wooley</author><publisher>Manning</publisher></book></books>
XElement x = XElement.Load(url, LoadOptions.PreserveWhitespace);
IEnumerable<xelement> authors = x.Descendants("author");
foreach (XElement author in authors)
{
Response.Write(author.Value + "<br />");
}
Here is XML file :
<?xml version="1.0" encoding="utf-8" ?><books><book><title>LINQ in Action</title><author>Fabrice Marguerie</author><author>Steve Eichert</author><author>Jim Wooley</author><publisher>Manning</publisher></book></books>
LINQ to XML
1) functional construction:
2) context-free XML creation
3)simplified names
RSS --- Really Simple Syndication--- a format for distributing and gathering content from sources across the web, including newspapers, magaxines, and blogs:
XML API class hierarchy:
XObject --> XNode --> XContainer-->
XDocument vs XElement
XDocment is complete xml doc.
2) context-free XML creation
3)simplified names
RSS --- Really Simple Syndication--- a format for distributing and gathering content from sources across the web, including newspapers, magaxines, and blogs:
XML API class hierarchy:
XObject --> XNode --> XContainer-->
XDocument vs XElement
XDocment is complete xml doc.
Monday, April 21, 2008
Partial Classes in ASP.NET
Partial classes split class into multiple physical files. Compiler treats all these partial classes as a single type.
partial keyword applies to classes, structs and interfaces but not enums
partial keyword applies to classes, structs and interfaces but not enums
pessimistic concurrency vs optimistic concurrency
locks another user to make changes until the record is released --- pessimistic concurrency
allow user to make changes to the same record -- optimistic concurrency
allow user to make changes to the same record -- optimistic concurrency
Tuesday, April 15, 2008
My Practices coding
namespace LINQtoSQL
{
public partial class PublisherMgr : System.Web.UI.Page
{
Table tbPublisher;
DataContext publisherDataContext;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(DataAccess.GetAdventureConnection());
publisherDataContext = new DataContext(conn);
tbPublisher = publisherDataContext.GetTable();
gvPublisher.DataSource = from pub in tbPublisher orderby pub.PublisherName select pub;
gvPublisher.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
Publisher newPub = new Publisher();
newPub.PublisherId = Guid.NewGuid();
newPub.PublisherName = txtPublisher.Text;
tbPublisher.InsertOnSubmit(newPub);
publisherDataContext.SubmitChanges();
gvPublisher.DataSource = from pub in tbPublisher orderby pub.PublisherName select pub;
gvPublisher.DataBind();
}
}
}
namespace LINQtoSQL
{
static public class DataAccess
{
static public IQueryable GetDataAccess()
{
string connectionString = ConfigurationSettings.AppSettings["connectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
DataContext dataContext = new DataContext(connection);
IQueryable books = from book in dataContext.GetTable() select book;
return books;
}
static public string GetAdventureConnection()
{
return ConfigurationSettings.AppSettings["connectionString"].ToString();
}
static public string GetNorthwindConnection()
{
return ConfigurationSettings.AppSettings["connectionStringNorthwind"].ToString();
}
}
}
namespace LINQtoSQL
{
[Table(Name="dbo.Book")]
public class Book
{
[Column(Name="BookId", IsPrimaryKey=true)]
public Guid BookId { get; set; }
[Column(Name="Isbn")]
public string Isbn { get; set; }
[Column (Name="Notes")]
public string Notes { get; set; }
[Column(Name="PageCount")]
public Int32 PageCount { get;set; }
[Column (Name="Price")]
public decimal Price {get;set;}
[Column (Name="PublicationDate")]
public DateTime PublicationDate { get; set; }
[Column (Name="Summary")]
public string Summary{get;set;}
[Column (Name="Title")]
public string Title{get;set;}
[Column (Name="SubjectId")]
public Guid SubjectId { get; set; }
[Column (Name="PublisherId")]
public Guid PublishId { get; set; }
}
[Table(Name = "dbo.Subject")]
public class Subject
{
[Column(Name="SubjectId",IsPrimaryKey=true)]
public Guid SubjectId { get; set; }
[Column(Name="Description")]
public string Description { get; set; }
}
[Table(Name = "dbo.Publisher")]
public class Publisher
{
[Column(Name="PublisherId", IsPrimaryKey=true)]
public Guid PublisherId { get; set; }
[Column(Name="PublisherName")]
public string PublisherName { get; set; }
}
}
{
public partial class PublisherMgr : System.Web.UI.Page
{
Table
DataContext publisherDataContext;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(DataAccess.GetAdventureConnection());
publisherDataContext = new DataContext(conn);
tbPublisher = publisherDataContext.GetTable
gvPublisher.DataSource = from pub in tbPublisher orderby pub.PublisherName select pub;
gvPublisher.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
Publisher newPub = new Publisher();
newPub.PublisherId = Guid.NewGuid();
newPub.PublisherName = txtPublisher.Text;
tbPublisher.InsertOnSubmit(newPub);
publisherDataContext.SubmitChanges();
gvPublisher.DataSource = from pub in tbPublisher orderby pub.PublisherName select pub;
gvPublisher.DataBind();
}
}
}
namespace LINQtoSQL
{
static public class DataAccess
{
static public IQueryable
{
string connectionString = ConfigurationSettings.AppSettings["connectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
DataContext dataContext = new DataContext(connection);
IQueryable
return books;
}
static public string GetAdventureConnection()
{
return ConfigurationSettings.AppSettings["connectionString"].ToString();
}
static public string GetNorthwindConnection()
{
return ConfigurationSettings.AppSettings["connectionStringNorthwind"].ToString();
}
}
}
namespace LINQtoSQL
{
[Table(Name="dbo.Book")]
public class Book
{
[Column(Name="BookId", IsPrimaryKey=true)]
public Guid BookId { get; set; }
[Column(Name="Isbn")]
public string Isbn { get; set; }
[Column (Name="Notes")]
public string Notes { get; set; }
[Column(Name="PageCount")]
public Int32 PageCount { get;set; }
[Column (Name="Price")]
public decimal Price {get;set;}
[Column (Name="PublicationDate")]
public DateTime PublicationDate { get; set; }
[Column (Name="Summary")]
public string Summary{get;set;}
[Column (Name="Title")]
public string Title{get;set;}
[Column (Name="SubjectId")]
public Guid SubjectId { get; set; }
[Column (Name="PublisherId")]
public Guid PublishId { get; set; }
}
[Table(Name = "dbo.Subject")]
public class Subject
{
[Column(Name="SubjectId",IsPrimaryKey=true)]
public Guid SubjectId { get; set; }
[Column(Name="Description")]
public string Description { get; set; }
}
[Table(Name = "dbo.Publisher")]
public class Publisher
{
[Column(Name="PublisherId", IsPrimaryKey=true)]
public Guid PublisherId { get; set; }
[Column(Name="PublisherName")]
public string PublisherName { get; set; }
}
}
Friday, April 11, 2008
Debug tool --- Query Visualizer tool
Download from:
http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx
and copy SqlServerQueryVisualizer.dll paste to file://program/ Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers
restart VS 2008 , you are good to debug LINQ Expression
http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx
and copy SqlServerQueryVisualizer.dll paste to file://program/ Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers
restart VS 2008 , you are good to debug LINQ Expression
Thursday, April 10, 2008
Standend query operators samples
Besides where, select, here are SelectMany, Selecting Indeces, Distinst...
SelectMany:
var authors = SampleData.Books.SelectMany(book => book.Authors);
equal expression:
var authors = from book in SampleData.Books
from author in book.Authors
select author.LastName
you can't write
var authors = from book in SampleData.Books SelectMany ........
select index:
var books = SampleData.Books
.Select((book, index) => new { index, book.Title })
.OrderBy(book => book.Title);
foreach (var bk in books)
{
Response.Write(bk.Title + bk.index);
}
SelectMany:
var authors = SampleData.Books.SelectMany(book => book.Authors);
equal expression:
var authors = from book in SampleData.Books
from author in book.Authors
select author.LastName
you can't write
var authors = from book in SampleData.Books SelectMany ........
select index:
var books = SampleData.Books
.Select((book, index) => new { index, book.Title })
.OrderBy(book => book.Title);
foreach (var bk in books)
{
Response.Write(bk.Title + bk.index);
}
Wednesday, April 9, 2008
Example Query expression & Operator
Which method you prefer???
string[] books =
{ "Funny Stories", "All your base are belong to us", "C# on Railjs", "Bonjour mon Amoue" };
// Operator:
GridView1.DataSource =
books
.Where(book => book.Length > 10)
.OrderBy(book => book)
.Select(book => book.ToUpper());
// query expression
GridView1.DataSource = from book in books where book.Length > 10 orderby book select book;
GridView1.DataBind();
string[] books =
{ "Funny Stories", "All your base are belong to us", "C# on Railjs", "Bonjour mon Amoue" };
// Operator:
GridView1.DataSource =
books
.Where(book => book.Length > 10)
.OrderBy(book => book)
.Select(book => book.ToUpper());
// query expression
GridView1.DataSource = from book in books where book.Length > 10 orderby book select book;
GridView1.DataBind();
Tuesday, April 8, 2008
Deferred query execution
The query operators is that they execute not when constructed but when ecumerated (in other words, when MoveNext is called on its enumerator)
LINQ sample:
var numbers = new List();
numbers.Add(1);
var query = from n in numbers select n * 10;
numbers.Add(10);
foreach (int i in query)
{
Console.WriteLine(i);
}
Console.ReadLine();
The number 10 is added into the query result, this is called lazy evalution or deferred.
This feature seperate the query construction from query execution
LINQ sample:
var numbers = new List
numbers.Add(1);
var query = from n in numbers select n * 10;
numbers.Add(10);
foreach (int i in query)
{
Console.WriteLine(i);
}
Console.ReadLine();
The number 10 is added into the query result, this is called lazy evalution or deferred.
This feature seperate the query construction from query execution
Iterator yield return sample code
using System.Collections.Generic;
protected void Page_Load(object sender, EventArgs e)
{
foreach (var v in OneTwoThree())
{
Response.Write(v);
}
}
private IEnumerable OneTwoThree()
{
Response.Write("return 1");
yield return 1;
Response.Write("return 2");
yield return 2;
Response.Write("return 3");
yield return 3;
}
protected void Page_Load(object sender, EventArgs e)
{
foreach (var v in OneTwoThree())
{
Response.Write(v);
}
}
private IEnumerable
{
Response.Write("return 1");
yield return 1;
Response.Write("return 2");
yield return 2;
Response.Write("return 3");
yield return 3;
}
IEnumerable two usage generic && non-generic
The non-generic type'System.Collections.IEnumerable' cannot be used with type arguments. error message: ask you add using System.Collections.Generic
LINQ Sample
var processes =
Process.GetProcesses().Where(process => process.WorkingSet64 > 20 * 1024 * 1024)
.OrderByDescending(process => process.WorkingSet64)
.Select(process => new { Id = process.Id, Name = process.ProcessName });
foreach (var obj in processes)
{
Response.Write(obj.Id +" & "+ obj.Name +"");
}
Process.GetProcesses().Where(process => process.WorkingSet64 > 20 * 1024 * 1024)
.OrderByDescending(process => process.WorkingSet64)
.Select(process => new { Id = process.Id, Name = process.ProcessName });
foreach (var obj in processes)
{
Response.Write(obj.Id +" & "+ obj.Name +"");
}
Anonymous types
Sample code:
var v1 = new {FirstName ="Bin", LastName="Zeng" }
The conpilers consider anonymous types that is specified within the same program with properties of the same names and types in the same order to be the same type.
Linitations:
var v1 = new {FirstName ="Bin", LastName="Zeng" }
The conpilers consider anonymous types that is specified within the same program with properties of the same names and types in the same order to be the same type.
Linitations:
Monday, April 7, 2008
Write Extension methods
Extension Methods: allow us to add new methods to existing CLR type.
simple example:
string customerName ="you foo";
if(Customer.IsValid(customerName))
{}
now by adding extending methods
string customerName = "you foo";
if(custimerName.IsValid())
{}
simple example:
string customerName ="you foo";
if(Customer.IsValid(customerName))
{}
now by adding extending methods
string customerName = "you foo";
if(custimerName.IsValid())
{}
Lambda Expressions
Lambda Expressions a writing anonymous methods:
IEnumerable <person> results = people.Where(p => p.LastName == "Zeng");
Convent to inline methods:
IEnumerable <Person> results = people.Where( delegate (Person p){return p.LastName = ="Zeng";}
) ;
IEnumerable<Person> advanceResults = people.Where(p => p.LastName == "Zeng")
.OrderBy(p => p.FirstName)
.Take(2);
IEnumerable <person> results = people.Where(p => p.LastName == "Zeng");
Convent to inline methods:
IEnumerable <Person> results = people.Where( delegate (Person p){return p.LastName = ="Zeng";}
) ;
IEnumerable<Person> advanceResults = people.Where(p => p.LastName == "Zeng")
.OrderBy(p => p.FirstName)
.Take(2);
Object and collection initializers
Object initializers:
var data = new ProcessData {Id = 123, Name ="CurrentProcess",Memory = 12345567};
Collectiopn initializers:
var digits = new List {0,1,2,3,4,5};
for example:
foreach (var process in Process.GetProcesses())
{
processes.Add(new ProcessData { Id = process.Id, Name = process.ProcessName, Memory = process.WorkingSet64 });
}
yeah yeah yeah so easy now !!!!!!!!!!!!!!!!!!!!!!
var data = new ProcessData {Id = 123, Name ="CurrentProcess",Memory = 12345567};
Collectiopn initializers:
var digits = new List
for example:
foreach (var process in Process.GetProcesses())
{
processes.Add(new ProcessData { Id = process.Id, Name = process.ProcessName, Memory = process.WorkingSet64 });
}
yeah yeah yeah so easy now !!!!!!!!!!!!!!!!!!!!!!
C# 3.0 Language enhancements
1) Auto-implemented properties: This feature allows 3.0 compiler that creates anonymous private variables to contain each of the values that the individual property will be using:
for example:
public Int Id {get;set;} none private int _id
2)Implicitly typed local variables:
for example:
var Processes = new List<ProcessData>();
before:
List Processes = new List<ProcessData>()
In this case we no longer have to write the types of local variables twice, The compiler infers the types automatically. This means that even though we use a simplified syntax, we still get alll the benefits fo strong types, such as compile-time validation and IntelliSense.
for example:
public Int Id {get;set;} none private int _id
2)Implicitly typed local variables:
for example:
var Processes = new List<ProcessData>
before:
List
In this case we no longer have to write the types of local variables twice, The compiler infers the types automatically. This means that even though we use a simplified syntax, we still get alll the benefits fo strong types, such as compile-time validation and IntelliSense.
Tuesday, March 25, 2008
Monday, March 24, 2008
Model View Presenter --- MVP Design pattern

MVP pattern is one of the major patterns used for ectracting besuness logic outside of UI elements and by that, enabling unit testing the UI without the need for using sepecific UI based testing tools.
View contains the presenter instance
Presenter is the only class knowing how to reach to model and retrieve the data needed for performaing business logic.
Presenter talks to the view throgh the view interface (abstracted representation of the View without UI sepcific attributes)
View doesn't know nothing about the Model
a facade design patten
A facade, in software design terms, is an interface intended to simplify a more complex API.
Facade:
Knows which subsystem classes are responsible for a request. delegated client requests to approproate subsystem objects
Subsystem classes:
implement substem functionality
handle work assigned by the Facade object
have no knowledge of the facase and keep no reference to it
Facade:
Knows which subsystem classes are responsible for a request. delegated client requests to approproate subsystem objects
Subsystem classes:
implement substem functionality
handle work assigned by the Facade object
have no knowledge of the facase and keep no reference to it
Wednesday, March 12, 2008
BizTalk Message Delivery
Message-Delivery Patterns
Scatter-gather
Request-reply
Publish-subscriber
Message-Processing Patterns
Aggregator
First in/first out
Splitter
Scatter-gather
Request-reply
Publish-subscriber
Message-Processing Patterns
Aggregator
First in/first out
Splitter
Tuesday, March 11, 2008
What is ERP?
ERP-- Enterprose Resource Planning. ERP is a way to integrate the data and processes of an organization into one single system.
There are many advantages of implementing an EPR system; here are a few of them:
* A totally integrated system
* The ability to streamline different processes and workflows
* The ability to easily share data across various departments in an organization
* Improved efficiency and productivity levels
* Better tracking and forecasting
* Lower costs
* Improved customer service
While advantages usually outweigh disadvantages for most organizations implementing an ERP system, here are some of the most common obstacles experienced:
Usually many obstacles can be prevented if adequate investment is made and adequate training is involved, however, success does depend on skills and the experience of the workforce to quickly adapt to the new system.
* Customization in many situations is limited
* The need to reengineer business processes
* ERP systems can be cost prohibitive to install and run
* Technical support can be shoddy
* ERP's may be too rigid for specific organizations that are either new or want to move in a new direction in the near future.
The term ERP originally referred to how a large organization planned to use organizational wide resources. In the past, ERP systems were used in larger more industrial types of companies. However, the use of ERP has changed and is extremely comprehensive, today the term can refer to any type of company, no matter what industry it falls in. In fact, ERP systems are used in almost any type of organization - large or small.
In order for a software system to be considered ERP, it must provide an organization with functionality for two or more systems. While some ERP packages exist that only cover two functions for an organization (QuickBooks: payroll & accounting), most ERP systems cover several functions.
Today's ERP systems can cover a wide range of functions and integrate them into one unified database. For instance, functions such as Human Resources, Supply Chain Management, Customer Relations Management, Financials, Manufacturing functions and Warehouse Management functions were all once stand alone software applications, usually housed with their own database and network, today, they can all fit under one umbrella - the ERP system.
There are many advantages of implementing an EPR system; here are a few of them:
* A totally integrated system
* The ability to streamline different processes and workflows
* The ability to easily share data across various departments in an organization
* Improved efficiency and productivity levels
* Better tracking and forecasting
* Lower costs
* Improved customer service
While advantages usually outweigh disadvantages for most organizations implementing an ERP system, here are some of the most common obstacles experienced:
Usually many obstacles can be prevented if adequate investment is made and adequate training is involved, however, success does depend on skills and the experience of the workforce to quickly adapt to the new system.
* Customization in many situations is limited
* The need to reengineer business processes
* ERP systems can be cost prohibitive to install and run
* Technical support can be shoddy
* ERP's may be too rigid for specific organizations that are either new or want to move in a new direction in the near future.
The term ERP originally referred to how a large organization planned to use organizational wide resources. In the past, ERP systems were used in larger more industrial types of companies. However, the use of ERP has changed and is extremely comprehensive, today the term can refer to any type of company, no matter what industry it falls in. In fact, ERP systems are used in almost any type of organization - large or small.
In order for a software system to be considered ERP, it must provide an organization with functionality for two or more systems. While some ERP packages exist that only cover two functions for an organization (QuickBooks: payroll & accounting), most ERP systems cover several functions.
Today's ERP systems can cover a wide range of functions and integrate them into one unified database. For instance, functions such as Human Resources, Supply Chain Management, Customer Relations Management, Financials, Manufacturing functions and Warehouse Management functions were all once stand alone software applications, usually housed with their own database and network, today, they can all fit under one umbrella - the ERP system.
Wednesday, March 5, 2008
Thursday, February 28, 2008
BizTalk Components
Businees Rules EngineThe rules engine allows you to apply business process logic against message data. MS provides a full-featured tool for rules creation, called the Business Rule Composer.
Orchestrations
Provides a unique graphical interface for routing, evaluating, and manipulatiing incoming and outgoing messages
Orchestrations also provide a means by which you can communicate with web services, databases, and other corporate entities
Healthe and Activity Tracking(HAT)
monitoring the BizTalk
Business Activity Monitoring(BAM)
gives non technical personnel a portal to view the data
Business Activity Services
set providers functionality for managing and instantiating integration relationships with various trading partners.
Messaging
One could almost make the point that messaging is the core component of the BizTalk Server product. Messaging is not simply one particular application that you can start. It's a combination of adapters, pipelines, ports, and more that collaborate to effectively and efficiently manipulate and route your message data
Enterprise Single Sign-On
Enterprise Single Sign-On (SSO) is the process by which non-Windows authentication accounts can be granted or denied rights based on preferential mappings established by the BizTalk administrator. This allows you to take in a message that has established authentication through the trading partner's own criteria and correspondingly map that authentication to an internal account within your enterprise
Orchestrations
Provides a unique graphical interface for routing, evaluating, and manipulatiing incoming and outgoing messages
Orchestrations also provide a means by which you can communicate with web services, databases, and other corporate entities
Healthe and Activity Tracking(HAT)
monitoring the BizTalk
Business Activity Monitoring(BAM)
gives non technical personnel a portal to view the data
Business Activity Services
set providers functionality for managing and instantiating integration relationships with various trading partners.
Messaging
One could almost make the point that messaging is the core component of the BizTalk Server product. Messaging is not simply one particular application that you can start. It's a combination of adapters, pipelines, ports, and more that collaborate to effectively and efficiently manipulate and route your message data
Enterprise Single Sign-On
Enterprise Single Sign-On (SSO) is the process by which non-Windows authentication accounts can be granted or denied rights based on preferential mappings established by the BizTalk administrator. This allows you to take in a message that has established authentication through the trading partner's own criteria and correspondingly map that authentication to an internal account within your enterprise
BizTalk Server 2006
Adapters concepts:
File Adapter, Web Services Adapter
SQL Adapter, HTTP Adapter
these four collection of adapters that micorsoft has provided.
are the application-specific interfaces to the BizTalk messaging engine.
Web Services Adapter
Send and receive messages as SOAP packages over HTTP
File Adapter
Read and write files to the file system
MSMQ Adapter
Send and receive messages with Microsoft Message Queuing
HTTP Adapter
Send and receive messages via HTTP
WebSphere Adapter
Send and receive messages using WebSphere MQ by IBM
SMTP Adapter
Send messages via SMTP
POP3 Adapter
Receive e-mail messages and attachments
SharePoint Services Adapter
Access SharePoint document libraries
SQL Adapter
Interface with a SQL Server database
File Adapter, Web Services Adapter
SQL Adapter, HTTP Adapter
these four collection of adapters that micorsoft has provided.
are the application-specific interfaces to the BizTalk messaging engine.
Web Services Adapter
Send and receive messages as SOAP packages over HTTP
File Adapter
Read and write files to the file system
MSMQ Adapter
Send and receive messages with Microsoft Message Queuing
HTTP Adapter
Send and receive messages via HTTP
WebSphere Adapter
Send and receive messages using WebSphere MQ by IBM
SMTP Adapter
Send messages via SMTP
POP3 Adapter
Receive e-mail messages and attachments
SharePoint Services Adapter
Access SharePoint document libraries
SQL Adapter
Interface with a SQL Server database
Wednesday, February 20, 2008
SQL dateTime, date
create function DateOnly(@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
begin
return dateadd(dd,0, datediff(dd,0,@DateTime))
end
go
create function Date(@Year int, @Month int, @Day int)
-- returns a datetime value for the specified year, month and day
-- Thank you to Michael Valentine Jones for this formula (see comments).
returns datetime
as
begin
return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
end
go
create function Time(@Hour int, @Minute int, @Second int)
-- Returns a datetime value for the specified time at the "base" date (1/1/1900)
-- Many thanks to MVJ for providing this formula (see comments).
returns datetime
as
begin
return dateadd(ss,(@Hour*3600)+(@Minute*60)+@Second,0)
end
go
create function TimeOnly(@DateTime DateTime)
-- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
returns datetime
as
begin
return @DateTime - dbo.DateOnly(@DateTime)
end
go
create function DateTime(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int)
-- returns a dateTime value for the date and time specified.
returns datetime
as
begin
return dbo.Date(@Year,@Month,@Day) + dbo.Time(@Hour, @Minute,@Second)
end
go
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
begin
return dateadd(dd,0, datediff(dd,0,@DateTime))
end
go
create function Date(@Year int, @Month int, @Day int)
-- returns a datetime value for the specified year, month and day
-- Thank you to Michael Valentine Jones for this formula (see comments).
returns datetime
as
begin
return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
end
go
create function Time(@Hour int, @Minute int, @Second int)
-- Returns a datetime value for the specified time at the "base" date (1/1/1900)
-- Many thanks to MVJ for providing this formula (see comments).
returns datetime
as
begin
return dateadd(ss,(@Hour*3600)+(@Minute*60)+@Second,0)
end
go
create function TimeOnly(@DateTime DateTime)
-- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
returns datetime
as
begin
return @DateTime - dbo.DateOnly(@DateTime)
end
go
create function DateTime(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int)
-- returns a dateTime value for the date and time specified.
returns datetime
as
begin
return dbo.Date(@Year,@Month,@Day) + dbo.Time(@Hour, @Minute,@Second)
end
go
Friday, January 4, 2008
Good Recommandation to mock up design site
http://www.templatemonster.com/
Avid using HTML Tables to Control Layout
the W3C officially discourages it:
www.w3c.org/tr/wai-webcontent
Avid using HTML Tables to Control Layout
the W3C officially discourages it:
www.w3c.org/tr/wai-webcontent
Back to the beerhouse again
You start by establishing the user experience you want people to have, and then you design the plumbing behing the scenes that will provide that user experience. Some basic considerations that affect the user's experience are the menu and navigation, use of images, and the organization of elements on the page. The menu must be intuitive and should be augmented by navigation hints such as a site map or breadcrumbs that can remind users where they are, relative to the site as a whole.
Breadcrumbs in this context refer to a set of small links on the page that form atrail that enables users to back up to a previous page by clicking on the link segment for a page higher in the page hierarchy.
code reusability and enhance maintainability.
Breadcrumbs in this context refer to a set of small links on the page that form atrail that enables users to back up to a previous page by clicking on the link segment for a page higher in the page hierarchy.
code reusability and enhance maintainability.
Subscribe to:
Posts (Atom)
