10/13/09

WCF

1. What is WCF?

WCF (Windows Communication Foundation) is a unification of technology.

Which Units the following technologies.

a. Net Remoting
b. MSMQ
c. Webservice

d. COM+

It is based on SOA(Service oriented Architecture)
.

There are a few articles about the WCF ABC's (1, 2)but the short story is that you always have to remember:
2. What is ABC in WCF?


  1. A stands for Address
  2. B stands for Binding
  3. C stands for Contract
Address ( Where)

An address indicates where we can find this service. Address is a URL(http://mydomain.com/Myservice.asmx), which points to the location of the service.

WCF can provided addresses for the following protocols:
  1. HTTP
  2. TCP
  3. NamedPipe
  4. Peer2Peer
  5. MSMQ

Binding (How)

Bindings determine how this end can be accessed. It determines how communications are done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.

Contract (What)

Contract is an agreement between two or more parties. It defines the protocol how the client should communicate with your service. Technically, it describes parameters and return values for a method.

10/12/09

Events in Asp.net Life Cycle of the Page

PreInit: All the Pre and Post events are introduced as part of .NET Framework 2.0. As the name suggests, this event is fired before the Init method is fired. Most common functionalities implemented in this method include:

1. Check the IsPostBack property
2. Set the master page dynamically
3. Set the theme property of the page dynamically
4. Read or Set the profile property values
5. Re-create the dynamic controls

Init: This event is raised after all controls in the page are initialized and any skin settings have been applied. This event is used to read or initialize control properties. It can be used to register events for some controls for which the events are not specified in the aspx page.
Ex: OnClick event of the Button can be registered in the Init rather than specifying in the OnClick property of the Button in the aspx page.

InitComplete: Use this event for processing tasks that require all initialization to be complete.

PreLoad: Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load: The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections.

Control events: Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

LoadComplete: Use this event for tasks that require that all other controls on the page be loaded.

PreRender: This is the last event raised before the HTML code is generated for the page. The PreRender event also occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

SaveStateComplete: Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
Use this event to perform tasks that require view state to be saved, but that do not make any changes to controls.

Render: This is the stage where the HTML code for the page is rendered. The Page object calls the Render method of each control at this stage. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.

UnLoad: This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

State Management in Asp.net

Purpose

State management is the process by which you maintain state and page information over multiple requests for the same or different pages.


Types of State Management

There are 2 types State Management:

1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

2. Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

Implementation Procedure


Client – Side State Management:

View State:
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML:

input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value=" pmgnqjqhlh66cdw="="


Encrypting of the View State: You can enable view state encryption to make it more difficult for attackers and malicious users to directly read view state information. Though this adds processing overhead to the Web server, it supports in storing confidential information in view state. To configure view state encryption for an application does the following:











Alternatively, you can enable view state encryption for a specific page by setting the value in the page directive, as the following sample demonstrates:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%>


View State is enabled by default, but if you can disable it by setting the EnableViewState property for each web control to false. This reduces the server processing time and decreases page size.
Reading and Writing Custom View State Data:
If you have a value that you’d like to keep track of while the user is visiting a single ASP.NET Web page, adding a custom value to ViewState is the most efficient and secure way to do that. However, ViewState is lost if the user visits a different Web page, so it is useful only for temporarily storing values.
Example: Determine the time of last visit to the page

// Check if View State object exists, and display it if it does

If (ViewState ["lastVisit"]!= null)

Label1.Text = (string)ViewState["lastVisit"]; else

Label1.Text = "lastVisit ViewState not defined.";

// Define the ViewState object for the next page view ViewState.Add("lastVisit", DateTime.Now.ToString());





Control State: If you create a custom control that requires ViewState, you can use the ControlState property to store state information for your control. ControlState allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. To use control state in a custom control, your control must override the OnInit method and call the Register-RequiresControlState method during initialization and then override the SaveControl-State and LoadControlState methods.

Hidden fields: ViewState stores information in the Web page using hidden fields. Hidden fields are sent back to the server when the user submits a form; however, the information is never displayed by the Web browser (unless the user chooses to view the page source). ASP.NET allows you to create your own custom hidden fields and store values that are submitted with other form data. A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. You can use hidden fields only to store information for a single page, so it is not useful for storing session data. If you use hidden fields, you must submit your pages to the server using Hypertext Transfer Protocol (HTTP) POST (which happens if the user presses a button) rather than requesting the page using HTTP GET (which happens if the user clicks a link). Unlike view state data, hidden fields have no built-in compression, encryption, hashing, or chunking, so users can view or modify data stored in hidden fields.

Cookies: Web applications can store small pieces of data in the client’s Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages.

Reading and Writing Cookies:
A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request.
Create a cookie -> add a value to the Response.Cookies HttpCookieCollection.
Read a cookie -> read values in Request.Cookies.
Example:
// Check if cookie exists, and display it if it does

if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains client-side script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);

else Label1.Text = "No value defined";

// Define the cookie for the next visit Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);


If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser.

To delete a cookie, overwrite the cookie and set an expiration date in the past. You can’t directly delete cookies because they are stored on the client’s computer.
Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a different hostname. You can control a cookie’s scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates:

Example:
Response.Cookies["lastVisit"].Path = "/Application1"; 


Through this the scope is limited to the “/Application1” folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement:
Example:
Response.Cookies[“lastVisit”].Domain = “Contoso”;

Storing Multiple Values in a Cookie:
Though it depends on the browser, you typically can’t store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates:
Example:

Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"].Value = "Tony";

Response.Cookies["info"]["border"].Value = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);


Running the code in this example sends a cookie with the following value to the Web browser:
(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)

Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example:
http://support.microsoft.com/Default.aspx?kbid=315233
In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named “kbid,” and a value for that parameter, “315233.” Query strings can also have multiple parameters, such as the following real-world URL, which specifies a language and query when searching the Microsoft.com Web site:
http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world

Value Name | ASP.NET Object | Value
mkt | Request.QueryString[“mkt”] | en-US
setlang | Request.QueryString[“setlang”] | en-US
q | Request.QueryString[“q”] | hello world

Limitations for Query Strings:
1. Some Browsers and client devices impose a 2083 – character limit on the length of the URL.
2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldn’t add query strings to button targets in forms.
3. You must manually add query string values to every hyperlink that the user might click.
Example:
Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) +

", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) +

", Page: " + Server.HtmlEncode(Request.QueryString["page"]);


Server - Side State Management:

Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.

ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:

a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.

b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.

c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.


Session State: ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary.

You can use session state to accomplish the following tasks:
i. Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit.

ii. Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information.

iii. Raise appropriate session management events. In addition, you can write application code leveraging these events.

ASP.NET session state supports several different storage options for session data:

a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.

b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.

c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.

d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.

e. Off Disables session state. You should disable session state if you are not using it to improve performance.

Advantages


Advantages of Client – Side State Management:

1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

7/28/09

Object Initializers and Collection Initializers

New C# Language Feature: Automatic Properties

If you are a C# developer today, you are probably quite used to writing classes with basic properties like the code-snippet below:

public class Person {

private string _firstName;
private string
_lastName;
private int
_age;

public string
FirstName {

get {
return _firstName;
}
set {
_firstName
= value;
}
}

public string LastName {

get {
return _lastName;
}
set {
_lastName
= value;
}
}

public int Age {

get {
return _age;
}
set {
_age
= value;
}
}
}

Note about that we aren't actually adding any logic in the getters/setters of our properties - instead we just get/set the value directly to a field. This begs the question - then why not just use fields instead of properties? Well - there are a lot of downsides to exposing public fields. Two of the big problems are: 1) you can't easily databind against fields, and 2) if you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters) without recompiling any assemblies compiled against the old class.

The new C# compiler that ships in "Orcas" provides an elegant way to make your code more concise while still retaining the flexibility of properties using a new language feature called "automatic properties". Automatic properties allow you to avoid having to manually declare a private field and write the get/set logic -- instead the compiler can automate creating the private field and the default get/set operations for you.

For example, using automatic properties I can now re-write the code above to just be:

public class Person {

public string FirstName {
get; set;
}

public string LastName {
get; set;
}

public int Age {
get; set;
}
}

Or If I want to be really terse, I can collapse the whitespace even further like so:

public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

When the C# "Orcas" compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for you within your class, and implement a public getter and setter property implementation to it. The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our first (more verbose) implementation above. This means that -- unlike public fields -- I can in the future add validation logic within my property setter implementation without having to change any external component that references my class.

Bart De Smet has a great write-up on what happens under the covers when using automatic properties with the March CTP release of "Orcas". You can read his excellent blog post on it here.

New C# and VB Language Feature: Object Initializers

Types within the .NET Framework rely heavily on the use of properties. When instantiating and using new classes, it is very common to write code like below:

Person person = new Person();
person.FirstName = "Rambhopal";
person.LastName = "Reddy";
person.Age = 30;

Have you ever wanted to make this more concise (and maybe fit on one line)? With the C# and VB "Orcas" compilers you can now take advantage of a great "syntactic sugar" language feature called "object Initializers" that allows you to-do this and re-write the above code like so:

Person person = new Person { FirstName="Rambhopal", LastName="Reddy", Age=30 };

The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.

In addition to setting simple property values when initializing a type, the object initializer feature allows us to optionally set more complex nested property types. For example, assume each Person type we defined above also has a property called "Address" of type "Address". We could then write the below code to create a new "Person" object and set its properties like so:

Person person = new Person {
FirstName
= "Rambhopal",
LastName
= "Reddy"
Age = 30,
Address
= new Address {
Street
= "India",
City
= "Hyderabad",
State
= "AP",
Zip
= 500045
}
}
;

Bart De Smet again has a great write-up on what happens under the covers when using object initializers with the March CTP release of "Orcas". You can read his excellent post on it here.

New C# and VB Language Feature: Collection Initializers

Object Initializers are great, and make it much easier to concisely add objects to collections. For example, if I wanted to add three people to a generics-based List collection of type "Person", I could write the below code:

List people = new List();

people.Add( new Person { FirstName = "Rambhopal", LastName = "Reddy", Age = 30 } );
people.Add( new Person { FirstName = "Bill", LastName = "Gates", Age = 50 } );
people.Add( new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 } );

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what I'd need to type with the C# 2.0 compiler.

The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes:

List people = new List {
new Person { FirstName = "Rambhopal", LastName = "Reddy", Age = 30 },
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
}
;

When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.

Summary:

As developers we now have a much more concise way to define objects, initialize them, and add them to collections. At runtime, the semantics will be exactly the same as with today's longer syntax (so you don't need to worry about behavior changes). But now you don't need to type as much, and your code can be more crisp and concise.

In the near future I'll do additional blog posts that examine even more "Orcas" language improvements including Extension Methods, Lambdas, and Anonymous Types. I'll then do a deep dive into LINQ, and show how it takes advantage of all of these features to provide a really elegant way to query and interact with data.





Extension Methods

New to .NET 3.5 are a very powerful new paradigm called Extension Methods. Extension Methods, in a nutshell, are a way to extend the functionality of additional classes--adding new Methods to existing classes for the purpose of augmenting capability. The easiest way to demonstrate this is to show you a great example...

namespace ExtensionMethods
{
public static class StringExtensionMethods
{
public static bool IsNumeric(this string str)
{
try
{
int i = int.Parse(str);
return true;
}
catch
{
}
return false;
}
}
}

C#, as many of you know, lacks the built in VB.NET function, IsNumeric. (By the way, I can name a few things wrong with this particular extension method--so only use this example for the How-To of Extension Methods, not synthesizing IsNumeric) This extension Method extends the type string (the keyword "this" in the method signature is used to define what this method extends). With this newly written function, you can determine if a string is numeric by running code like this:

string s = "someValue";
bool bs = s.IsNumeric();
// bs is false;

string i = "7";
bool bi = i.IsNumeric();
// bi is true;

Now--as you may know, .NET strings do not intrinsically have a method IsNumeric() on them--this is our new Extension Method in action. In Visual Studio, you'll get intellisense if everything's set up right. Here's the rules you need to follow...

  1. All Extension Methods need to be defined in a static class
  2. All Extension Methods need to be defined as a static method.
  3. All Extension Methods need to take at least one parameter defined as follows:
    this (keyword) string (type) parameterName
    Where the type is whatever type that you wish to extend.
  4. The "this" parameter needs to be the first parameter. All other parameters are optional--and must follow "this".

Also I recommend the following points...

  1. Extension Methods adds complexity to your project and more importantly your IDE must parse these--don't go extension method crazy.
  2. Extension Methods should be extensions only. It's not advisable to define them in commonly used NameSpaces such as "System". That could be bad...
  3. If you're writing too many extension methods--maybe it's time to write a custom class that inherits from that data type, No?

A powerful tool, they are--extend the .NET framework they can. Enjoy them you must.

Also, technically, you can use 'em in .NET 2.0--but its a lot more work.
http://msdn.microsoft.com/en-us/magazine/cc163317.aspx#S7

http://msdn.microsoft.com/en-us/library/bb383977.aspx





Local Type Inference

he focus of this article will be on highlighting the local type inference feature that has been added to C# 3.0 and Visual Basic 9.0 languages. You'll touch on what it is, the syntax behind it, and why it is relevant to understand. You'll also touch on some examples of invalid uses because it can be just as helpful to examine what it is not to get a grasp on the concept.

Local Type Inference Defined

Local type inference is a language feature that allows you to define variables and use them without worrying about their true type. Local type inference is also interchangeably known as implicitly typed local variables. The burden is put on the respective language compiler to determine the type of a variable by inferring it from the expression assigned to the variable. The result is type safety while allowing you to write more relaxed code, which is required to support Language Integrated Query (LINQ).

Based on the description and a first glance of code, it is very easy to mistake type inference to be similar to defining everything as a type object or use of variants, which is heavily used in Visual Basic 6.0. This is entirely untrue and not what type inference is about. Type inferred variables are strongly typed. The type cannot be changed once it is assigned as could be done with a variant type so it does not involve any casting operations or the resulting performance implications. A strong type is assigned, but simply done so by the compiler based on the results of the expression assigned to the variable. The net effect is the true type isn't as readily apparent when reading code, but the Visual Studio IDE will tell you the type assigned along with the GetType() method will return a strong type at runtime.

There may be temptation over time to get lazy and let the compiler do the work for you by using type inference across the board. However, this is where the local part of local type inference comes into play. Type inference can only be used within a local scope where its type can be inferred by the expression assignment. Type inference cannot be applied to any of the following:

  • Cannot be a part of a member property declaration on a class, struct, or interface
  • Cannot be used in a parameter list on a method
  • Cannot be a return type for a method
  • Cannot be defined without a right hand assignment expression
  • Cannot reassign to be a different type once type has been inferred

Local Type Inference in C# 3.0

C# 3.0 implements local type inference through the var keyword in place of a specific type in a variable declaration.

The sample code below demonstrates the syntax for local type inference in C#. I created a new Windows console project to hold the code. Visual Studio 2008 Beta 2 was used to create the examples contained within.


namespace CodeGuru.TypeInference
{
class Program
{
static void Main(string[] args)
{
int a = 5;
var b = a; // int
var x = 5.5M; // double
var s = "string"; // string
var l = s.Length; // int

Console.WriteLine("value of b is {0} and type is {1}",
b, b.GetType().ToString());
Console.WriteLine("type of x is {0}", x.GetType().ToString());
Console.WriteLine("type of s is {0}", s.GetType().ToString());
Console.WriteLine("type of l is {0}", l.GetType().ToString());

Console.ReadLine();
}
}
)

It can be just as useful at times to look at examples where something does not apply. The following sample C# code demonstrates situations in which local type inference cannot be used. The code that is listed below will result in six different compile errors based on invalid usage and intentionally will not compile.

namespace CodeGuru.TypeInference
{
class Program
{
var test = "invalid use"; // invalid in member declaration

// Invalid as parameter
public void TryAsParameter(var parm)
{
}

// Invalid as return type
public var TryAsReturnType()
{
return "invalid use";
}

public void TryInvalidLocalUse()
{
var local1; // must be initialized
var local2 = null; // can't infer type from null

var local3 = 5; // valid use
local3 = "change type"; // can't change type
}
}


}

Local Type Inference in Visual Basic 9.0



Using local type inference in Visual Basic is more likely to be
misleading because it can appear as if it matches the behavior of Option Strict Off. As with C#, you still get a strong type despite the appearances. The syntax in Visual Basic is to omit the As Type part of the variable declaration. This will work just fine with Option Strict On and it is encouraged to continue use of Option Strict On to ensure variant types are not allowed and avoids the undesired boxing and unboxing.



Visual Basic allows you to turn local type inference on and off. There is Option Infer On and Option Infer Off that will enable or disable local type inference respectively. It is on by default.



The sample code below will demonstrate the syntax for local type inference in Visual Basic.



Option Strict On

Module Module1

Sub Main()

Dim As Integer = 5
Dim b = a ' int
Dim x = 5.5 ' double
Dim s = "string" ' string
Dim l = s.Length() ' int

Console.WriteLine("value of b is {0} and type is {1}", b, _
b.GetType().ToString())
Console.WriteLine("type of x is {0}",
x.GetType().ToString())
Console.WriteLine("type of s is {0}",
s.GetType().ToString())
Console.WriteLine("type of l is {0}",
l.GetType().ToString())

Console.ReadLine()

End Sub

End Module



As with the C# example, it can be just as beneficial to demonstrate
where local type inference cannot be used. The following sample code
demonstrates invalid attempts at using local type inference in Visual
Basic 9.0. It is important to note this code will not compile.



Module Module1

Dim test = "invalid use" ' invalid in member declaration

' Invalid as parameter
Sub TryAsParameter(ByVal parm)
End Sub


Sub Main()
Dim local ' must be initialized

Dim local3 = 5 ' valid use
local3 = "change type" ' cannot change type
End Sub

End Module



Summary



This article covered the local type inference language feature. You
examined what it is along with the syntax using examples of how it can
and cannot be used. Type inference is one of the language features
along with extension methods, partial methods, and others that enable
Language Integrated Queries (LINQ) to be possible, so it is important
to understand how type inference works and what it is not.

Read Data From an Excel File in ASP.NET

In this article, we will see how to display data from an Excel spreadsheet using ASP.NET. We will connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then display the data in a GridView. Let us get started.
Step 1: Open Visual Studio > File > New >Website > Under Templates, click ASP.NET WebSite and choose either Visual C# or Visual Basic as the language. Select a location and click Ok.
Step 2: We will create two excel sheets and add them to the project. One excel sheet will be created in Office 2003(.xls) and the other one using Office 2007(.xlsx or .xls) . Add 4 columns called EID, EName, Age and City to the ‘Sheet1’. Also add some data into the columns. Once these excel files are created, add them to your project. To add them to the project, right click project > Add Existing Item > Add the two excel files.
Step 3: We will now create a web.config file to store the connection string information. Right click project > Add New Item > Web.config. Add the following entries to the file.


<connectionStrings>
<add name="xls"connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sample1.xls;Extended Properties=Excel 8.0"/>
<add name="xlsx"connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties=Excel 12.0"/>
As you can observe, the connection string for xlsx (Excel 2007) contains Microsoft.ACE.OLEDB.12.0 as the provider. This is the new Access database engine OLE DB driver and is also capable of reading Excel 2003.
Step 4: Add a GridView to the Default.aspx page. We will extract data from the excel file and bind it to the GridView.
Step 5: Let us now create a connection to the excel file and extract data from it. Before that add a reference to System.Data.OleDb;
C#
protected void Page_Load(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
// Create the connection object
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
// Create OleDbCommand object and select data from worksheet Sheet1
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds, "Employees");
// Bind the data to the GridView
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch
{
}
finally
{
// Close connection
oledbConn.Close();
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("xls").ConnectionString
' Create the connection object
Dim oledbConn As OleDbConnection = New OleDbConnection(connString)
Try
' Open connection
oledbConn.Open()
' Create OleDbCommand object and select data from worksheet Sheet1
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn)
' Create new OleDbDataAdapter
Dim oleda As OleDbDataAdapter = New OleDbDataAdapter()
oleda.SelectCommand = cmd
' Create a DataSet which will hold the data extracted from the worksheet.
Dim ds As DataSet = New DataSet()
' Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds, "Employees")
' Bind the data to the GridView
GridView1.DataSource = ds.Tables(0).DefaultView
GridView1.DataBind()
Catch
Finally
' Close connection
oledbConn.Close()
End Try
End Sub
All set!! Run the application and see the data getting displayed in the GridView. If you want to target the Excel 2007 sheet, just change xls to xlsx in the ConfigurationManager.ConnectionString.
I hope this article was useful and I thank you for viewing it.
If you liked the article, Subscribe to my RSS Feed.
}
}




Thats it




5/1/09

Duplicate Count rows and Duplicate Delete Rows

Duplicate Count rows

----------------------------------------------------------------------------

we will see how to find count of all the duplicate records in the table. Following query demonstrates usage of GROUP BY, HAVING, ORDER BY in one query and returns the results with duplicate column and its count in descending order.

SELECT YourColumn, COUNT(*) TotalCount
FROM YourTable
GROUP BY YourColumn
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC


----------------------------------------------------------------------------------

Duplicate Delete Rows


----------------------------------------------------------------------------------


The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.


DELETE
FROM
MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2
)


---------------------------------------------------------------------------------------


Query to Retrieve the Nth Maximum value

-------------------------------------------------------------------------------------------------


How to get 1st, 2nd, 3rd, 4th, nth topmost salary from an Employee table

The following solution is for getting 6th highest salary from Employee table ,


SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

You can change and use it for getting nth highest salary from Employee table as follows
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary


where n > 1 (n is always greater than one)

Same example converted in SQL Server 2005 to work with Database AdventureWorks.

USE AdventureWorks;
GO
SELECT TOP 1 Rate
FROM (
SELECT DISTINCT TOP 4 Rate
FROM HumanResources.EmployeePayHistory
ORDER BY Rate DESC) A
ORDER BY Rate
GO



--------------------------------------------------------------------------------------------------

1/1/09

SQL SERVER - Query to find number Rows, Columns, ByteSize for each table in the current database - Find Biggest Table in Database

USE
GO
CREATE TABLE #temp (
table_name sysname ,
row_count INT,
reserved_size VARCHAR(50),
data_size VARCHAR(50),
index_size VARCHAR(50),
unused_size VARCHAR(50))
SET NOCOUNT ON
INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused "?"'
SELECT a.table_name,
a.row_count,
COUNT(*) AS col_count,
a.data_size
FROM #temp a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count, a.data_size
ORDER BY CAST(REPLACE(a.data_size, 'KB', '') AS integer) DESC
DROP TABLE #temp

SQL SERVER - Shrinking Truncate Log File - Log Full

SQL SERVER - Shrinking Truncate Log File - Log Full

December 30, 2006 by pinaldave

Sometime, it looks impossible to shrink the Truncated Log file. Following code always shrinks the Truncated Log File to minimum size possible.

USE DatabaseName
GO
DBCC SHRINKFILE(, 1)
BACKUP LOG WITH TRUNCATE_ONLY
DBCC SHRINKFILE(, 1)
GO

Welcome