Monday, 25 May 2009

SQL Server Date Time Functions

GETDATE()
Returns the current system date and time in the SQL Server standard internal format for datetime values.

DATEPART(datepart, date)
Returns an integer that represents the specified datepart of the specified date.

DATENAME(datepart, date)
Returns a character string representing the specified datepart of the specified date.

DATEADD(datepart, diffNum, date)
Returns a new datetime value based on adding an interval to the specified date.

DATEDIFF(datepart, date1, date2)
Returns the number of date and time boundaries crossed between two specified dates.

Year(date), Month(date), Day(date) are working exactly same with DATENAME(year/month/day, date)

The param datepart is the parameter that specifies on which part of the date to calculate the difference.

Saturday, 16 May 2009

ASP.NET page event ordering

  • Master page child controls initialization: All server controls contained within the master page are first initialized.
  • Content page child controls initialization: All server controls contained in the content page are initialized.
  • Master page initialization: The master page itself is initialized.
  • Content page initialization: The content page is initialized.
  • Content page load: The content page is loaded (this is the Page_Load event followed by the Page_LoadComplete event).
  • Master page load: The master page is loaded (this is also the Page_Load event followed by the Page_LoadComplete event).
  • Master page child controls load: The server controls on the master page are loaded onto the page.
  • Content page child controls load: The server controls on the content page are loaded onto the page.

UML class diagram notation

Untitledxx

Monday, 11 May 2009

Easy AJAX Callback Using ASP.NET ClientScriptManager

What I am going to show you is a fast, safe, easy way to create an AJAX callback process without manually write any JavaScript code regarding creating and handling XMLHTTPRequest object. The key is to use ASP.NET ClientScriptManager.

I will show you the sever side code first and explain to you what these code will do.

   1:  // Code behind
   2:  protected void Page_Load(object sender, EventArgs e)
   3:  {
   4:      string js = Page.ClientScript.GetCallbackEventReference(
   5:          this, 
   6:          "arg", 
   7:          "ClientCallbackFunction", 
   8:          "ctx", 
   9:          true);
  10:   
  11:      StringBuilder sb = new StringBuilder(); 
  12:      sb.Append("function DoTheCallback(arg, ctx) {"); 
  13:      sb.Append(js); 
  14:      sb.Append("}"); 
  15:      
  16:      Page.ClientScript.RegisterClientScriptBlock(
  17:          this.GetType(), 
  18:          "callbackkey", 
  19:          sb.ToString(), 
  20:          true); 
  21:  }

The first part in the code (line 4 to 9) is creating the JavaScript code which will try to invode ASP.NET AJAX engine, which will maintain a XMLHTTPRequest object for us. In line 7 we specify the callback JavaScript function name is “ClientCallBackFunction”. In line 9 we specify the AJAX calling is asynchronous. In line 6 and 8 we specify the return variable name and context variable name (I will explain this later).

In the 2nd part (line 11 to 20) we are creating the JavaScript code string which is the entry of our client side AJAX call. Line 11 to 14 are building the JavaScript code including function name, parameters, and join the code we created in the 1st part as the content of our new function.

From line 12 you can see our AJAX method has two parameters: arg and ctx. The names have to be the same string we used in line 6 and 8. I will show you the created html code and you will know why.

   1:  <script type="text/javascript"> 
   2:  //<![CDATA[
   3:  function DoTheCallback(arg, ctx) {
   4:      WebForm_DoCallback('__Page',arg,ClientCallbackFunction,ctx,null,true)}//]]>
   5:  </script>

By doing above things we have finished the hardest part. Now it is time to make our aspx page support client call back. To do so we need the Page class implement ICallBackEventHandler interface.

   1:  public partial class Ajax : System.Web.UI.Page, ICallbackEventHandler
   2:  {
   3:      private string returnValue = string.Empty;
   4:   
   5:      #region ICallbackEventHandler Members
   6:   
   7:      public string GetCallbackResult()
   8:      {
   9:          return "the result you want to pass to client";
  10:      }
  11:   
  12:      public void RaiseCallbackEvent(string eventArgument)
  13:      {
  14:          // handle the eventArgument value to different things
  15:      }
  16:   
  17:      #endregion
  18:  }

ICallBackEventHandler has two methods, the RaiseCallbackEvent method will fire first when client-side calls the AJAX method we created and inside this method we have a chance to handle different call based on the different eventArgument values.

Then the GetCallbakcResult method will be called at here you can return any string value you want. Since RaiseCallbackEvent and GetCallbakcResult are separate we have to find a way to share data between them that is why I declared a private string variable returnValue at line 3. By using so I can set the value by a proper value in RaiseCallbackEvent and return the value in GetCallbakcResult.

Note: the client side DoTheCallback method’s 2nd parameter will never be used in server side, the AJAX call will return exactly the same value to the callback method “ClientCallBackFunction”.

The last thing to do is create a callback function we declared at part one which will handle the AJAX callback call.

   1:      function ClientCallbackFunction(arg, ctx, a, b, c, d, e) {
   2:          //do your client stuff here
   3:      }

The callback method will receive only two parameters, the first one always the return value and the second one always the context string which we passed in when we begin the AJAX call. You can check the values for parameters a to c and they are always null.

ALL DONE. :)

Tuesday, 21 April 2009

Creating Tableless Sites - Why and Some Basics by Nicole Hernandez

In a time of web developers who just like to say that ‘Tables are Evil’ and can’t (or won’t) explain why, this article will attempt to give you some solid reasons that people create tableless designs. Included are six major benefits of creating tableless sites, and how to sell your desire to alter your website to a resistant manager.

Let’s begin with the benefits of a tableless layout. These are only in the order that I feel they should go in, some things are more important to other people, so rank them as you will.

Forces You To Write Well-Formed Code

You cannot have a properly made tableless layout, and use improper and non-standard code. Well, let me correct that - you can (technically you can do it) but it defeats the whole purpose. When you are creating a tableless design, you should be using standards compliant code. I think that anything that makes you get into the habit of always writing clean code is a good thing.

Faster Loading Time

This is absolutely a benfit of a tableless layout, and for several reasons. First, on a fundamental level - tables load slowly. For the most part, unless you set the height and width of your table elements, all the text has to be loaded and rendered BEFORE the table sizes itself to the page. Of course, this is what so many people loved about tables isn’t it? The fact that they were so easily sizeable. The downside is how much more time they take to load.

Okay, so the solution to that loading time is to set all the values explicitly, right? So now we see another downside. Code clutter that increases loading time. First of all, just by themselves, tables take alot of code. How many td open and close tags does your average table based layout have? Tons. Having to set all the values explicitly only adds to the page size and loading time. There are many experiments that have been done on this topic, I’ll point you toward this one that StopDesign did on a remake of the Microsoft website from a tablebased site to a tableless layout. That remake showed a 62% file size reduction of the site, and using their average hits per month for the Microsoft site, calculated that Microsoft would be saving 924 GIGS in bandwidth per day, and 329 Terabytes of bandwidth per year. For any company that pays for bandwidth, these things are important.

Easier to Read Code

If you are using standard code, semantic document conventions, and a tableless layout, your code can be so clean that it looks practically like just regular text with a few extra symbols.

That is a great benefit because it not only makes it easier for you to update, but it makes it easier for a non-technical user to make small alterations to. Additionally, if you work as a web developer in a more freelance capacity, it is common for there to be a full-time web developer who has to maintain that site. Clean and simple to read code makes that a easy transition. We like it when people leave us easy to understand code, right? Let’s return the favor.

Print Alternate Views

When you create a page using a table-layout, you are rather unfortunately locked into a certain layout. Developers who have created table-based websites, as most of us have at some point - particularly if you were in the the industry before the big tableless movement, know that you often have to create a separate printable version of your pages. This can be, needless to say, quite tiresome.

Ease of printing style control is a huge benefit with a tableless layout. You can easily create a single new printing style that applies to all your pages, instead of making them individually. That alone is a huge time saver, but there is more.

While you can control all elements with this approach, the biggest key is organization of information within the page itself. Using the example, let’s assume that the display order we want all our pages to print using the following order: The page header first, the content next, the special news after that, then the link list, and then the footer. However! We still want it to display as it would normally when viewing (meaning the header at the top, the links on the left, content in the middle, news on the right, and footer at the bottom). With a table-based layout, you would have to create a new page to do that special printing organization because the print style will read your columns left to right. With a table-less layout, you are not bound by this. You can order the content in your page however you like, and still control the way it looks… all by using the CSS only!

Additionally, because we can put the content in whatever order we want in the HTML, and then move the content blocks around for website viewing using CSS - we can have ultimate control over presentation.

That is very important because the clean code, and ability to alter presentation, means that your site can be viewable by someone on a small mobile phone screen, a PDA, in all text format can be perfect for someone using a text-to-speech reader, or a braille device, and since the code is clean, it is both backward compatible (with older browsers seeing mostly just the text) and forward compatible with new technologies to come. The flexibilty and organization leads to being able to create a powerful website that takes advantage of some of the possibilities with XHTML, and adding in support in your pages for microformats, or taking advantage of using RSS / ATOM feeds from your site to develop a base of regular readers.

Search Engine Optimization

Due to the fact that you can organize your most important content at the top of your page, without affecting the layout, your page can be better optimized for search engines. For instance, say that I have a navigation bar on the left side of the page that lists tons of parts of the site that are actually great keywords. I could move that navigation bar code higher up in my actual HTML, without changing the layout, because I’m using the CSS to position the navigation where I want it.

Those search engines can also more clearly find common words throughout your document without having to filter through code. Search engines prioritize websites that have a higher content to code ratio, so putting all your style elements into your external CSS stylesheet makes your site highly content based to a search engine. Tableless layouts, as previously mentioned, decrease page size and loading time - another bonus to search engines.

Additionally, being able to take advantage of the RSS/ATOM feeds (see the section directly above) will aid you in some new technology for site indexing as used by all search engines called ROR. (ROR is an XML format summary of your website, like a sitemap, that search engines can access for additional information about your website.)

Presentation Flexibility

Making changes to a CSS based Tableless layout is simple. You can alter the CSS file only, changing as many styles and graphics as you want. The affects cascade through all the pages on your website, and eliminate the need for manually updating many pages.

For one of the best known examples of how powerful presentation can be, you can visit the CSS Zen Garden and navigate through the ‘Select a Design’ links to see the differences. Each of the different designs uses exactly the same HTML file content. The only thing that changes is the CSS file for each one.

Selling Yourself On Standards

Sometimes knowing how to code for standards, and create flexible tableless layouts is not enough. There are some web designers who meet with difficulties from their management. Most often those difficulties are rooted in the management being unaware of the benefits of using tableless content and CSS driven layout.

If you want to design for standards, but you work for a company that is not very forward-thinking in allowing you the time to work on the changes — try this: Make them think about their pocket-book. Point out the cost saving benefits.

For instance, try grabbing a single page of existing code. Clean it up to standards. Compare the page size to before (including image optimization), and count the difference in bytes saved. Multiply that across the number of site pages, and the number of days per month. Then explain to them the amount of bandwidth cost saved monthly if this was done across the whole site. If that isn’t enough, show them how quickly you can make changes to a website once it is CSS driven, and push the idea that you will be able to change the site more rapidly when there are needed updates, and you will have more time to focus on adding in new functionality to the site - instead of spending your time doing maintenance.

Summary Hopefully, this little article will serve as a way to get you started on understanding why to use a tableless layout, what the benefits are, and you can easily take a look at Layout Gala and download just 1, or all 40 of the tableless layout examples to get you started. However, the best step toward moving to a tableless design is to slowly move your website toward a standard compliant version first, before you get rid of the tables. To get to that point, study as much on CSS as you can, read through the articles here and elsewhere on the web, and moving from table layouts to tableless will be just a matter of time.

Wednesday, 8 April 2009

DataContractSerializer V.S. XMLSerializer

Features DataContractSerializer XMLSerializer
Default mapping All the data member in the class event it is private All the public fields and Readable/Writable Properties
Need attribute [DataContractAttribute],
[DataMemberAttribute], [Serializable]
No
Order of data members Alphabetic order The order when declare them
Compatibility remoting asmx
Deserialzation do nothing Call default constructor

Saturday, 4 April 2009

Avoid web page been embedded by others

The key is using window.top. The keyword 'top' is a property in window instance which returns you the very most top parent frame instance of current window. Code Sample:
   1:  <script type="text/javascript">
   2:  function a()
   3:  {
   4:      if (window != top)
   5:      {
   6:          top.location.href = window.location.href;
   7:      }
   8:  }
   9:   
  10:  window.onload = a;
  11:  </script>

Friday, 27 February 2009

Why the SQL Server 2008 IntelliSense doesn’t work?

First of all, please check your text editor setting to make sure you have already turn on the IntelliSense function. To do so by clicking Tools > Options > Text Editor > Transact SQL > IntelliSence, and make sure the Enable IntelliSense checkbox is ticked (it should be ticked defaulted).

If the IntelliSense feature still doesn’t show then you may connected to a old version of SQL Server. The SQL Server 2008 IntelliSense only works with SQL Server 2008 database. Yeah, what a stupid reason :)

Tuesday, 24 February 2009

Managing ASP.NET Navigation

by Mike Gunderloy
04/08/2003

In an ASP.NET application, you can move between Web Forms in a variety of ways: with hyperlinks, with Response.Redirect, with Server.Transfer, or with Server.Execute. In this article, I will take a look at these various navigation methods and help you choose the appropriate one for your application.

Hyperlinks

The simplest possible way to navigate from one Web Form to another is with an HTML hyperlink control. On a Web Form, that might look like this:

<a href="WebForm2.aspx">WebForm2</a>

When the user clicks on the hyperlink, WebForm2.aspx is served up to their browser. You can use this technique just about anywhere, including on HTML pages and in classic ASP. ASP.NET gives you another alternative, the HyperLink Web Server control:

<form id="Form1" method="post" runat="server">
    <asp:HyperLink id="HyperLink1" runat="server"
    NavigateUrl="WebForm2.aspx">WebForm2</asp:HyperLink>
</form>

At runtime, this HTML has exactly the same effect as the first example, since ASP.NET renders the HyperLink Web Server control as an HTML hyperlink control. There is one key difference, though: the Web Server control can be programmed on the server side. In particular, you can change its NavigateUrl property in code, opening up the possibility of a hyperlink whose destination depends on some part of your application's state:

Private Sub Button1_Click( _ 
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
        Handles Button1.Click 
        HyperLink1.NavigateUrl = "WebForm3.aspx" 
End Sub

If the user clicks on the hyperlink after this code has executed, then the link will serve up WebForm3.aspx instead of WebForm2.aspx.

Controlling Transfers Yourself

Although hyperlinks do transfer your application from one page to another, they do so completely under the control of the user. Sometimes it's convenient to control the entire process in code yourself, including deciding when to move to another page. As it happens, ASP.NET provides three different methods to accomplish this. You can call the Redirect method of the Response object, or the Transfer or Execute methods of the Server object. Although they behave very similarly, there are differences between these three methods.

Response.Redirect

The Response.Redirect method causes the browser to connect to a specified URL. When the Response.Redirect() method is called, it creates a response whose header contains a 302 (Object Moved) status code and the target URL. When the browser receives this response from the server, it uses this header information to generate another HTTP request to the new URL. When using the Response.Redirect method, the redirection happens at the client side and involves two round trips to the server: one to request the original page, which is met by the 302 response, and then a second to request the redirected page.

Server.Transfer

The Server.Transfer method transfers execution from the current ASPX file to another ASPX file on the same web Server. When your code calls the Server.Transfer method, the current ASPX page terminates execution and the flow of control is transferred to another ASPX page. The new ASPX page still uses the response stream created by the prior ASPX page. When you use this method to navigate between pages, the URL in the browser still shows the original page, because the redirection occurs on the server side and the browser remains unaware of the transfer.

By default, the Server.Transfer method does not pass the form data or the query string of the original page request to the transferred page. But you can preserve the form data and query string of the original page by setting the optional second argument of the method to True. When you use this technique, though, you need to aware of one thing: the destination page uses the same response stream that was created by the original page, and therefore the hidden _VIEWSTATE field of the original page ends up on the second page. This causes the ASP.NET machine authentication check (MAC) to assume that the ViewState of the new page has been tampered with. Therefore, when you choose to preserve the form and query string collection of the original page, you must set the EnableViewStateMac attribute of the Page directive to False for the destination page.

Server.Execute

The Server.Execute method allows the current ASPX page to execute a specified ASPX page on the same web server. After the specified ASPX page is executed, the control transfers back to the original page from which the Server.Execute method was called. This technique of page navigation is analogous to making a function call to an ASPX page. The called ASPX page has access to the form and query string collections of the calling page, and thus you need to set the EnableViewStateMac attribute of the Page directive to False on the executed page.

By default, the output of the executed page is added to the current response stream. This method also has an overloaded version in which the output of the redirected page can be fetched in a TextWriter object (or one of its children, such as a StringWriter object) instead of added directly to the response stream. This helps you to control where to place the output in the original page.

To see how this works, create a Web Form in a test ASP.NET application and place a Button control (Button1) and a Literal control (Literal1) on the Web Form. Switch to code view and add an Imports statement for the System.IO namespace. Then add code to execute when the user clicks the button:

Private Sub Button1_Click( _
    ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
        Handles Button1.Click
        Dim sw As StringWriter = New StringWriter()
        Server.Execute("WebForm2.aspx", sw)
        Literal1.Text = sw.ToString()
End Sub

Now create a second Web Form in the same application, WebForm2.aspx. Switch to the HTML view of this second Web Form and modify its Page directive to disable ViewState checking:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm2.aspx.vb"
  Inherits="Navigate.WebForm2" EnableViewStateMac="false"%>

Switch back to design view and add some controls to the second Web Form. Now set the first Web Form as the default page and start the application. Click the button, and the controls from WebForm2 will be displayed in the area of WebForm1 where you placed the Literal control, as shown in Figure 1. You'll note from the URL and page title that the browser is still displaying WebForm1.

Screen shot.
Figure 1: A page in the browser composed by using Server.Execute to combine two source files.

There's one more thing to be aware of when you use the Server.Transfer or Server.Execute methods to navigate: the ultimate page may not be valid HTML. That's because the response to the client will contain multiple <html> and <body> tags, among other tags. Internet Explorer seems to tolerate this situation just fine, but you may want to test the results carefully if your users prefer a different browser.

Decisions, Decisions

So, given these choices for navigating from page to page, how do you select the appropriate one for your application? Here are some things to think about:

  • Hyperlinks are appropriate when you want the end user to control when navigation is performed, or to choose where to go.
  • To control the user's destination, but let them decide when to get there, use a Web Server HyperLink control whose NavigateUrl property is dynamically set.
  • Use Response.Redirect to connect to resources outside of the web server where your page is hosted.
  • Use Response.Redirect to connect to non-ASPX resources such as HTML pages.
  • Use Response.Redirect if you need to preserve a query string as an explicit part of the URL.
  • When you want to transfer control to an ASPX page residing on the same web server, you should use Server.Transfer instead of Response.Redirect because Server.Transfer will avoid the unnecessary round trip and provide better performance and a better user experience.
  • To capture the output from an ASPX page and display it at a specified location on another ASPX page, use Server.Execute.
  • If valid HTML output is essential, use Response.Redirect instead of either the Server.Transfer or Server.Execute methods.

Mike Gunderloy is the lead developer for Larkware and author of numerous books and articles on programming topics.

Monday, 23 February 2009

How to make a self-adapting size iframe

I didn't test the code on any browser yet, so if you tried and found any issue please leave a comment here. THX

<iframe id="iFrame1" name="iFrame1" width="100%" 
onload="this.height=iFrame1.document.body.scrollHeight" frameborder="0" src="index.htm">
</iframe>

Thursday, 5 February 2009

How to create WCF service manually

This article will show you how to create a WCF service by hand instead of the VS IDE. The reason of doing so is we can get rid of all the rubbish code created by VS and also it will help us understand more the infrastructure of WCF skills.

To build a WCF service manually we will create 5 assemblies:
1, Contract
2, Service
3, Host
4, ClientProxy
5, Client/WebClient

The Contract assembly (a class library) is the core of a particular WCF service. All the other 4 assemblies need a reference to this Contract.dll. The Contract assembly need a reference to System.ServiceModel so it can use all the related attributes: ServiceContract, OperationContract etc etc.

The Service assembly (a class library) includes the implementation of all the Contract Interfaces. You no need reference to System.ServiceModel for this assembly.

Now we are going to finish our first WCF service. To do so we need create a host. The Host assembly (a console app) will reference to Contract, Service, System.ServiceModel dlls and will need a Service configuration file. Below is a very sample config including two endpoints (using net.tcp and http proxy)
//Config file
<configuration>
  <system.serviceModel>
    <services>
      <service name="WcfTraining.Service.MyFirstService">
        <endpoint address="net.tcp://localhost:4002/MyFirstService"
                  binding="netTcpBinding"
                  contract="WcfTraining.Service.IHelloService"></endpoint>
        <endpoint address="http://localhost:9002/MyFirstService"
                          binding="wsHttpBinding"
                          contract="WcfTraining.Service.IHelloService"></endpoint>
      </service>
    </services>
  </system.serviceModel>
</configuration>


//Code behind
ServiceHost serviceHost = new ServiceHost(typeof(MyFirstService), 
        new Uri("net.tcp://localhost:9002/"));
serviceHost.Open();

Now you can run this Host app and a WCF service is online immediately. How easy it is. Warming: the <configSections> tag has to be always the first tag in the configure file.

Note: the second param of the ServiceHost method IMO is used to test if the Uri address is available. It could be any valid Uri address but if it is not exited in your endpoint list then it means nothing to client.

When the service is runing it is time to build our client. The first thing we need do is build a ClientProxy assembly which is a class library referenced the Contract and System.ServiceModel assemblies. Inside we simply implement the Contract Interface and inherit a generic class CProxy<Interface> which supply a ChannelFactory instance, which is used to communicate with the service. For example if we have a service named GetMessage and we are inheriting from System.ServiceModel’s inner Proxy ClientBase<> then the code will simply be:
    public class Proxy : ClientBase<IHelloService>, IHelloService
    {
        public string GetMessage(string name)
        {
            return Channel.GetMessage(name);
        }
    }

We are almost there now. The final is build our own client which could be a win app, console app or web app. The client need reference the ClientProxy, Contract and System.SerivceModel assemblies. And also the Client need a config file to tell where the service is runing. Please remembet there should be only one endpoint inside the client config file. Below is a client config sample.
  <system.serviceModel>
    <client>
      <endpoint address="net.tcp://localhost:4002/MyFirstService"
                binding="netTcpBinding"
                contract="WcfTraining.Service.IHelloService" />
    </client>
  </system.serviceModel>

Remember the abc in the config file: address, binding and Contract. Inside the Client class, simply create a instance of ClientProxy and directly call any service method you want. All Done.
Proxy proxy = new Proxy();
MessageBox.Show(proxy.GetMessage(textBox1.Text));