Friday, October 13, 2006

SQL Subqueries

INSERT INTO TableA (PosID, PosValue, DataDate) SELECT PosID, PosValue, DataDate FROM TableB WHERE DataDate = '2006-10-6' AND PosID = 'TAEE1'

^ Values (A,B,C)部分替换成一个SELECT A,B,C语句便可。


UPDATE TableA SET PosValue = (SELECT PosValue FROM TableB WHERE
DataDate = '2006-10-6' AND PosID = 'TAEE1' ) WHERE PosID = 'TAEE1' AND DataDate = '2006-10-6'


^
SELECT OUID, (SELECT ID, OUName FROM Accounts_OU WHERE ID = A.OUID ORDER BY ID) AS OUName FROM BizMgtStationOrder A WHERE PipeLineID = " & XXX & " ORDER BY OUID"


d Subquery Fundamentals

A subquery is a SELECT query that returns a single value and is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. A subquery can be used anywhere an expression is allowed. In this example a subquery is used as a column expression named MaxUnitPrice in a SELECT statement.

SELECT Ord.OrderID, Ord.OrderDate,
(SELECT MAX(OrdDet.UnitPrice)
FROM Northwind.dbo.[Order Details] AS OrdDet
WHERE Ord.OrderID = OrdDet.OrderID) AS MaxUnitPrice
FROM Northwind.dbo.Orders AS Ord

A subquery is also called an inner query or inner select, while the statement containing a subquery is also called an outer query or outer select.

Many Transact-SQL statements that include subqueries can be alternatively formulated as joins. Other questions can be posed only with subqueries. In Transact-SQL, there is usually no performance difference between a statement that includes a subquery and a semantically equivalent version that does not. However, in some cases where existence must be checked, a join yields better performance. Otherwise, the nested query must be processed for each result of the outer query to ensure elimination of duplicates. In such cases, a join approach would yield better results. This is an example showing both a subquery SELECT and a join SELECT that return the same result set:

/* SELECT statement built using a subquery. */
SELECT ProductName
FROM Northwind.dbo.Products
WHERE UnitPrice =
(SELECT UnitPrice
FROM Northwind.dbo.Products
WHERE ProductName = 'Sir Rodney''s Scones')

/* SELECT statement built using a join that returns
the same result set. */
SELECT Prd1.ProductName
FROM Northwind.dbo.Products AS Prd1
JOIN Northwind.dbo.Products AS Prd2
ON (Prd1.UnitPrice = Prd2.UnitPrice)
WHERE Prd2.ProductName = 'Sir Rodney''s Scones'

A subquery nested in the outer SELECT statement has the following components:
A regular SELECT query including the regular select list components.
A regular FROM clause including one or more table or view names .
An optional WHERE clause.
An optional GROUP BY clause.
An optional HAVING clause.

The SELECT query of a subquery is always enclosed in parentheses. It cannot include a COMPUTE or FOR BROWSE clause, and may only include an ORDER BY clause when a TOP clause is also specified.

A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. Up to 32 levels of nesting is possible, although the limit varies based on available memory and the complexity of other expressions in the query. Individual queries may not support nesting up to 32 levels. A subquery can appear anywhere an expression can be used, if it returns a single value.
If a table appears only in a subquery and not in the outer query, then columns from that table cannot be included in the output (the select list of the outer query).

Statements that include a subquery usually take one of these formats:


WHERE expression [NOT] IN (subquery)
WHERE expression comparison_operator [ANY ALL] (subquery)
WHERE [NOT] EXISTS (subquery)

In some Transact-SQL statements, the subquery can be evaluated as if it were an independent query. Conceptually, the subquery results are substituted into the outer query (although this is not necessarily how Microsoft® SQL Server™ actually processes Transact-SQL statements with subqueries).
There are three basic types of subqueries, those that:
Operate on lists, introduced with IN or those that a comparison operator modified by ANY or ALL.
Are introduced with an unmodified comparison operator and must return a single value.
Are existence tests introduced with EXISTS.


Wednesday, October 11, 2006

Label and Label Cloud / Tag and Tag Cloud

Making and sending HTML email

@ The Process of Creating and Sending an E-mail Message: To create and send an e-mail message, follow these steps:

  1. Create a MailMessage object. MailMessage and other mail-related classes are in the System.Net.Mail namespace.
  2. If you did not specify the recipients in the MailMessage constructor, add them to the MailMessage object.
  3. If you need to provide multiple views (such as plain text and HTML), create AlternateView objects and add them to the MailMessage object.
  4. If necessary, create one or more Attachment objects and add them to the MailMessage object.
  5. Create an SmtpClient object, and specify the SMTP server.
  6. If the SMTP server requires clients to authenticate, add credentials to the SmtpClient object.
  7. Pass your MailMessage object to the SmtpClient.Send method. Alternatively, you can use SmtpClient.SendAsync to send the message asynchronously.

How to create a MailMessage

^ 一定要首先创建空的MailMessage,然后把MailMessage.ToMailMessage.FromMailMessage.SubjectMailMessage.Body四个property依次添加到MailMessage中。还可以添加MailMessage.CcMailMessage.Bcc

^ 因为每次发送邮件不一定会发给多少个人,所以写程序时不区分发给单人还是多人的情况。把所有得到的收件人地址都放进一个MailAddressCollection中。

@ BCC stands for "blind carbon copy".

@ The problem with BCC is that spam filters frequently block messages that do not have the recipient's email address in the From header, Therefore, if you use BCC, the message will very likely be filtered.

How to create HTML email?

@ To create an HTML email message, supply HTML-tagged content for MailMessage.Body and set MailMessage.IsBodyHtml attribute to True.
Dim OneMailMessage = New MailMessage
String OneMailMessageHtmlBody = "XHTML codes ..."
OneMailMessage.IsBodyHtml = True
OneMailMessage.Body = OneMailMessageHtmlBody

@ Most email clients will ignore the head section, and will ignore any client-side scripts, and will not automatically download images from Web sites.

@ To embed images into an HTML message so that they appear when the user clicks the message (without requiring the user to explicitly choose to download images): first creat an HTML message using AlternateView and then add images using LinkedResource classes.

^ 因为有的邮件客户端或者服务器会阻止图片内容,或者只支持普通文本格式的邮件,或者用户设定只接受文本邮件,所以需要提供alternate view以根据情况显示邮件内容。

e 4guysfromrolla.com Sending Email in ASP.NET 2.0
e 4guysfromrolla.com Sending Email in ASP.NET 2.0: HTML-Formatted Emails, Attachments, and Gracefully Handling SMTP Exceptions

e Complete FAQ for the System.Net.Mail namespace found in .NET 2.0

Globalization: Culture, Region, Date, Number

@ How to detect a user's current culture information?
Using the CurrentCulture property of the executing thread's CurrentThread property. i.e.,
Dim UserCulture As CultureInfo = Thread.CurrentThread.CurrentCulutre
Console.WriteLine("The current culture of this application is : " & UserCulutre.Name)

@ How to set the current culture?
Just specify a different value to the CurrentCulture property of the CurrentThread property of the Thread class. i.e.,
Thread.CurrentThread.CurrentCulutre = New CultureInfo("es-VE")

@ The RegionInfo class provides specific information about a particular country or region.

@ The DateTimeFormatInfo class provides a comprehensive set of methods and properties to handle and respond to the dates of different culutres.
Dim UserCulture As CultureInfo = New CultureInfo("zh-CN")
Dim Days() As String = UserCulture.DateTimeFormat.DayNames
For Each Day As String In Days
Console.WriteLine("Culture : " & UserCulture.Name)
Console.WriteLine("Day Name : " & Day)
Next

Shared Method V.S. Instance Method

@ Shared means "shared between all instances of a class", which is also called static.

Tuesday, October 10, 2006

Declarative Language V.S. Imperetive Language

@ The ASP.NET markup language (that is, the ASPX language) is increasingly being recognized as a declarative programming language.

@ Declarative programming is quite a different programming model.
@ When you program with an imperative language, you reach a desired goad by providing the specific operations required to reach the goal. (That is, you tell the computer how to reach your goal.)
@ When you program with a declarative language, you specify your goal and a compiler or interpreter uses its predefined algorithms to determine the appropriate operations to reach that goal. (That is, the computer find a way to reach your goal.)

^ 这就像我曾经说过的,我只在乎是否实现了一个function,而不在乎这个function是怎么被实现的。

e The Right Way to do Ajax is Declaratively
e Declarative V.S. Imperative Programming
e Declarative programming
e del.icio.us/tag/declarative

Manipulating Microsoft Office

Excel How to
Office Wiki
Joe Andreshak (MS) http://blogs.officezealot.com/joe/
Clinick's Clinic http://weblogs.asp.net/andrewclinick/
John Durant (MS) http://blogs.msdn.com/johnrdurant
Mark Harrison (MS) http://blog.markharrison.co.uk/
Laura John (MS) http://blogs.msdn.com/lauraj
Eric Lippert (MS) http://blogs.msdn.com/ericlippert
Andrew May (MS): http://blogs.msdn.com/andrew_may
Chris Kunicki http://blogs.officezealot.com/chris
Charles Maxson http://blogs.officezealot.com/charles
Office Zealot Blogz http://www.officezealot.com/BlogHome.aspx
Frank Rice (MS) http://blogs.msdn.com/frice
Peter's Blog: http://blog.jausovec.net/
Peter Torr: http://weblogs.asp.net/ptorr/

About VB.NET Procedure / Method

@ A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.

@ Types of Procedures
Visual Basic uses several types of procedures:
· Sub Procedures perform actions but do not return a value to the calling code.
· Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by an occurrence in a program.
· Function Procedures return a value to the calling code. They can perform other actions before returning.
· Property Procedures return and assign values of properties on objects or modules.
· Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-defined class or structure.
· Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters, so the calling code can pass specific data types each time it makes a call.

Reflection到底是个啥东西?

@ Code in the CLR is packaged in an assembly. Even though it is often thought of as a file, an assembly is actually a logical container for different parts of the data the CLR needs to execute code.

@ These parts of data of an assembly include: Assembly metadata, Type metadata, Intermediate Language code, and Resources.

@ Assembly Metadata includes data that defined the assembly, such as the name, version, strong name, and culture information. Assembly metadata is also called manifest.

@ Type Metadata is the information describes what a type looks like, including the namespace, class name, members (methods, properties, constructors, etc.), and parameters.

@ Most of the time, all these parts of an assembly are compiled into a single file.

@ Assemblies are containers for modules, and modules are containers for types.

^ 我啥时候会用的上Reflection呀?

e C-sharp reflection: Save development time throughout the project life-cycle

Web API V.S. Web Services

@ Web APIs are application programming interfaces that can be called over standard Internet protocols.

@ It is helpful to think of a Web API as a series of Web services, each of which has one or more procedures that can be called using the Internet.

@ Web APIs are typically a related collection of Web services.

Monday, October 09, 2006

Callback

Saturday, October 07, 2006

Page.IsPostBack

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Page.IsPostBack是用来检查目前网页是否为第一次加载,
'当使用者第一次浏览这个网页时page.ispostback 会传回false,不是第一次浏览这个网页时就传回true;
'所以当我们在page_load 事件中就可以使用这个属性来避免做一些重复的动作。
'此处,如果是第一次加载,则要执行下列代码,否则就不执行,所以要保证If true Then
If Not Page.IsPostBack Then
......
End If
End Sub

The constructor method of VB.NET

A constructor is a method that runs when a new instance of the class is created.
In Visual Basic, the constructor method is always named Sub New:


Class Person
Private CreateTime As Date
Sub New()
' Display a diagnostic message.
Console.WriteLine("A new instance of Person is being created.")
' Remember when this instance was created.
CreateTime = Now
' Perform other initialization chores.

End Sub
End Class

Cross Page Postback in ASP.Net 2.0

Exporting Data to Excel

Original Address: http://www.developer.com/net/asp/article.php/3633891

A common request of users is to be able to download data for use in Microsoft Excel. This is actually fairly easy to accomplish without a lot of extra work.

I do most of my database work with DataTable objects, as I don't need the overhead of a DataSet. I also have a Database wrapper class that is able to easily retrieve data from a SQL Server database. Once I use my function to get my DataTable, I can start exporting the data. For this example, however, I'll use the traditional SqlDataAdapter method to retrieve the data initially.

There are a few tricks to making this work.
First, you have to create an ASPX page with no HTML content in it. The only thing that should be in the ASPX page is the Page directive at the top.
The second trick is to clear the existing content and send down a new content type. For Excel, you use a content type of application/vnd.ms-excel. This tells your Web browser to expect something that can be handled within Excel.
The third trick is to send down the data tab-delimited per column and a newline at the end of each row.
After that, Excel does the rest of the work for you.

Tuesday, October 03, 2006

ASP.NET Inline Data-Binding Syntax

@ One-way data binding:

Eval("", "")

第一部分是Item的名称;第二部分是一个Formatter。

@ Two-way data binding:
<%# Bind("Name", "{0:mm dd yyyy}") ) %>
第一部分是Item的名称;第二部分是一个Formatter。

Sunday, October 01, 2006

.NET Framework Application Domain

@ How to create an Application Domain?
@ To create an AppDomain, call static AppDomain.CreateDomain("YourAppDomain") method.
@ To load an assembly in an application domain, call AppDomain.ExecuteAssembly("TheAssemblyName.exe") method.
@ To unload an application domain, call static AppDomain.Unload(YourAppDomainReference) method.

Dim OneAppDomain As AppDomain = AppDomain.CreateDomain("MyFirstDomain")
Console.WriteLine(" Host domain: " + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine("Child domain: " + OneAppDomain.FriendlyName)

@ Create an application domain anytime you want to launch an assembly.

Saturday, September 30, 2006

To collapse and hide a section of code in Visual Studio 2005

The #Region directive enables you to collapse and hide sections of code in Visual Basic files. The #Region directive lets you specify a block of code that you can expand or collapse when using the Visual Studio code editor. The ability to hide code selectively makes your files more manageable and easier to read. For more information, see How to: Outline and Hide Code.

#Region directives support code block semantics such as #If...#End If. This means they cannot begin in one block and end in another; the start and end must be in the same block. #Region directives are not supported within functions.

To collapse and hide a section of code
Place the section of code between the #Region and #End Region statements, as in the following example:

#Region "This is the code to be collapsed"
Private components As System.ComponentModel.Container
Dim WithEvents Form1 As System.Windows.Forms.Form

Private Sub InitializeComponent()
components = New System.ComponentModel.Container
Me.Text = "Form1"
End Sub
#End Region


The #Region block can be used multiple times in a code file; thus, users can define their own blocks of procedures and classes that can, in turn, be collapsed. #Region blocks can also be nested within other #Region blocks.

Note
Hiding code does not prevent it from being compiled and does not affect #If...#End If statements.

^ 在一个method范围内是不能使用Region的,如果要实现“收起放开”,需要使用CTRL+M and then CTRL+H以及CTRL+M and then CTRL+U.

@ Hide Selection
Collapses the currently selected text. Text must be selected to use this command. Shortcut keys are CTRL+M and then CTRL+H.

@ Stop Hiding Current
Removes the outlining information for the currently selected user-defined region. Shortcut keys are CTRL+M and then CTRL+U.
Note This command becomes available in Visual C# and Visual J# when Automatic Outlining is turned off or Stop Outlining is selected. Not available in Visual Basic.

Friday, September 29, 2006

Determining the Number of Days in a Month with Javascript

ATTENTION: The following words are quoted from great work of Mr. Charlie published at www.bigbold.com on Thu May 25 08:02:48 GMT 2006

Essentially, writing some code to determine the number of days in a given month of a given year with javascript is not the worlds most difficult task. It is the type of exercise that one would expect to be given as a newbie developer during a lab or lecture. The solution normally involves determining if the month is February, an month with 30 days or a month with 31 days, then (if February) checking if the year is a leap year. All these tests add up, however, and add several lines of code to your .js file. They are also unnecessary!

Apparently, the javascript Date function allows you to overflow the day number parameter that you pass, creating a date in the next month. Deliberately overflowing the day parameter and checking how far the resulting date overlaps into the next month is a quick way to tell how many days there were in the queried month. Here is a function that does this:

function daysInMonth(iYear, iMonth) {
return (32 - new Date(iYear, iMonth, 32).getDate());
}


N.B.: iMonth is zero based, so 0 represents January, 1 represents February, 2 represents March and 11 represents December. iYear is not zero based, this is the actual calendar year number. (2006 is actually 2006)

Pray that the browser developers know the correct way to determine whether a year is a leap year! (It's more complicated than a simple mod 4 == 0) Here is a quote from Wikipedia's page on leap years: " The Gregorian calendar, the current standard calendar in most of the world, adds a 29th day to February in all years evenly divisible by 4, except for centennial years (those ending in '00'), which receive the extra day only if they are evenly divisible by 400. Thus 1600, 2000 and 2400 are leap years but 1700, 1800, 1900 and 2100 are not. "

How does this function work? It is quite simple. When the Date() function is given a day number that is greater than the number of days in the given month of the given year, it wraps the date into the next month. The getDate() function returns the day of the month, starting from the beginning of the month that the date is in. So, day 32 of March is considered to be day 1 of April. Subtracting 1 from 32 gives the correct number of days in March!


API : Internet Business from where?

I think I might should start my Internet Business from and on the great ones' APIs, actually, mighty services and resources.

Google API
Flickr API
Live API
ebay API
amazon API
Yahoo API

不是曾经就告诉过自己一定要站在巨人的肩膀上发展吗?为什么不通过API呢?

Thursday, September 28, 2006

ASP.NET Server Control File Upload

Reference:
http://www.codeguru.com/csharp/sample_chapter/print.php/c12593__1/

Internet Application Architecture : Tiers ? Layers?

这两天考虑最多的一个问题是Tiers/Layers问题。这是一个争论广泛似乎没有答案的问题。下午试用Google Pages做网站时受了启发。任何一种架构,存在了就是合理的,就应是满足了某种需求解决了某类问题。所以,为什么一定要为所有的问题找一个统一的解决放案呢?互联网网站有大有小、有简单的有复杂的、有专一的有综合的、有长久发展的有临时实验的,千姿百态,共性的东西其实并不多。这样的话,寻找一种能够包容所有问题域的解决方案似乎就挺不务实的。一个方案解决所有问题,听上去似乎很好:统一了开发过程。可是执行起来就有问题了:无论网站大小,都用同样的架构,写同样多的基础代码。如果做十个网站有八个是短平快且不相似的,那开发成本是提高了而不是降低了。

大型的网站,像Amazon,ebay,Taobao,Yahoo,My Space,其架构、技术、开发都是工业级的,自有Enterprise的方法和技术。
专一的网站:Flickr,Delicious,BaseCamp等所谓Web2.0网站,有Getting Real思想指导下的过程。
普通的网站,比如那些企业门户,又可以用简单快速的技术实现。
个人的网站:比如Blog,比如个人portal,更可以根本不需要编程就实现,比如使用Windows Live Space,Google Pages。

不同类型的网站,可以使用不同的架构、不同的语言、不同的过程来实现。所以,对于Tiers/Layers问题,如果说Case by Case不是一个好的答案,那么Type by Type应该算是一个还好的答案。





Recommended Blogs on Architecture

Web Applications: N-Tier vs. N-Layer - Benefits and Trade-Offs

Should all apps be n-tier?

Avoid Chatty Interfaces Between the Tiers in Your ASP.NET Web Application

What is n-Tier Architecture?

N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005

http://msdn.microsoft.com/architecture/shareideas/sharebrowseblogs/

Wednesday, September 27, 2006

Transact-SQL

@ Database developers must hava a thorough knowledge of Transact-SQL to read data from and write data to SQL Server database. Using Transact-SQL is the only way to work with the data.

@ Transact-SQL is a fairly simple language; Yet many develpers don't spend the time to understand it, and they end up writing less-than-desirable code.
@ The key to creating well-perfomring Transact-SQL queries is to think in terms of sets instead of row-by-row operations, as you would be in a procedural system.

@ A database developer must ensure that queryies use as few tables as possible to statify the data requirements.

@ Avoid the temptation of creating monolithic, do-everything queries that can be sued to statisfy the requirements of many different parts of the applicaton, or that return data from additional tables just in case it might be necessary in the future.

Tuesday, September 26, 2006

ASP.NET Architecture BLL

How to centralize these business rules into a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL.
In a real-world application, the BLL should be implemented as a separate Class Library project; however, for these tutorials we'll implement the BLL as a series of classes in our App_Code folder in order to simplify the project structure.

ASP.NET Atlas Tutorial Video

http://www.asp.net/learn/videos/default.aspx?tabid=63

http://weblogs.asp.net/scottgu/archive/2006/08/25/Great-New-Atlas-Videos-Published-_2800_All-Free_2900_.aspx