Chain effects in the single element is inline effect but not including .css():
Here is the example:
$('div.label').click(function(){
$('div.button').fadeTo('slow',0.5)
.animate({left: 650},'slow')
.fadeTo('slow',1.0)
.slideUp('slow')
.css('backgroundColor','#f00');
});
You will see the backgroundColor of button will immediately affected after click on div.label
Monday, March 16, 2009
Monday, February 9, 2009
useful small function to write text log in local machine
public static void WriteLog(string logFile, string logHeader, string message)
{
string logMessage = string.Empty;
byte[] logMessageBytes;
try
{
FileInfo logFileInfo = new FileInfo(logFile);
if (!IsFileOrDirectoryExists(logFile, FileType.File))
{
logMessage = logHeader + "\r\n" + message;
logMessageBytes = Encoding.ASCII.GetBytes(logMessage);
}
else
{
logMessage = "\r\n" + message;
logMessageBytes = Encoding.ASCII.GetBytes(logMessage);
}
using (FileStream logFileStream = logFileInfo.Open(FileMode.Append, FileAccess.Write, FileShare.Read))
{
logFileStream.Write(logMessageBytes, 0, logMessageBytes.Length);
}
}
catch(Exception ex)
{
DSTrace.LogEvent(DSTL.E, FormatE4XException(ex));
}
}
here: logfile is the file name
message is what you want to write to this page
logheaere is not you need
reference: system.IO; system.text
{
string logMessage = string.Empty;
byte[] logMessageBytes;
try
{
FileInfo logFileInfo = new FileInfo(logFile);
if (!IsFileOrDirectoryExists(logFile, FileType.File))
{
logMessage = logHeader + "\r\n" + message;
logMessageBytes = Encoding.ASCII.GetBytes(logMessage);
}
else
{
logMessage = "\r\n" + message;
logMessageBytes = Encoding.ASCII.GetBytes(logMessage);
}
using (FileStream logFileStream = logFileInfo.Open(FileMode.Append, FileAccess.Write, FileShare.Read))
{
logFileStream.Write(logMessageBytes, 0, logMessageBytes.Length);
}
}
catch(Exception ex)
{
DSTrace.LogEvent(DSTL.E, FormatE4XException(ex));
}
}
here: logfile is the file name
message is what you want to write to this page
logheaere is not you need
reference: system.IO; system.text
Wednesday, January 28, 2009
WCF--- Foundation Programming Model
Addressing a service is essential to being able to use a service.
Address Section includes: Transport scheme, machinename(fully qualified domain name of the machine), port, path.
Addresses: HTTP, TCT, MSMQ, Pipes
Bindingss: the format to communicate with the service
The transport(HTTP, MSMQ,Named Pipes, TCP)
The channels(one-way, duplex, request-reply)
The encoding(XML, binary, MTOM...)
Messaging Exchange Patterns: Request-Reply(default pattern), One-Way(similar to calling an an asynchronous method with a void return type)
Duplex--- the both ends simultaneously acting as both a sender and a receiver.
Address Section includes: Transport scheme, machinename(fully qualified domain name of the machine), port, path.
Addresses: HTTP, TCT, MSMQ, Pipes
Bindingss: the format to communicate with the service
The transport(HTTP, MSMQ,Named Pipes, TCP)
The channels(one-way, duplex, request-reply)
The encoding(XML, binary, MTOM...)
Messaging Exchange Patterns: Request-Reply(default pattern), One-Way(similar to calling an an asynchronous method with a void return type)
Duplex--- the both ends simultaneously acting as both a sender and a receiver.
Tuesday, January 13, 2009
.NET3.5 load XML class--- ObjectDataSource
public class CustomerDataProvider
{
public CustomerDataProvider(){}
private List Customers
{
get
{
XDocument xdoc = XDocument.Load(@"customers.xml");
List customers = new List();
IEnumerable iCustoms
= from C in xdoc.Descendants("customer")
orderby C.Attribute("CustomerID").Value
select new Customer
{
ID = C.Attribute("CustomerID").Value,
CompanyName = C.Attribute("CompanyName").Value,
ContactName = C.Attribute("ContactName").Value,
Address = C.Attribute("Address").Value,
ContactTitle = C.Attribute("ContactTitle").Value,
City = C.Attribute("City").Value,
Phone = C.Attribute("Phone").Value,
State = C.Attribute("State").Value,
ZipCode = C.Attribute("ZipCode").Value
};
customers = (List)iCustoms;
return customers;
}
}
public IEnumerable FindAll()
{
return this.Customers;
}
public IEnumerable FindById(string CustomerId)
{
return (from C in this.Customers where C.ID == CustomerId select C);
}
public void Update(Customer newCustomer)
{
Customer custm = this.Customers.Find(x => x.ID == newCustomer.ID);
custm.CompanyName = newCustomer.CompanyName;
custm.ContactName = newCustomer.ContactName;
custm.ContactTitle = newCustomer.ContactTitle;
custm.Address = newCustomer.Address;
custm.City = newCustomer.City;
custm.State = newCustomer.State;
custm.Phone = newCustomer.Phone;
custm.ZipCode = newCustomer.ZipCode;
}
}
{
public CustomerDataProvider(){}
private List
{
get
{
XDocument xdoc = XDocument.Load(@"customers.xml");
List
IEnumerable
= from C in xdoc.Descendants("customer")
orderby C.Attribute("CustomerID").Value
select new Customer
{
ID = C.Attribute("CustomerID").Value,
CompanyName = C.Attribute("CompanyName").Value,
ContactName = C.Attribute("ContactName").Value,
Address = C.Attribute("Address").Value,
ContactTitle = C.Attribute("ContactTitle").Value,
City = C.Attribute("City").Value,
Phone = C.Attribute("Phone").Value,
State = C.Attribute("State").Value,
ZipCode = C.Attribute("ZipCode").Value
};
customers = (List
return customers;
}
}
public IEnumerable
{
return this.Customers;
}
public IEnumerable
{
return (from C in this.Customers where C.ID == CustomerId select C);
}
public void Update(Customer newCustomer)
{
Customer custm = this.Customers.Find(x => x.ID == newCustomer.ID);
custm.CompanyName = newCustomer.CompanyName;
custm.ContactName = newCustomer.ContactName;
custm.ContactTitle = newCustomer.ContactTitle;
custm.Address = newCustomer.Address;
custm.City = newCustomer.City;
custm.State = newCustomer.State;
custm.Phone = newCustomer.Phone;
custm.ZipCode = newCustomer.ZipCode;
}
}
jquery load xml and display in html
$(function(){
$.get('books.xml',function(d){
$('body').append(' <h1>Recommended Web Development Bookds</h1>');
$('body').append(' <dl>');
$(d).find('book').each(function(){
var $book = $(this);
var title = $book.attr("title");
var description = $book.find('description').text();
var imageurl = $book.attr('imageurl');
var html = ' <dt><img class="bookImage" alt="" src="http://www.blogger.com/" /> </dt>';
html += ' <dd><span class="loadingPic" alt="Loading">';
html += ' <p class="title">' + title + '</p>';
html += ' <p>' + description + '</p>' ;
html += '</dd>';
$('dl').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});</dl></span>
<span class="loadingPic" alt="Loading"></span>
$.get('books.xml',function(d){
$('body').append(' <h1>Recommended Web Development Bookds</h1>');
$('body').append(' <dl>');
$(d).find('book').each(function(){
var $book = $(this);
var title = $book.attr("title");
var description = $book.find('description').text();
var imageurl = $book.attr('imageurl');
var html = ' <dt><img class="bookImage" alt="" src="http://www.blogger.com/" /> </dt>';
html += ' <dd><span class="loadingPic" alt="Loading">';
html += ' <p class="title">' + title + '</p>';
html += ' <p>' + description + '</p>' ;
html += '</dd>';
$('dl').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});</dl></span>
<span class="loadingPic" alt="Loading"></span>
Monday, January 12, 2009
JQuery post data to .ashx, pass to LINQ to SQL
First I create contact table which has contactId, name, email and comment. Then I create LINQtoSQL contact.dbml file.
Create new handler file call : SubmitDB.ashx. update the ProcessRequest method :
public void ProcessRequest (HttpContext context) {
var name = context.Request["name"];
var email = context.Request["email"];
var comment = context.Request["comment"];
ContactDataContext contactDB = new ContactDataContext();
Contact contact = new Contact();
contact.Name = name;
contact.Email = email;
contact.Comments = comment;
contactDB.Contacts.InsertOnSubmit(contact);
contactDB.SubmitChanges();
context.Response.Write("loading success");
}
On the front file: submitDataToDB.htm add the form method="post" action ="SubmitDB.ashx"
add container div:
<div id="container">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<label for="comment">Comment</label>
<textarea id="comment" name="comment" cols="35" rows="5">
</textarea>
<br />
<input type="button" id="submit" name="submit" value="Go" />
</div>
In Javascript, reference google javascript:
add another script:
$(function(){
$('#submit').click(function(){
$('#container').append('<img id="loadining" src="ajax-loader.gif" alt="loading"/>');
var name = $('#name').val();
var email = $('#email').val();
var comment = $('#comment').val();
// console.log(name,email, comment);
$.ajax({
url: 'SubmitDB.ashx',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comment=' +comment,
success:function(result)
{
$('#response').remove();
$('#container').append('<p id="response">'+ result+ '</p>');
$('#loadining').fadeOut(500,function(){
$(this).remove();
});
}
});
return false;
});
});
Create new handler file call : SubmitDB.ashx. update the ProcessRequest method :
public void ProcessRequest (HttpContext context) {
var name = context.Request["name"];
var email = context.Request["email"];
var comment = context.Request["comment"];
ContactDataContext contactDB = new ContactDataContext();
Contact contact = new Contact();
contact.Name = name;
contact.Email = email;
contact.Comments = comment;
contactDB.Contacts.InsertOnSubmit(contact);
contactDB.SubmitChanges();
context.Response.Write("loading success");
}
On the front file: submitDataToDB.htm add the form method="post" action ="SubmitDB.ashx"
add container div:
<div id="container">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<label for="comment">Comment</label>
<textarea id="comment" name="comment" cols="35" rows="5">
</textarea>
<br />
<input type="button" id="submit" name="submit" value="Go" />
</div>
In Javascript, reference google javascript:
add another script:
$(function(){
$('#submit').click(function(){
$('#container').append('<img id="loadining" src="ajax-loader.gif" alt="loading"/>');
var name = $('#name').val();
var email = $('#email').val();
var comment = $('#comment').val();
// console.log(name,email, comment);
$.ajax({
url: 'SubmitDB.ashx',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comment=' +comment,
success:function(result)
{
$('#response').remove();
$('#container').append('<p id="response">'+ result+ '</p>');
$('#loadining').fadeOut(500,function(){
$(this).remove();
});
}
});
return false;
});
});
Friday, January 9, 2009
Resize Text in JQuery
$('a').click(function(){
var os = $('p').css('font-size');
var num = parseFloat(os, 10);
var um = os.slice(-2);
$('p').css('font-size', num / 1.4 + um);
if(this.id == 'larger')
{
$('p').css('font-size', num * 1.4 + um);
}
});
------ HTML-----
<a href="#" id ="larger">Larger</a>
<br>
<a href="#" id="smaller">Smaller</a>
<p>
Fits Single/Double Shopping Carts, High Chairs & Infant Swings!
</p>
var os = $('p').css('font-size');
var num = parseFloat(os, 10);
var um = os.slice(-2);
$('p').css('font-size', num / 1.4 + um);
if(this.id == 'larger')
{
$('p').css('font-size', num * 1.4 + um);
}
});
------ HTML-----
<a href="#" id ="larger">Larger</a>
<br>
<a href="#" id="smaller">Smaller</a>
<p>
Fits Single/Double Shopping Carts, High Chairs & Infant Swings!
</p>
Thursday, January 8, 2009
JQuery Hover Images
$(function(){
$('#container img').animate({
"opacity" : .5
});
$('#container img').hover(function(){
$(this).stop().animate({"opacity" :1});
},function(){
$(this).stop().animate({"opacity" : .5});
});
});
Tuesday, December 30, 2008
Hashtable vs Dictionary<>
Hashtable, array, and ArrayList ---- System.Collections, weak data type
Dictionary<>, List<> -----System.Collection.Generic, strong data type
for example:
you can define hashtable:
Hashtable employees = new Hashtable();
employees.Add("A100",1);
employees.Add("A101",2);
employees.Add(3, "asdfasf");
no compile error
Dictinary diEmp = new Dictionary();
Dictionary<>, List<> -----System.Collection.Generic, strong data type
for example:
you can define hashtable:
Hashtable employees = new Hashtable();
employees.Add("A100",1);
employees.Add("A101",2);
employees.Add(3, "asdfasf");
no compile error
Dictinary
Monday, December 29, 2008
Using sql agent date and time handling
I had project try to insert batch run time into database. The batchRunDt data formation is "20070430204147", the field in database is datetime,
here is the example to show you how to using fn_agentDate2DateTime to converts datetime
declare @batchRunDt varchar(20)
select @batchRunDt = '20070430204147'
print msdb.dbo.fn_AgentDateTime2DateTime(left(@batchRunDt,8),Right(@batchRunDt,6))
The result is :
Apr 30 2007 8:41PM
print msdb.dbo.fn_AgentDate2DateTime(20060806)
The result is:
Aug 9 2006 12:00AM
you can download the function in : http://sqldev.net/sqlagent/SQLAgentDateTime.htm
here is the example to show you how to using fn_agentDate2DateTime to converts datetime
declare @batchRunDt varchar(20)
select @batchRunDt = '20070430204147'
print msdb.dbo.fn_AgentDateTime2DateTime(left(@batchRunDt,8),Right(@batchRunDt,6))
The result is :
Apr 30 2007 8:41PM
print msdb.dbo.fn_AgentDate2DateTime(20060806)
The result is:
Aug 9 2006 12:00AM
you can download the function in : http://sqldev.net/sqlagent/SQLAgentDateTime.htm
Find the missing two interger in array
We all know how to find one missing interger in array, my question is how can we find the two missing interger in interger array:
public void Find2MissingNum()
{
int[] iTol = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] iMis = { 1, 2, 4, 6, 7, 8, 9, 10 };
int x, y;
// try to find 3, 5
//sum iMis
int sMis =0 , sTol=0;
foreach (int i in iMis)
{
sMis += i;
}
// sum iTol
sTol = iTol.Length * (iTol.Length + 1) / 2;
// time total
int tMis = 1, tTol = 1;
foreach (int i in iMis)
{
tMis *= i;
}
foreach (int i in iTol)
{
tTol *= i;
}
int timeSmisStol = tTol / tMis;
int difTM = sTol - sMis;
for (int i = 0; i < difTM; i++)
{
if (i * (difTM - i) == timeSmisStol)
{
x = i;
y = difTM - i;
}
}
}
public void Find2MissingNum()
{
int[] iTol = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] iMis = { 1, 2, 4, 6, 7, 8, 9, 10 };
int x, y;
// try to find 3, 5
//sum iMis
int sMis =0 , sTol=0;
foreach (int i in iMis)
{
sMis += i;
}
// sum iTol
sTol = iTol.Length * (iTol.Length + 1) / 2;
// time total
int tMis = 1, tTol = 1;
foreach (int i in iMis)
{
tMis *= i;
}
foreach (int i in iTol)
{
tTol *= i;
}
int timeSmisStol = tTol / tMis;
int difTM = sTol - sMis;
for (int i = 0; i < difTM; i++)
{
if (i * (difTM - i) == timeSmisStol)
{
x = i;
y = difTM - i;
}
}
}
Tuesday, December 23, 2008
REST Web Services Characteristics
Client- Server: a pull based interaction style: consuming components pull representtaions.
Stateless: each request from client to server smust contain all the information necessary to understand the request, and cannot take advantage of any stored contect on the server.
Cache:to impreove network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
Uniform interface: all resources are accessed with a generic interface(http get, post, put, delete)
Named resources -- the system is comprised of resources which are names using a URL.
interconnected resource representations -- the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
Layered componens-- intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
Stateless: each request from client to server smust contain all the information necessary to understand the request, and cannot take advantage of any stored contect on the server.
Cache:to impreove network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
Uniform interface: all resources are accessed with a generic interface(http get, post, put, delete)
Named resources -- the system is comprised of resources which are names using a URL.
interconnected resource representations -- the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
Layered componens-- intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
REST-- An architectural style, not a standard
REST is not a standard, it does use standards:
HPPT,
URL,
XML/HTML/GIF/JPEG/etc(Resource Representations),
text/xml,text/html/image/gif,
image/jpeg, etc
HPPT,
URL,
XML/HTML/GIF/JPEG/etc(Resource Representations),
text/xml,text/html/image/gif,
image/jpeg, etc
REST--- Representational State Transfer
REST Data Elements:
resource --- the intended conceptual target of a hypertext reference
resource identifier --- url, urn
REPRESENTATION ---html document, JPEG image
representation metadata -- media tyoe, last- modified time
resource metadata -- source link, alternates, vary
control data -- if modified- since, cache- control
resource --- the intended conceptual target of a hypertext reference
resource identifier --- url, urn
REPRESENTATION ---html document, JPEG image
representation metadata -- media tyoe, last- modified time
resource metadata -- source link, alternates, vary
control data -- if modified- since, cache- control
Wednesday, December 17, 2008
Function to find second highest integer
private int FindSecondHighestInt()
{
int[] testArray = { 6,4, 7, 9, 10, 3, 2 };
int highest, secondHighest, temp;
highest = testArray[0];
secondHighest = testArray[0];
for (int i = 0; i < testArray.Length; i++)
{
temp = testArray[i];
if ( temp > highest)
{
secondHighest = highest;
highest = temp;
}
else
if (temp > secondHighest)
{
secondHighest = temp;
}
}
return secondHighest;
}
_____________________________________________
{
int[] testArray = { 6,4, 7, 9, 10, 3, 2 };
int highest, secondHighest, temp;
highest = testArray[0];
secondHighest = testArray[0];
for (int i = 0; i < testArray.Length; i++)
{
temp = testArray[i];
if ( temp > highest)
{
secondHighest = highest;
highest = temp;
}
else
if (temp > secondHighest)
{
secondHighest = temp;
}
}
return secondHighest;
}
_____________________________________________
Wednesday, December 3, 2008
Compare XML data with SQL 2000 table
In SQL 2000, I wrote some code in stored procedure in SQL 2000 openxml. I need check for the data duplication before inserting the value,
Create Proc prdSaveHPCatalog(@xml TEXT, @brand varchar(200), @isExisted bit output)
AS
SET NOCOUNT ON
DECLARE @IDocumentHandle int
DECLARE @isExisted bit
EXECUTE sp_xml_preparedocument @iDocumentHandle output, @xml
---- check if the data already existed
if not exists( select 1 from OpenXML(@iDocumnetHandle, '/productCatalog/header',2) WITH (batchRunDt varchar(20) 'barchRunDt') HeaderRunTime WHERE HeaderRunTime.batchRunDt in (select batchRunDt from CategoryHeader)
)
set @isExisted = 1
Create Proc prdSaveHPCatalog(@xml TEXT, @brand varchar(200), @isExisted bit output)
AS
SET NOCOUNT ON
DECLARE @IDocumentHandle int
DECLARE @isExisted bit
EXECUTE sp_xml_preparedocument @iDocumentHandle output, @xml
---- check if the data already existed
if not exists( select 1 from OpenXML(@iDocumnetHandle, '/productCatalog/header',2) WITH (batchRunDt varchar(20) 'barchRunDt') HeaderRunTime WHERE HeaderRunTime.batchRunDt in (select batchRunDt from CategoryHeader)
)
set @isExisted = 1
Tuesday, December 2, 2008
Improving the Search Time with Binary Search Trees
The important concept to understand the BST is that ideally at each step in the algorithm that number of nodes that have to be considered has been cut in half. With an ideally arrangd BST the midpoint is the root. We than traverse down the tree, navigating to the left and right children as needed. These approaches cut the search space in half at each step. Such algorithms that exhibit this property have an asymptotic running time of log2n,
Tuesday, November 25, 2008
LINQ Query
Almonst every generic collection provided by the .NET Framework implements IEumerable. .NET controls support data binding to any IEnumerable collection.
LINQ query return results is type IEumerable T is determined by the object type of the select clause
LINQ query return results is type IEumerable
Saturday, November 8, 2008
Useful HTTP status:
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
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
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();
Subscribe to:
Posts (Atom)