Saturday, September 6, 2008

Introduction to .NET3.0

In the programming field, .NET is the most successful development platform..Net Framework 2.0 is enough to satisfy for most of us. .NET Framework 3.0 came with many new and useable features. With .NET Framework 3.0, developers feel more easy when develops. In the new version of .NET, there is nothing new with CLR (Common Language runtime) but it introduces four new technologies. The latest versions of .NET are .NET Framework 3.0. Programming with .NET Framework 3.0 become more advance.
It is built with all the advantage of .NET framework 2.0, and is all set to bring in a paradigm shift in the way we write our applications today. When we go to develop any application then the main goal we set is, to create the Best application in least amount of time. The .NET Framework 3.0 will still ship with Windows Vista, and will be available down-level for Windows XP and Windows Server 2003 as planned.This newly released framework was earlier named as WinFx! .NET Framework 3.0 , compromise of familiar .NET Framework2.0 components (ASP.NET, ADO.NET, Window Forms etc).There are four new technologies in .NET Framework 3.0. These technologies are added to face the new challenge of software development. These new complementary technologies are added to address some of the most arduous challenges of contemporary software development.
The New in .NET Framework 3.0
Here .NET Framework 3.0 is same like as .NET Framework 2.0, but with some new technology and feature. The entire features are same in new framework, which was in .NET Framework 2.0.
As .NET 2.0 and 3.0 share the same CLR, everything written in .NET 2.0 works in .NET 3.0 which is an important and significant departure from previous versions. In terms of change, for those who love algebra equations the relationship can be summed anecdotally as:
The .NET Framework 3.0 achieves this objective through four key standards-based pillars corresponding to areas identified and requested by our customers. It also introduced a key new language called XAML. XAML is a declarative XML-based language that defines objects and their properties in XML allowing customers to develop workflows (WF) and immersive user experiences (WPF) declaratively.
.NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Window CardSpace + Workflow Foundation
The .NET 3.0 introducing four new foundation technologies:
Windows Presentation Foundation (WPF)
Windows Communication Foundation (WCF)
Windows Workflow Foundation (WWF)
Windows Card Space (WCS)
Lets learn more about WPF in the next Blog

Sunday, July 27, 2008

Guidelines to Creating a Good ASP.NET Application

The following are the some of the guidelines to create a good ASP.NET application.
  • Disable session when not using it. This can be done at the application level in the "machine.config" file or at a page level.
  • The in-proc model of session management is the fastest of the three options. SQL Server option has the highest performance hit.
  • Minimize the amount and complexity of data stored in a session state. The larger and more complex the data is, the cost of serializing/deserializing of the data is higher (for SQL Server and State server options).
  • Use Server.Transfer for redirecting between pages in the same application. This will avoid unnecessary client-side redirection.
  • Choose the best suited session-state provider - In-process is the fastest option.
    Avoid unnecessary round-trips to the server - Code like validating user input can be handled at the client side itself.
  • Use Page.IsPostback to avoid unnecessary processing on a round trip.
  • Use server controls in appropriate circumstances. Even though are they are very easy to implement, they are expensive because they are server resources. Sometimes, it is easier to use simple rendering or data-binding.
  • Save server control view state only when necessary.
  • Buffering is on by default. Turning it off will slow down the performance. Don't code for string buffering - Response.Write will automatically buffer any responses without the need for the user to do it. Use multiple Response.Writes rather than create strings via concatenation, especially if concatenating long strings.
  • Don't rely on exceptions in the code. Exceptions reduce performance. Do not catch the exception itself before handling the condition.
// Consider changing this...try { result = 100 / num;}catch (Exception e) { result = 0;}
// to this...if (num != 0) result = 100 / num;else result = 0;

  • Use early binding in VB.NET and Jscript code. Enable Option Strict in the page directive to ensure that the type-safe programming is maintained.
  • Port call-intensive COM components to managed code. While doing Interop try avoiding lot of calls. The cost of marshalling the data ranges from relatively cheap (i.e. int, bool) to more expensive (i.e. strings). Strings, a common type of data exchanged for web applications, can be expensive because all strings in the CLR are in Unicode, but COM or native methods may require other types of encoding (i.e. ASCII).
  • Release the COM objects or native resources as soon as the usage is over. This will allow other requests to utilize them, as well as reducing performance issues, such as having the GC release them at a later point.
  • Use SQL server stored procedures for data access.
  • Use the SQLDataReader class for a fast forward-only data cursor.
  • Datagrid is a quick way of displaying data, but it slows down the application. The other alternative, which is faster, is rendering the data for simple cases. But this difficult to maintain. A middle of the road solution could be a repeater control, which is light, efficient, customizable and programmable.
  • Cache data and page output whenever possible.
  • Disable debug mode before deploying the application.
  • For applications that rely extensively one external resource, consider enabling web gardening on multiprocessor computers. The ASP.NET process model helps enable scalability by distributing work to several processes, one on each CPU. If the application is using a slow database server or calls COM objects that access external resources, web gardening could be a solution.
  • Enumerating into collections sometimes is more expensive than index access in a loop. This is because the CLR can sometimes optimize array indexes and bounds checks away in loops, but can't detect them in for each type of code.
  • JScript .NET allows methods within methods - to implement these in the CLR required a more expensive mechanism which can be much slower, so avoid them by moving inner methods to be just regular methods of the page.
  • Do a "pre-batch" compilation. To achieve this, request a page from the site.

ASP.NET Life Cycle and Best Practices

When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. When we try to build ASP.NET pages and this execution cycle is not taken into account, we can cause a lot of headaches for ourselves. However, when used and manipulated correctly, a page's execution cycle can be an effective and powerful tool. Many developers are realizing that understanding what happens and when it happens is crucial to effectively writing ASP.NET pages or user controls.
I'll set the stage with a simple submission form written in ASP.NET with C#. The page is loaded for the first time and has several server-side Web controls on it. When the Web server receives a request for the page, it will process our Web controls and we will eventually get rendered HTML. If we follow some tips, we can increase the performance of the page.


The following are the main ten steps in the ASP.NET page life cycle.

1. Object Initialization
A page's controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file, the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.

2. Load Viewstate Data
After the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden control that is passed from page request to page request. As you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. This event can be overridden using the LoadViewState method and is commonly used to customize the data received by the control at the time it is populated.

3. LoadPostData Processes Postback Data
During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that submitted data. The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such as several custom user controls existing on a single page. After the LoadPostData event triggers, the RaisePostDataChanged event is free to execute (see below).

4. Object Load
Objects take true form during the Load event. All object are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. During Load, coded logic, such as arithmetic, setting control properties programmatically, and using the StringBuilder to assemble a string for output, is also executed. This stage is where the majority of work happens. The Load event can be overridden by calling OnLoad.

5. Raise PostBack Change Events
As stated earlier, this occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object's data has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data.

6. Process Client-Side PostBack Event
After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series of postback events due to the accuracy of the data that is rendered to the browser. Controls that are changed during postback should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should always be reflected in the resulting page. The RaisePostBackEvent can be trapped by catching RaisePostBackEvent.

7. Prerender the Objects
The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender.

8. ViewState Saved
The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not. You can override this step by using SaveViewState.

9. Render To HTML
The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render them into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only.

10. Disposal
After the page's HTML is rendered, the objects are disposed of. During the Dispose event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. You can override Dispose, as well as Render by setting the appropriate selection in the object parameter.

SQL Indexes

A SQL View is a virtual table, which is based on SQL SELECT query. Essentially a view is very close to a real database table (it has columns and rows just like a regular table), except for the fact that the real tables store data, while the views don’t. The view’s data is generated dynamically when the view is referenced. A view references one or more existing database tables or other views. In effect every view is a filter of the table data referenced in it and this filter can restrict both the columns and the rows of the referenced tables.Here is an example of how to create a SQL view using already familiar Product and Manufacturer SQL tables:

CREATE VIEW vwAveragePrice AS
SELECT Manufacturer, ManufacturerWebsite, ManufacturerEmail, AVG(Price) AS AvgPriceFROM Manufacturer JOIN ProductON Manufacturer.ManufacturerID = Product.ManufacturerIDGROUP BY Manufacturer, ManufacturerWebsite, ManufacturerEmail

A view can be referenced and used from another view, from a SQL query, and from stored procedure. You reference a view as you would reference any real SQL database table:

SELECT * FROM vwAveragePrice

Master Pages - ASP.NET 2.0

Master Pages - The Master Pages feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.

Master and Content Pages
Defining a Master Page is just like defining a normal page. Master Pages can contain markup, controls, or code, or any combination of these elements. However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A ContentPlaceHolder can also contain default content, just in case the derive page does not need to override this content. The syntax of a ContentPlaceHolder control is given below:
<%-- ContentPlaceHolder control --%>

<%-- ContentPlaceHolder with default content --%>

Welcome to my florist website!



To differentiate a Master Page from a normal page, a Master Page is saved under the .master file extension. A page can derive from a Master Page by defining a MasterPageFile attribute on its Page directive, as demonstrated below. A page that is associated to a Master Page is called a Content Page.
<%@ Page MasterPageFile="Site.master" %>

Content Page can declare Content controls that specifically override content placeholder sections in the Master Page. A Content control is associated to a particular ContentPlaceHolder control through its ContentPlaceHolderID property. A Content Page may only contain markup and controls inside Content controls; it cannot have any top-level content of its own. It can, however, have directives or server-side code.
<%@ Page MasterPageFile="Site.master" %>

With sunshine, water, and careful tending, roses will bloom several times in a season.





Accessing a Master Page from CodeIn addition to overriding content, it is possible for a Content Page to programmatically access its Master Page. A Content Page creates a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, specifying the virtual path to the master page:
<%@ MasterType VirtualPath="Site.master" %>

The Content Page can then reference the Master Page using the Master property of the Page class:

Master.FooterText = "This is a custom footer"Dim ad As AdRotator = Master.FindControl("MyAdRotator")

Triggers - SQL

A trigger is a database object that is Bind to a table. In many aspects it is similar to a stored procedure and are often referred to as a "special kind of stored procedure." SQL Server 2000 greatly enhances trigger functionality, extending the capabilities of the triggers you already know and love, and adding a whole new type of trigger, the "Instead Of" trigger.
When to Use Triggers
There are many reasons to use triggers. If you have a table which keeps a log of messages, you may want to have a copy of them mailed to you if they are urgent. If there were no triggers you would have some solutions, though they are not as elegant. You could modify the application(s) logging the messages. This means that you might be redundantly coding the same thing in every application that logs messages.
Tables can have multiple triggers. The CREATE TRIGGER statement can be defined with the FOR UPDATE, FOR INSERT, or FOR DELETE clauses to target a trigger to a specific class of data modification actions. When FOR UPDATE is specified, the IF UPDATE (column_name) clause can be used to target a trigger to updates affecting a particular column.
SQL Server 2000 greatly enhances trigger functionality, extending the capabilities of the triggers you already know and love, and adding a whole new type of trigger, the "Instead Of" trigger.
SQL Server 2000 has many types of triggers:
  1. After Trigger
  2. Multiple After Triggers
  3. Instead Of Triggers
  4. Mixing Triggers Type

Stored Procedures - SQL

Stored Procedures – What are they?
Stored procedure is a set of pre-defined Transact-SQL statements, used to perform a specific task. There can be multiple statements in a stored procedure, and all the multiple statements are clubbed in to one database object.

How to create a stored procedure?
Creating a stored procedure is as easy as running the “Create Procedure” statement followed by the SQL script. You can run your Create Procedure statement from the SQL Query Analyzer, or can use the New Procedure menu item in the Enterprise Manager.
The simplest skeleton of a stored procedure.
CREATE PROC procedure_name [ { @parameter data_type } ] AS sql_statement

stored procedure includes
1. A CREATE PROC (CREATE PROCEDURE) statement;
2. The procedure name;
3. The parameter list
4. And the SQL statements.

Advantages!
1. Performance
All the SQL statements, that you send to your database server passes through a series of actions, called execution. These are the steps that your SQL statement passes through before the data is returned to the client.
2. Security
Stored procedures provide significant benefits when it comes to security. By using a stored procedure, you can grant permissions to certain users to access data, reducing the immense coding that you need to do in your client applications. This is one of the best ways to control access to your data.
3. Modifications/Maintenance
If you use stored procedures for database access, any change in the database can be reflected on to the client application without much effort. This is because you know exactly where the data is accessed from, and you also know exactly where you need to alter. This means no scuba diving in to thousands of lines of source code to identify areas where you need to alter and no headache of re-deploying the client application.
4. Minimal processing at the client.
When creating a client/server application, normally it was the client who took care of the integrity of data that went in to the database. Managing Primary Keys, Foreign keys, cascaded deletion everything was done by the client, and the database server just had to store data given by the client.
5. Network traffic
Client applications always have to request/send data from the database server. These data are sent as packets, and travel through the network to the server.