add

Wednesday, December 23, 2009

How to reset the autoincrement field in MS Access Table

How to reset the autoincrement field in MS Access Table

Many times we use autoicrement field in Ms Access table and we have noticed that the value of autoincrement field keeps on increasing ever if we delete all the rows of the table and add new row.
In order to reset the autoincrement field value back to 1, do the following:

1. Delete all the rows from the table.
2. Compact the whole database .

This will automatically reset the autoincrement value back to 1.

Tuesday, December 22, 2009

Introducing WCF 3.5

This post is dedicated to WCF and its basics. We will go through various conceptual points of WCF and learn step by step implementation of WCF.
This post will cover few fundamental topics like:
• What is Windows Communication Foundation?
• Advantage of WCF
• What is an endpoint?
• Structure of endpoint or ABC of an end point.
• Explaining Address
• Explaining Binding and type of binding
• How to select proper binding
• Contracts and type of contracts
• Discussing Service Contract in detail।

What is WCF?
WCF stands for Windows Communication Foundation and comes along with Dot net framework 3.0 onwards and as a part of operating system from Vista onwards.
Business process in today’s market depends on various systems based on systems that runs on different platform within or outside an organization. There must be a way , a solution to have a communication between these various systems.
Why to use WCF?
WCF basically is a Microsoft’s solution to develop communication between distributed application। One may think why to use WCF when we already have lot of options to develop distributed application in past. The one line answer is that WCF acts as an unified technology that encapsulates all existing technologies to develop distributed application such as .NET Remoting, ASMX, MSMQ etc.

Apart from that we get lot of option on how to host the WCF service like IIS, or Widows Activated Service (WAS) etc. That we will discuss in later post.
I am eliminating discussion on history of distributed application since distributed application development is such a huge topic that it will divert our objective to learn WCF basics , However, throughout the document, I will map the similarity between existing distributed application solution to WCF।

Endpoint is the part that a service exposes to the outer system. It defines various details of a service hosted. The consumer reads the endpoint to judge the nature, type of the hosted service.
The ABC of WCF Endpoint:

Three basic component of any WCF service is :
“A” is for Address: Where to find the service
“B” is for Binding: How to communicate with the service
“C” is for Contract: What to send to the service or what to expect from the service.

Address:

It defines where on the network messages should be sent so that the endpoint receives them. This is the location to which messages must be sent by the client.

The address for an endpoint is a unique Uniform Resource Locator (URL) that identifies the location of the service. The address should follow the Web Service Addressing (WS-Addressing) standard, which means it might contain the following four parts:

• Scheme: The top-level portion of the address, this is typically “http” followed by a colon.
This is not the same thing as a protocol, even though it commonly uses the same letters as the protocol.
• Machine: Identifies the machine name, which can be a public URL or a local identifier.
• Port: The optional port number, preceded by a colon.
• Path: The path used to locate the service files. Typically, this is just the service name, but the path

Syntax of an address will be: Scheme://Machine[:Port]/Path1/Path2

Examples:

http://localhost:8080/Service1
http://localhost/Service1/SubService
http://www.ServiceHost.com/Service1
net.tcp://localhost:1234/OrderService

WCF supports several protocols, and each has its own particular addressing format.
1. HTTP protocol:
HTTP services can be either self-hosted or hosted on Internet Information Services (IIS). When addressing an HTTP service in a self-hosted scenario, you use the following format:
http://localhost:8080/QuickReturns/Exchange
2. TCP Protocol:
The TCP transport uses the net.tcp: scheme but otherwise follows the same rules as described
for HTTP addresses. Here is an example:
net.tcp://localhost:8080/QuickReturns/Exchange
3. MSMQ:
You can use the Microsoft Message Queue (MSMQ) transport in an asynchronous one-way
(fire-and-forget) or duplex type of messaging pattern and use the MSMQ features of Windows. net.msmq://localhost/private$/QuickReturnSettleTrade
4. Named Pipes:
It is a common way to provide a means to implement inter- or in-process communication.
The Named Pipes transport in WCF supports only local communication and uses the
net.pipes scheme. Port numbers don’t have any meaning with the Named Pipes transport.
This results in the following address format:
net।pipe://localhost/QuickReturns/Exchange

Binding:

A binding defines how you can communicate with the service. It is the primary extension point of the ABCs of WCF. The binding controls the following:

• The transport (HTTP, MSMQ, Named Pipes, TCP)
• The channels (one-way, duplex, request-reply)
• The encoding (XML, binary, MTOM…)
• The supported WS-* protocols (WS-Security, WS-Federation, WS-Reliability, WS-Transactions)


WCF provides a default set of bindings that should cover most of your requirements. If the default bindings don’t cover your requirements, you can build your own binding by extending from CustomBinding.

There are nine preconfigured bindings in WCF. Each of these provides the means for a particular distributed computing need. There are several factors that determine which binding to choose for a specific application, including security, interoperability, reliability, performance, and transaction requirements.

Table below compares the nine preconfigured bindings by showing the common features they support. This table can be used to select a best binding for a particular need.















Below is the process that will help you to select the binding you required for your application:











Contract:

A contract is a description of the messages that are passed to and from service endpoints.

There are three types of contracts in WCF:

• Service contracts : Service contracts describe the functional operations implemented by the service. A service contract maps the class methods of a .NET type to WSDL services, port types, and operations. Operation contracts within service contracts describe the service operations, which are the methods that implement functions of the service.

• Data contracts: Data contracts describe data structures that are used by the service to communicate with clients. A data contract maps CLR types to XML Schema Definitions (XSD) and defines how they are serialized and deserialized. Data contracts describe all the data that is sent to or from service operations.

• Message contracts: Message contracts map CLR types to SOAP messages and describe the format of the SOAP messages and affect the WSDL and XSD definitions of those messages. Message contracts provide precise control over the SOAP headers and bodies.

We will cover each type of binding and contract as we moves ahead with the implantation of WCF service. All theory will really make all of confuse so we need a bit of coding also..

Explaining Service Contract:

NOTE: before going into code, I would like to mention that all class, attributes specified to WCF comes from System.ServiceModel namespace. So import this namespace before going for coding.
A service contract is a collective mechanism by which a service capabilities and requirements are specified for its consumers.
Few points regarding Service Contract:
• A service contract can be applied to a normal dot net class or an interface.
• Service contract attribute is not inherited. That means if you are inheriting a class that has service contract attribute to it, you need to define the attribute to the derived class also. It will not get inherited automatically.
• Best practice is to use service contract attribute to interface.
• Always use namespace and Name parameter when defining a service contract attribute.

Sample Code:

An interface defined as a service contract without any parameter.
[ServiceContract()]
public interface ITaskManagerService
{ …. }
An interface defined as a service contract without any parameter.
[ServiceContract(Name=”ServiceName”,Namespace=”http://schema.application.com/path1”)]
public interface ITaskManagerService
{ …। }

Explaining Operation Conntract:

The OperationContractAttribute, also defined in the System.ServiceModel namespace, can be applied only to methods. It is used to declare the method as belonging to a Service contract.


[ServiceContract(Name=”ServiceName”,Namespace=”http://schema.application.com/path1”)]
public interface ITaskManagerService
{
[OperationContract(IsOneWay = true,name=”Operation1”)]
void ProcessInsertMessage(Message message);
}
So the above piece of code displays a interface defined as a service contract and its method as an operation contract।

In next article, I will discuss Message Exchange Pattern and two other contracts that is Data Contract and Message Contract.

Wednesday, November 18, 2009

All about Global.asax

This file is used by the application to hold application-level events, objects, and variables — all of which are accessible application-wide. Active Server Pages developers had something similar with the Global.asa file.

Your ASP.NET applications can have only a single Global.asax file. This file supports a number of items.

When it is created, you are given the following template:

<%@ Application Language="VB" %>
<script runat="server">

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is
' set to StateServer
' or SQLServer, the event is not raised.
End Sub

</script>

Just as you can work with page-level events in your .aspx pages, you can work with overall application
events from the Global.asax file.

In addition to the events listed in this code example, the following list
details some of the events you can structure inside this file:

- Application_Start: Called when the application receives its very first request. It is an ideal spot in your application to assign any application-level variables or state that must be maintained across all users.

- Session_Start: Similar to the Application_Start event except that this event is fired when an individual user accesses the application for the first time. For instance, the Application_Start event fires once when the first request comes in, which gets the application going, but the Session_Start is invoked for each end user who requests something from the application for the first time.

- Application_BeginRequest: Although it not listed in the preceding template provided by Visual Studio 2008, the Application_BeginRequest event is triggered before each and every request that comes its way. This means that when a request comes into the server, before this request is processed, the Application_BeginRequest is triggered and dealt with before any processing of the request occurs.

- Application_AuthenticateRequest: Triggered for each request and enables you to set up custom authentications for a request.

- Application_Error: Triggered when an error is thrown anywhere in the application by any user of the application. This is an ideal spot to provide application-wide error handling or an event recording the errors to the server’s event logs.

- Session_End: When running in InProc mode, this event is triggered when an end user leaves the application.

- Application_End: Triggered when the application comes to an end. This is an event that most ASP.NET developers won’t use that often because ASP.NET does such a good job of closing and cleaning up any objects that are left around.

In addition to the global application events that the Global.asax file provides access to, you can also use directives in this file as you can with other ASP.NET pages. The Global.asax file allows for the following directives:

- @Application
- @Assembly
- @Import

These directives perform in the same way when they are used with other ASP.NET page types.

How to place two classes written in different languages in App_Code

What is App_Code ?

The \App_Code folder is meant to store your classes, .wsdl files, and typed datasets. Any of these items stored in this folder are then automatically available to all the pages within your solution.

Everything placed in the \App_Code folder is compiled into a single assembly. The class files placed within the \App_Code folder are not required to use a specific language. This means that even if all the pages of the solution are written in Visual Basic 2008, the class in the \App_Code folder of the solution can be built in C#.
Here is a small catch...

Because all the classes contained in this folder are built into a single assembly, you cannot have classes of different languages sitting in the root \App_Code folder, as in the following example:

\App_Code
Class1.cs
Class2.vb

Having two classes made up of different languages in the \App_Code folder causes an
error to be thrown. It is impossible for the assigned compiler to work with two different languages.

Therefore, in order to be able to work with multiple languages in your \App_Code folder, you must make some changes to the folder structure and to the web.config file.

The first step is to add two new subfolders to the \App_Code folder
— a \VB folder and a \CS folder.
This gives you the following folder structure:
\App_Code
  \VB
  \CS

This still will not correctly compile these class files into separate assemblies, at least not until you make some additions to the web.config file.

In the web.config file , change the <compilation>
node so that it is structured as following:

<compilation>
<codeSubDirectories>
<add directoryName="VB"></add>
<add directoryName="CS"></add>
</codeSubDirectories>
</compilation>

Now that this is in place in your web.config file, you can work with each of the classes in your ASP.NET pages. In addition, any C# class placed in the CS folder is now automatically compiled just like any of the classes placed in the VB folder.

NOTE: The name of sub directories are'VB' and 'CS' for this example. You can put any name you wish to.

Tuesday, November 10, 2009

SharePoint Server 2010 Preliminary System Requirements

Sharepoint Server 2010 is on its way and it is high time to get ourself familiar with the system requirement of SharePoint Server 2010..

  • SharePoint Server 2010 will be 64 bit only.
  • SharePoint Server 2010 requires 64 bit Windows Server 2008 (R2)
  • SharePoint Server 2010 requires 64 bit SQL Server 2005 or 2008
  • SharePoint Server 2010 will support only IE7, IE8 and Firefox 3.x on Windows OS.
  • IE6 will not be supported by SharePoint Server 2010

The reason SharePoint platform is upgrading to 64 bit is to utilize the full power of extra bits while using 64 bit bus.

SharePoint performance and scalability can benefit significantly from 64-bit SQL Server and the throughput increases are significant enough for us to make the difficult decision to only support SharePoint Server 2010 on 64-bit SQL Server 2005 or 2008. It has been our strong recommendation for some time that SharePoint Server 2007 customers take advantage of 64-bit SQL Server due to the inherent performance and scale benefits it can provide.

Look out for the space for more news on SharePoint Server 2010.....

Varun

Tuesday, September 8, 2009

How to disconnect a map drive using vbscript

In my previous post, I described how to connect to a network drive.
In this post, I will demonstrate how to disconnect from an existing connected network drive.

Suppose we have a drive Z: that is a network drive connected. Following is the code regarding how ti remove it.


Option Explicit
Dim WshNetwork, ShareName
Set WshNetwork = WScript.CreateObject("WScript.Network")
ShareName = "Z:"
WshNetwork.RemoveNetworkDrive ShareName, true, true
WScript.Quit


We are creating an object of WScript.Network and calling method RemoveNetworkDrive by passing the drive letter.

How to map network drive using VBScript

Some time it is required to map a network drive using vbscript.
Today I will demonstate how to connet and then disconnect from a network drive.

In order to connect to a network drive, we need following data/information:

1. HomeServer Location: Actual path of the drive. In our example it is
"\\125.99.218.158\Data"

2. Name of the drive you wish to give: Let us say Z:

3. UserId/Password using which we will connect the map drive. If userid is same as logged in user then it is not required.

We will create an object of WScript.Network and call its method MapNetworkDrive

Here is the code:

Option Explicit
Dim strUser, strPassword, strDriveLetter, strHomeServer, strProfile
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")

strDriveLetter = "Z:"
strHomeServer = "\\125.99.218.158\Data"
strProfile = "False" ' Mapping (not) stored in user Profile
strUser = "USERID"
strPassword = "PASSWORD"

objNetwork.MapNetworkDrive strDriveLetter,strHomeServer,strProfile,strUser,strPassword

WScript.Quit


So the above code is creating an object of Wscript.Network and calling method MapNetworkDrive by passwing parameters like drive letter, hom server, userid and password.
There is one more parameter that is strProfile. If set true, it will store the drive info in user profile and it will connect automatically next time when user logs in.

Wednesday, July 29, 2009

Tuesday, July 21, 2009

How to send mail using CDO in VBScript

Today we will see how to send mail using CDO in VBScript. The same code can be used in ASP, VB also with small modification.

STEP 1: Define the constants:

Const cdoSendUsingMethod="http://schemas.microsoft.com/cdo/configuration/sendusing"
Const cdoSendUsingPort = 2
Const cdoSMTPServer ="http://schemas.microsoft.com/cdo/configuration/smtpserver"
Const cdoSMTPServerPort ="http://schemas.microsoft.com/cdo/configuration/smtpserverport"
Const cdoSMTPConnectionTimeout ="http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"
Const cdoSMTPAuthenticate = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"
Const cdoBasic = 1
Const cdoSendUserName="http://schemas.microsoft.com/cdo/configuration/sendusername"
Const cdoSendPassword ="http://schemas.microsoft.com/cdo/configuration/sendpassword"
Const CdoReferenceTypeName = 1

STEP 2: Declare variables

Dim objConfig ' As CDO.Configuration
Dim objMessage ' As CDO.Message
Dim Fields ' As ADODB.Fields
Dim HtmlBody

STEP 3: Get a handle on the config object and it's fields

' Get a handle on the config object and it's fields
Set objConfig = CreateObject("CDO.Configuration")
Set Fields = objConfig.Fields

' Set config fields we care about
With Fields
.Item(cdoSendUsingMethod) = cdoSendUsingPort
.Item(cdoSMTPServer) = <SMTP-SERVER-NAME>
.Item(cdoSMTPServerPort) = <PORT-NUMBER>
.Item(cdoSMTPConnectionTimeout) = 10
.Item(cdoSMTPAuthenticate) = cdoBasic
.Item(cdoSendUsingMethod ) = 2
.Update
End With

STEP 4: Create instance CDO.Messsage object

Set objMessage = CreateObject("CDO.Message")

STEP 5: Add image to the mail body

Add this step only if you have an image to add to the body
Set objBP = objMessage.AddRelatedBodyPart("C:\Users\Varun.Sharma\Shell\1.jpg", "1.jpg", CdoReferenceTypeName)
objBP.Fields.Item("urn:schemas:mailheader:Content-ID") = "<1.jpg>"
objBP.Fields.Update

For description of step 5, visit: How to add image to mail body using CDO

STEP 6: assign the properties of CDO.Message object

Set objMessage.Configuration = objConfig

STEP 7: Build the HTML Body

Always prepare your html body before hand. That will help your code look better

HtmlBody="<img src=1.jpg><br>"
HtmlBody=HtmlBody & " Sending mail using CDO"

STEP 8: Set the CDO.Message mail properties

With objMessage
.To = To-Address
.Cc = CC-Address
.From = From-Address
.Subject = "SMTP Relay Test"
.HtmlBody=HtmlBody
.Send
End With

STEP 9: Release the CDO instances

Set Fields = Nothing
Set objMessage = Nothing
Set objConfig = Nothing


FULL CODE:

Const cdoSendUsingMethod ="http://schemas.microsoft.com/cdo/configuration/sendusing"
Const cdoSendUsingPort = 2
Const cdoSMTPServer ="http://schemas.microsoft.com/cdo/configuration/smtpserver"
Const cdoSMTPServerPort ="http://schemas.microsoft.com/cdo/configuration/smtpserverport"
Const cdoSMTPConnectionTimeout ="http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"
Const cdoSMTPAuthenticate ="http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"
Const cdoBasic = 1
Const cdoSendUserName ="http://schemas.microsoft.com/cdo/configuration/sendusername"
Const cdoSendPassword ="http://schemas.microsoft.com/cdo/configuration/sendpassword"
Const CdoReferenceTypeName = 1


Dim objConfig ' As CDO.Configuration
Dim objMessage ' As CDO.Message
Dim Fields ' As ADODB.Fields
Dim HtmlBody



' Get a handle on the config object and it's fields
Set objConfig = CreateObject("CDO.Configuration")
Set Fields = objConfig.Fields



' Set config fields we care about
With Fields
.Item(cdoSendUsingMethod) = cdoSendUsingPort
.Item(cdoSMTPServer) = SMTP-SERVER-NAME
.Item(cdoSMTPServerPort) = PORT-NUMBER
.Item(cdoSMTPConnectionTimeout) = 10
.Item(cdoSMTPAuthenticate) = cdoBasic
.Item(cdoSendUsingMethod ) = 2
.Update
End With


Set objMessage = CreateObject("CDO.Message")

Set objBP = objMessage.AddRelatedBodyPart(PHYSICAL-PATH-OF-IMAGE, "1.jpg", CdoReferenceTypeName)
objBP.Fields.Item("urn:schemas:mailheader:Content-ID") = "<1.jpg>"
objBP.Fields.Update



Set objMessage.Configuration = objConfig
HtmlBody="<img src=1.jpg><br>"
HtmlBody=HtmlBody & "Testing the mail"

With objMessage
.To = TO-ADDRESS
.Cc = CC-ADDRESS
.From = FROM-ADDRESS
.Subject = "SMTP Relay Test"
'.TextBody = "SMTP Relay Test Sent @ " & Now()
.HtmlBody=HtmlBody
.Send
End With

Set Fields = Nothing
Set objMessage = Nothing
Set objConfig = Nothing

How to add image to mail body using CDO

Many times we face situation like, we need to send image in the html body of the mail that too using CDO.

Suppose we have an image at local server from where MailSend Code will get fire, here is the code:

Add this line of code to your CDO code to send image as a mail body:


Set objMessage = CreateObject("CDO.Message")
Set objBP = objMessage.AddRelatedBodyPart("C:\Users\Varun.Sharma\Shell\1.jpg", "1.jpg", CdoReferenceTypeName)
objBP.Fields.Item("urn:schemas:mailheader:Content-ID") = "<1.jpg>"
objBP.Fields.Update

Here, in AddRelatedBodyPart,
argument 1 is : physical location of image
argument 2 is : identifier of the image (any name)
argument 3 is : To tell CDO to send the image as well

In next line, just put image identifer to the right hand side.

When sending mail refer the image in html body like this:

mail.HtmlBody="<img src=1.jpg" >

For full code of sending mail using CDO, check the following link:
How to send mail using cdo in vbscript

Sunday, July 5, 2009

Learning UML with C#

UML is a simple diagramming style that was developed from work done by Grady Booch, James Rumbaugh, and Ivar Jacobson, which resulted in a merging of ideas into a single specification and, eventually, a standard.

Here , We will see how to map a class and its relation in UML.

Basic UML diagrams consist of boxes representing classes. Let’s consider
the following class (which has very little actual function).

Basic Class :

public class Person {
private string name;
private int age;
//-----
public Person(string nm, int ag) {
name = nm;
age = ag;
}
public string makeJob() {
return "hired";
}
public int getAge() {
return age;
}
public void splitNames() {
}
}

We can represent this class in UML, as shown in Figure



The top part of the box contains the class name and package name (if any).
The second compartment lists the class’s variables, and the bottom compartment lists its methods. The symbols in front of the names indicate that member's visibility, where "+" means public, "-" means private, and "#" means protected. Static methods are shown underlined.

Abstract methods may be shown in italics or in an “{abstract}” label.

UML does not require that you show all of the attributes of a class, and it
is usual only to show the ones of interest to the discussion at hand.




Inheritance:

Now, we will look into inheritance and how to implement it in UML.

Let’s consider a version of Person that has public, protected, and private variables and methods, and an Emplo yee class derived from it.

public abstract class Person {
protected string name;
private int age;
//-----
public Person(string nm, int ag) {
name = nm;
age = ag;
}
public string makeJob() {
return "hired";
}
public int getAge() {
return age;
}
public void splitNames() {
}
public abstract string getJob(); //must override
}

We now derive the Employee class from it, and fill in some code for the getJob method.

public class Employee : Person {
public Employee(string nm, int ag):base(nm, ag){
}
public override string getJob() {
return "Worker";
}
}

You represent inheritance using a solid line and a hollow triangular arrow.
For the simple Employee class that is a subclass of Person, we represent this in UML, as shown in Figure



Note that the name of the Employee class is not in italics because it is now a concrete class and because it includes a concrete method for the formerly abstract getJob method.

Friday, June 19, 2009

OOPS Part II -- Pillars of OOPS -- Inheritance, Polymorphism, Encapsulation

Part I --> OOPS Part I -- OOPS Part I -- Understanding the Object Oriented Programming

All object-based languages must contend with three core principals of object-oriented programming, often called the "pillars of object-oriented programming (OOP)":

Encapsulation: How does this language hide an object’s internal implementation details and preserve data integrity?
Inheritance: How does this language promote code reuse?
Polymorphism: How does this language let you treat related objects in a similar way?

The Role of Encapsulation



The first pillar of OOP is called encapsulation. This trait boils down to the language’s ability to hide unnecessary implementation details from the object user.

For example, assume you are using a class named DatabaseReader, which has two primary methods: Open() and Close():

// This type encapsulates the details of opening and closing a database.
DatabaseReader dbReader = new DatabaseReader();
dbReader.Open(@"C:\MyCars.mdf");
// Do something with data file and close the file.
dbReader.Close();

The fictitious DatabaseReader class encapsulates the inner details of locating, loading, manipulating, and closing the data file. Object users love encapsulation, as this pillar of OOP keeps programming tasks simpler. There is no need to worry about the numerous lines of code that are working behind the scenes to carry out the work of the DatabaseReader class. All you do is create an instance and send the appropriate messages

Closely related to the notion of encapsulating programming logic is the idea of data hiding. Ideally, an object’s state data should be specified using the private (or possibly protected) keyword. In this way, the outside world must ask politely in order to change or obtain the underlying value. This is a good thing, as publicly declared data points can easily become corrupted (hopefully by accident rather than intent!). You will formally examine this aspect of encapsulation in just a bit.

The Role of Inheritance



The next pillar of OOP, inheritance, boils down to the language’s ability to allow you to build new class definitions based on existing class definitions.

In essence, inheritance allows you to extend the behavior of a base (or parent) class by inheriting core functionality into the derived subclass (also called a child class).

Figure below shows a simple example. You can read the diagram in Figure as "A Hexagon is-a Shape that is-an Object."




When you have classes related by this form of inheritance, you establish "is-a" relationships between types. The "is-a" relationship is termed classical inheritance.

Here, you can assume that Shape defines some number of members that are common to all
descendents. Given that the Hexagon class extends Shape, it inherits the core functionality defined by Shape and Object, as well as defines additional hexagon-related details of its own (whatever those may be).

There is another form of code reuse in the world of OOP: the containment/delegation model
(also known as the “has-a” relationship or aggregation). This form of reuse is not used to establish parent/child relationships. Rather, the “has-a” relationship allows one class to define a member variable of another class and expose its functionality (if required) to the object user indirectly.

For example, assume you are again modeling an automobile. You might want to express the
idea that a car “has-a” radio. It would be illogical to attempt to derive the Car class from a Radio, or vice versa (a Car “is-a” Radio? I think not!). Rather, you have two independent classes working together, where the Car class creates and exposes the Radio’s functionality:

class Radio
{
public void Power(bool turnOn)
{
Console.WriteLine("Radio on: {0}", turnOn);
}
}
class Car
{
// Car 'has-a' Radio
private Radio myRadio = new Radio();
public void TurnOnRadio(bool onOff)
{
// Delegate call to inner object.
myRadio.Power(onOff);
}
}
Notice that the object user has no clue that the Car class is making use of an inner Radio object.
static void Main(string[] args)
{
// Call is forwarded to Radio internally.
Car viper = new Car();
viper.TurnOnRadio(false);
}

Difference Between Inherating a class and instantiating a class



When you inherit a class, you get the superclass attributes and methods that you can use without instantiating a superclass object. You can only use those which are public or protected.
If you instantiate them, you make an object and upon that object you call methods defined in the object's class.

When you inherit a class, base class from which a class is derived does not have state, behaviour or identity where as if you create an instance of a class, the base class sets it's identity, state, behaviour.

When you create an instance of an object, you can access the method of the class by using dot operator (.) but if you inherit a class, you can not access base class method by using dot operator.

Use Inheritance when you are sure that you need to extend few methods of the base class or need to add some more methods to it otherwise just create the instance of the class.

The Role of Polymorphism



The final pillar of OOP is polymorphism. This trait captures a language’s ability to treat related objects in a similar manner. Specifically, this tenant of an object-oriented language allows a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendents. A class’s polymorphic interface is constructed using any number of virtual or abstract members.

In a nutshell, a virtual member is a member in a base class that defines a default implementation that may be changed (or more formally speaking, overridden) by a derived class. In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type. In either case, when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.

To preview polymorphism, let’s provide some details behind the shapes hierarchy shown in
Figure. Assume that the Shape class has defined a virtual method named Draw() that takes no parameters. Given the fact that every shape needs to render itself in a unique manner, subclasses (such as Hexagon and Circle) are free to override this method to their own liking.




Once a polymorphic interface has been designed, you can begin to make various assumptions
in your code. For example, given that Hexagon and Circle derive from a common parent (Shape), an array of Shape types could contain anything deriving from this base class. Furthermore, given that Shape defines a polymorphic interface to all derived types (the Draw() method in this example), we can assume each member in the array has this functionality. Consider the following Main() method, which instructs an array of Shape-derived types to render themselves using the Draw() method:

class Program
{
static void Main(string[] args)
{
Shape[] myShapes = new Shape[3];
myShapes[0] = new Hexagon();
myShapes[1] = new Circle();
myShapes[2] = new Hexagon();
foreach (Shape s in myShapes)
{
s.Draw();
}Console.ReadLine();
}
}

This wraps up our brisk overview of the pillars of OOP. Now that you have the theory in your mind, the remainder of this chapter explores further details of how encapsulation is handled under C#. The next chapter will tackle the details of inheritance and polymorphism.

Thursday, June 18, 2009

OOPS Part I -- Understanding the Object Oriented Programming

This chapter is a basic introduction to object-oriented programming. It introduces you to some of the basic concepts and terms you need to know as you get a handle on the specific details of how object-oriented programming works.


What Is Object-Oriented Programming?

The term object-oriented programming means many different things. But at its heart, object-oriented programming is a type of computer programming based on the premise that all programs are essentially computer-based simulations of real-world objects or abstract concepts.

For example: Flight-simulator programs attempt to mimic the behavior of real airplanes. Some do an amazingly good job; military and commercial pilots train on them.


Understanding Objects

Objects-both in the real world and in the world of programming-are entities that have certain basic characteristics. The following sections describe some of the more important of these characteristics: identity, type, state, and behavior.


Objects have identity

Every object in an object-oriented program has an identity. In other words, every occurrence of a particular type of object-called an instance-can be distinguished from every other occurrence of the same type of object, as well as from objects of other types.


Objects have type

Object-oriented programming lets you assign names to the different kind of objects in a program. Types are defined by classes. So when you create an object from a type, you're saying that the object is of the type specified by the class. For example, the following statement creates an object of type Invoice:

Invoice i = new Invoice();

In this case, the identity of this object (that is, its address in memory) is assigned to the variable i, which the compiler knows can hold references to objects of type Invoice.


Objects have state

The type of an object determines what attributes the object has. Thus, all objects of a particular type have the same attributes. However, they don't necessarily have the same values for those attributes.
The combination of the values for all the attributes of an object is called the object's state. Unlike its identity, an object's state can and usually does change over its lifetime.

Here are a few more interesting details about object state:

  • Some of the attributes of an object are publicly known, but others can be private. The private attributes may be vital to the internal operation of the object, but no one outside of the object knows they exist. They're like your private thoughts: They affect what you say and do, but nobody knows them but you.
  • The state of an object is represented by class variables, which are called fields. A public field is a field that's declared with the public keyword so the variable can be visible to the outside world.


Objects have behaviour


Another characteristic of objects is that they have behavior, which means they can do things. Like state, the specific behavior of an object depends on its type. But unlike state, the behavior isn't different for each instance of a type.

Another way to say that objects have behavior is to say they provide services that can be used by other objects. The behavior of an object is provided by its methods.




OOPS Part II -- Pillars of OOPS -- Inheritance, Polymorphism, Encapsulation

Interview Experience with PWC

Recently I gave an interview with PWC.. Though not selected, I would like to share my experience with you all. Here are the list of questions asked in Round I:


01. Tell me about your education background, work profile.
02. Is dot net object oriented?
Here I said 'YES'..so next question

Lets start with OOPS
------OOPS------------
03. What is an abstract class?
04. What is an interface?
05. What is the difference between abstract class and an interface?
06. When to use what (abstract/interface)?
07. Give practical scenario regarding usage.
08. What is the relation between virtual and override keyword?
09. What is Polymorphism?
10. What is method overloading and method overriding?
11. What is singleton class?
12. When to use singleton class?
13. Any class in dot net framework that is an example of singleton class?
14. What is inheritance?
-------------------------

------SHAREPOINT-------------
You have worked on SharePoint also....YES
SharePoint coding or just Out-Of-Box? ... Coding

15. What is a web part?
16. Advantage of web part?
17. How to deploy a web part..step by step
18. What is the command line utility used in SharePoint?
19. How you can implement List Item listener?
20. Scenario: You need to check before inserting an item to list that whether the EmpID( field) is unique or not? How will you implement?
21. How will you deploy a feature?
-------------------------

-------Database-----------
22. What is an index?
23. How many types of index are there?
24. How many index I can have on a table? Any max limit?
25. What is difference between a primary key and unique key?
26. What are constraints?
27. Name any constraint?
28. Scenario: Table: EMPID, EMPDEPT, SALARY. You need to restrict that one can insert a row where salary is less than 5000. How will you implement that?
29. What is trigger and of how many types?
30. Have you worked on cursors?..I said no..that's why no further questions
---------------------------

--------DOT NET-----------
31. What are attributes in dot net?
32. Can we define user defined attributes?..IF yes then How?
33. How web service communicates between two non-compatible platforms?
34. Can web service preserve state? How?
35. What is singleton web service?
36. When we add a class file, what remains the default assess modifier?
37. Difference between protected internal, protected ?
38. What is MVC?
39. How will you relate MVC with 3-tier architecture?
--------------------------

-------Process Oriented----------
40. Can you name and explain any design pattern with example
41. Have you ever used any defect analysis?
42. What type of proceed flow you use?
43. Have you ever designed design document?
44. What are the main parts of a design document?
45. What tool you used in order to draw class diagrams?
46. Any idea regarding UML?

Sunday, June 14, 2009

Structure of Sharepoint Site and Navigation

SharePoint sites are always part of a site collection, which has a single parent or top - level site .

The top - level site can have any number of child sites, grandchildren, and so on, and each site will have one or more pages in a page library .

The site structure is therefore based on pages(the leaf nodes, which are viewable by end users) and sites (the containers, each of which has at least one default page to display).

Thursday, June 11, 2009

How to get Data from Active Directory using C#

Today, I am going to discuss how to fetch data from active directory and how to store it into a clas..

We can access LDAP or AD by using two class: DirectoryEntry and DirectorySearcher

Step 1:

Add reference to System.DirectoryServices amd import it in the code by entering using System.DirectoryServices;

Step 2:

We need the AD Location, AD Userid and AD Password in order to read data from it.

We store these values in web.config:
<appSettings>
<add key="GaadLocation" value="LDAP://XXXXX:XXX"/>
<add key="GaadUserName" value="XXXXXX"/>
<add key="GaadPassword" value="XXXXXX"/>
</appSettings>


Step 3:

In order to store the data fetched from AD, we created a class and defined some properties.

public class ADContact
{
public string UniqueId {get; set; }
public string LastName { get; set; }
public string DepartmentNumber { get; set; }
public string EmployeeType { get; set; }
public string TelephoneNumber { get; set; }
public string FirstName { get; set; }
public string UserStatus { get; set; }
public string Mail { get; set; }
public string Mobile { get; set; }
public string Title {get; set; }
}


Step 4: Create a method that will return a datatable so that we can iterate through the result.

public List GetADContacts(string SirName, string GivenName, string UniqueId)
{}

Step 5:

Within the method, create a SearchResultCollection object , a datatable, and list of AD properties to access:

SearchResultCollection results = null;
List GaadData = new List();

string ADLocation, ADUserId, ADUserPassword = string.Empty;
#region List of AD Properties
string[] properties = new string[]
{
"modifyTimestamp",
"uid",
"sn",
"departmentNumber",
"facsimileTelephoneNumber",
"givenName",
"mail"
};
#endregion


Step 6:
Declare a try-catch block and within try- write the following code:

try {

string strfilter = string.Empty;


//Get AD Settings from web.config
ADLocation = ConfigurationManager.AppSettings["ADLocation"];
ADUserId = ConfigurationManager.AppSettings["ADUserName"];
ADUserPassword = ConfigurationManager.AppSettings["ADPassword"];


//Create an instance of DirectoryEntry by passing the setting valies)
DirectoryEntry root = new DirectoryEntry(ADLocation, ADUserId, ADUserPassword, AuthenticationTypes.FastBind);

//Create the filter string : we need to search the Ad for people matching the search criteria. Here we are passing three parameters: SirName, GivenName, Uid. If any field is blank, we are putting * there. that is to get all values

strfilter = String.Format(
"(&(&(sn={0})(givenname={1})(uid={2})))",
String.IsNullOrEmpty(SirName) ? "*" : SirName + "*",
String.IsNullOrEmpty(GivenName) ? "*" : GivenName + "*",
String.IsNullOrEmpty(UniqueId) ? "*" : UniqueId + "*");

if (strfilter != "")
{
DirectorySearcher searcher = new DirectorySearcher(root, strfilter, properties);
searcher.Asynchronous = true;
searcher.SearchScope = SearchScope.Subtree;
results = searcher.FindAll();
}
foreach (SearchResult result in results)
{
ADContact contact = new ADContact();

if (result.Properties["uid"].Count > 0)
contact.UniqueId= Convert.ToString(result.Properties["uid"][0]);

if (result.Properties["title"].Count > 0)
contact.Title = Convert.ToString(result.Properties["title"][0]);

if (result.Properties["sn"].Count > 0)
contact.LastName = Convert.ToString(result.Properties["sn"][0]);

if (result.Properties["givenName"].Count > 0)
contact.FirstName = Convert.ToString(result.Properties["givenName"][0]);

if (result.Properties["facsimileTelephoneNumber"].Count > 0)
contact.TelephoneNumber = Convert.ToString(result.Properties["facsimileTelephoneNumber"][0]);

if (result.Properties["mobile"].Count > 0)
contact.Mobile = Convert.ToString(result.Properties["mobile"][0]);

if (result.Properties["mail"].Count > 0)
contact.Mail = Convert.ToString(result.Properties["mail"][0]);

ADData.Add(contact);
}
return ADData;
}
catch (Exception ex)
{
throw ex;
}

Tuesday, June 9, 2009

New Features of dot Net 3.5 Framework

Dot net framework 3.5 is built on dot net 2.0 runtime library with addition of few dlls like: System.Core.dll, System.XML.LINQ.dll, System.AjaxExtension.dll etc..

Mainly enhancements are done with related to LINQ and Entitiy Model. Here are few enhancements listed:


1. Automatic Properties :

If you remember, prior to framework 3.5, we used to declare property within a class like this:

class Class1 {

privtae string _CustomerName;
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
}


Now, we will see how to implement the same code in dot net 3.5:

class Class1 {
public string CustomerName {get; set;}
}





2. Object Initializers :

Another new feature coming with .NET 3.5, C# 3 and VB 9 is object initialization. Object Initializers allow you to pass in named values for each of the public properties that will then be used to initialize the object.

Suppose we have a class called School and few fields, we used to initialization the class like this:

School school1=new School();
school1.Name="ABC";
school1.Address="DEF";


Now the problem is that if we need to initialize different fields based on logic, we need to create different constructors based on our logic. Here comes the use of Object Initializers.

Object Initializers allow you to pass in any named public property to the constructor of the class. This is a great feature as it removes the need to create multiple overloaded constructors using different parameter lists to achieve the same goal.

So, from framework 3.5 onwards, we will use:

School school1=new School {
Name="ABC";
Address="DEF";
};





3. Collection Initializers :

Like Object Initializers, the new Collection Initializers allow you to create a collection and initialize it with a series of objects in a single statement. The following statement demonstrates how the syntax is very similar to that of the Object Initializers. Initializing a List is accomplished by passing the instances of the Customer objects wrapped inside of curly braces.

Getting this feature as part of framwork, we don not need to declare the collection first and then add items to it.


List SchoolList = new List
{
new School {ID = 101, SchoolName = "School1"},
new School {ID = 102, SchoolName = "School2"},
new School {ID = 103, SchoolName = "School3"}
};




4. Extension Method

Extension methods are a new feature that allows you to enhance an existing class by adding a new method to it without modifying the actual code for the class. This is especially useful when using LINQ because several extension methods are available in writing LINQ query expressions.

For more details on extension method, check "What is Enxtension Method "

Extension Methods are very useful when you cannot add a method to the class itself, as in the case of creating a Cube method on the int class. Just because you can use a tool, does not mean you should use a tool.




5. Anonymous Types

When you create an Anonymous Type you need to declare a variable to refer to the object. Since you do not know what type you will be getting (since it is a new and anonymous type), you can declare the variable with the var keyword. This technique is called using an Implicitly Typed Variable.

Chek more details on "All about Anonymous Types

Steps in Compliation in ASP.NET

We all know the term compilation in Asp.Net. But do you know what is the order of compilation in an asp.net project. Do you know which folder in the application structure gets compiled first and which when get compiled last?

Here is the compilation life cycle of an Asp.Net project in the order they get compiled.

App_GlobalResources: First of all the global resources are compiled and the resource assembly is built. All the assembly's in the bin folder are linked to this assembly.

App_WebResources: Next the web resource folder will be compiled. This will create all the proxy types for the web services. The web reference created is then linked to the resource assembly (if it exists.).

Profile properties (defined in the Web.config file): If we have defined the profile properties in the web.config file than an assembly will be generated for the profile objects.

App_Code: Next all the files in the App_Code folder will be compiled. All code assemblies and the profile assembly are linked to the resources and Web references assemblies if any.

Global.asax: Next the Application object is compiled and then it is linked with all other previously generated assembly's.

Once the top-level items are compiled, the compilation of folder, pages and other items start as and when needed. Here is a list of how this process continues?

App_LocalResources: If the folder containing the requested item contains an App_LocalResources folder, the contents of the local resources folder are compiled and linked to the global resources assembly.

Individual Web pages (.aspx files),
User Controls (.ascx files),
HTTP handlers (.ashx files),

HTTP modules (.asmx files): Next these files are compiled.

Themes, master pages, other source files are compiled when referenced page is compiled.

Monday, June 8, 2009

What's the difference between encapsulation and abstraction?

Encapsulation protects abstractions. Encapsulation is the bodyguard; abstraction is the VIP.

Encapsulation provides the explicit boundary between an object's abstract interface (its abstraction) and its internal implementation details. Encapsulation puts the implementation details "in a capsule." Encapsulation tells users which features are stable, permanent services of the object and which features are implementation details that are subject to change without notice.

Encapsulation helps the developers of an abstraction: it provides the freedom to implement the abstraction in any way consistent with the interface. (Encapsulation tells developers exactly what users can and cannot access.) Encapsulation also helps the users of an abstraction: it provides protection by preventing dependence on volatile implementation details.

Abstraction provides business value; encapsulation "protects" these abstractions. If a developer provides a good abstraction, users won't be tempted to peek at the object's internal mechanisms. Encapsulation is simply a safety feature that reminds users not to stray over the line inadvertently.

What is an abstraction ?

An abstraction is a simplified view of an object in the user's own vocabulary.

In OO ,an abstraction is the simplest interface to an object that provides all the features and services the intended users expect.

An abstraction tells users everything they need to know about an object but nothing else. It is the well-defined, unambiguously specified interface. For example, on a vending machine, the abstraction is formed by the buttons and their meanings; users don't have to know about levers, internal counters, or other parts that are needed for the machine to operate. Furthermore the vending machine's price list implies a legally binding promise to users: if users put in the right amount of money, the machine promises to dispense the desired item.

The key to a good abstraction is deep knowledge of the problem domain. A good abstraction allows users to use an object in a relatively safe and predictable manner. It reduces the learning curve by providing a simple interface described in terms of the user's own vocabulary.

A good abstraction separates specification from implementation. It doesn't expose too much nor does it hide features that users need to know about. If an abstraction is good, users aren't tempted to peek at the object's implementation. The net result is simpler, more stable user code.

Sunday, June 7, 2009

How to use RunWithElevatedPrivileges in Sharepoint

The SPSecurity class provides a static method named RunWithElevatedPrivileges that enables code to execute as system code running under the identity of SHAREPOINT\system. This allows code to run in an escalated security context to perform actions as the system.

This method should be used with care and should not expose direct access to system resources, but rather should be used when you need to perform actions on behalf of the system. The method is simple. You can either create a delegate to a public void method or simply write code within an inline delegate.

The signature looks like the following:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Code runs as the "SharePoint\system" user
});


Note that :
Code running with the escalated privilege should use a new SPSite object for code running as the system and use the SPContext.Current property to access the actual calling user’s identity.

To modify WSS content under the System credentials, you need to create a new SPSite site collection that generates a new security context for objects referenced from the site, as in the following example. You cannot switch the security context of the SPSite once it has been created, but must instead create a new SPSite reference to switch user contexts. The following code uses the system credentials to add a list item using the profile data of the current Web user:

SPSecurity.RunWithElevatedPrivileges(
delegate() {
using (SPSite site = new SPSite(web.Site.ID)) {
using (SPWeb web2 = site.OpenWeb()) {
SPList theList = web2.Lists["visitors"];
SPListItem record = theList.Items.Add();
record["User"] = SPContext.Current.Web.CurrentUser;
record.Update();
}
}
);

How to add a SPGroup to a Site Collection- Sharepoint

Groups cannot directly be added to a site-they must be added to the site collection.
If you try to add a group to the site’s Groups collection, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

This situation occurs because the SPGroup is always created at the Site Collection level and assigned to the site. The following code is valid and adds the LitwareSecurityGroup to the site collection groups.

// Adds a new group to the site collection groups:
site.SiteGroups.Add("LitwareSecurityGroup", site.CurrentUser,site.CurrentUser, "A group to manage Litware Security");

However, this still does not associate the group with our site, nor would it be useful within the site without any permissions. To add the group to the site, create a new SPRoleAssignment by associating an SPRoleDefinition with the SPGroup, and then add that role assignment to the site, as in the following code sample:


SPGroup secGroup = site.SiteGroups["LitwareSecurityGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);

How to get list of SPGroups in Sharepoint Site Collection

Sharepoint Gropus (or SPGroups) are never created in the context of the site-they are always created in the context of the site collection and assigned to a site.

We can get list of groups of a site by suing site.Groups


SPSite siteCollection = new SPSite("http://localhost/litware/sales/");
SPWeb site = siteCollection.OpenWeb();

foreach(SPGroup group in site.Groups){
Console.WriteLine(group.Name);
}

Thursday, May 28, 2009

Using Extension Method

Why Extension Method ?

Many time we need a requirement where we need to add a new method to a class. Addition of new method is very easy if we have the class code but what if we don't have the source code of that class? We just have the dll..

One option is to inherit the existing class and add the new method or modify any existing method. The problem with this option is that it may not be possible every time due to OO Principles.

Here comes the concept of Extension Method

How to Use Extension Method

Here is a step by step tutorial on how to use extension method.

Suppose the case is that, we need to have a method called 'Next' and 'Previous' that will give us the next and previous number of the given number.

We will do it by using Extension method.

Step 1: Create a new Console application:
Step 2: Add a new class Item and name it 'Ext.cs'.
Step 3: Renamen the namespace of that class to System.
Step 4: Add the followign code:

public static class Ext
{
public static int Next(this int A)
{
return A + 1;
}
public static int Previous(this int A)
{
return A - 1;
}

}


The class will look like this:



Few things to explain:

1. Namespace has been renamed to 'System' since almost all C# source files have a using System; declaration, this extension method is effectively going to be available globally

2. An extension method must be static and public, must be declared inside a static class, and must have the keyword this before the first parameter type, which is the type that the method extends. Extension methods are public because they can be (and normally are) called from outside the class where they are declared.

Step 5: How to use an Extension Method:

We have created a public , static method using namespace System. Now the question is how to use it.
In step 1 , we have created a console application, so in the Main method of Program.cs, write this:

int a=10;
Console.WriteLine("Number after {0} is {1}", a, a.Next());
Console.WriteLine("Number after {0} is {1}", a, a.Previous());
Console.ReadLine();

You will notice here, as soon you type 'a' and press ., static mehtods declared in the Ext.cs will appears in intellisence and with a new symbol that marks it as extension.



Step 6: Build the application and press F5:

The output window will show the desired result:



Summary

Although this is not a big revolution, one advantage could be Microsoft IntelliSense support, which could show all extension methods accessible to a given identifier. However, the result type of the extension method might be the extended type itself. In this case, we can extend a type with many methods, all working on the same data. LINQ very frequently uses extension methods in this way.

The most common use of extension methods is to define them in static classes in specific namespaces, importing them into the calling code by specifying one or more using directives in the module.

Wednesday, May 27, 2009

What is difference between dataset and datareader ?

Following are some major differences between dataset and datareader :-

√ DataReader provides forward-only and read-only access to data, while the
DataSet object can hold more than one table (in other words more than one
rowset) from the same data source as well as the relationships between them.

√ Dataset is a disconnected architecture while datareader is connected
architecture.

√ Dataset can persist contents while datareader can not persist contents, they
are forward only.

Overview of ADO.NET architecture

The most important section in ADO.NET architecture is “Data Provider”. Data Provider
provides access to datasource (SQL SERVER, ACCESS, ORACLE).In short it provides
object to achieve functionalities like opening and closing connection, retrieve data and update data. In the below figure you can see the four main sections of a data provider :-

Connection.
Command object (This is the responsible object to use stored procedures)
Data Adapter (This object acts as a bridge between datastore and dataset).
Data Adapter (This object acts as a bridge between datastore and dataset).

Dataset object represents disconnected and cached data. If you see the diagram it is not in direct connection with the data store (SQL SERVER, ORACLE etc) rather it talks
with Data adapter, who is responsible for filling the dataset. Dataset can have one or more Datatable and relations.

Introduction to ASP.NET MVC

In this session we’ll take a look at WebForms and how its request pipeline is structured, and then introduce the MVC pattern, and how it is implemented into the ASP.NET MVC framework.

We’ll then discuss how WebForms and MVC differ from each other.
Then we’ll look into the default conventions and project structure of an MVC application.

Web Forms



In WebForms today you start out with an ASPX page.
Within the page you can have any number of user controls, custom controls, and server controls.
In addition, a page can have a master page, which can in turn have any number of controls itself.
When you introduce model data, due to the level of abstraction needed by WebForms, any of the components used can access to data.
The page, the master page, and any of their individual controls contain logic that both retreives model data and contains it view representation.

This is model that has made WebForms so successful and useful for web developers.

WebForms uses a pattern called page controller.
When a request comes into ASP.NET, the request is served by a specific ASPX page. Hence, the page itself serves as the controller, or face of the object that handles the request.

What is MVC ?

MVC or Model-View-Controller is an architectural pattern that separates model access from presentation logic.
It adds specific responsibility to individual portions of the application.
The model represents your business objects, that both houses your data, and contains business logic.
The controller is responsible for interacting with the model, and then passing that data down to the view.
The view’s sole responsibility is acting as a representation of the model data it is given by the controller.



ASP.NET MVC
So now let’s see how a typical ASP.NET MVC application contrasts to the way a WebForms application looked.



Notice that we still have our ASPX page, which in turn can leverage user controls, custom controls, and server controls. Nothing difference there.
The page can be associated with a master page, which can in turn have its own set of user controls, custom controls, and server controls. So far this is still the same as WebForms.
We re-introduce the model data, which is where the contrast between WebForms and MVC gets clearer.
With WebForms, any of the controls, or page, or master page was directly interacting with the model. We introduce the controller into the picture, which will now be the orchestrator between the model and the views.

Here, instead of the pages and controls directly accessing the model, the controller is strictly doing that. Once it gets the model data it is responsible for passing the data to the page, or view.

The main tenets of ASP.NET MVC are…
Alternative
ASP.NET MVC builds on top of ASP.NET, it doesn’t replace it. It is simply meant to serve as an alternative approach to developing web applications using ASP.NET.

Testable
While WebForms can be tested, it isn’t the most trivial task. ASP.NET MVC was built with testing in minding, so practicing TDD, or just simply writing unit tests, is a simple task with MVC.

Extensible
MVC follows the convention over configuration principle. At the same time, it isn’t meant to constrain developers by its conventions. MVC is built on an extensible framework that virtually every component can be easily replaced with your own logic.

Routable
ASP.NET MVC uses ASP.NET Routing to associate URL patterns with controller actions. This means that your MVC applications will naturally be search-engine optimized, since every controller action that corresponds to an HTTP GET can get be easily discovered.

Now’s let’s briefly discuss the differences between WebForms and ASP.NET MVC.
While MVC is built on top of ASP.NET, it doesn’t have…
Postbacks
View state or control state
Server-side form
Page/control lifecycle
The page/control lifecycle is still present if you’re using WebForms as your view engine, but even then, you most likely won’t be using it.

Example of ASP.NET MVC

Here we see an example of the default project structure of an ASP.NET MVC application.




Because ASP.NET MVC comes packaged with a set of default conventions, it’s important to understand those conventions, and even better how you can override them if you want.
Here we see the controllers, placed in the Controllers folder. You actually don’t have to place your controllers in this folder, but it is created for you by default, and is considered a pretty standard place for them.
The ASP.NET MVC project templates places a folder called Models in your project that can be used to contain your model classes. This is only one option for model placement, and shouldn’t be seen as guidance that this is the “right way” to do it. Your model classes are in no way coupled to their placement, so you can put them in a different folder, or even in another project if you want.

Views in an ASP.NET MVC application are by default located in the Views folder. Within the Views folder, there are two options to place your views:
Either underneath the Shared folder, which are views that are meant to be used by multiple controllers. These are typically user controls or master pages.
Or underneath a folder named after the Controller they are associated to. These are views that are specific to controllers.

This is the default convention, but it can be changed if you want. We’ll go into customizing this in the next session.

The route definitions that map URL patterns to your controllers are declared within your application’s Global.asax file. This way they can be created upon Application Start.

LINQ Architecture and Components




LINQ is currently integrated directly into the native syntax for both C# 3.0 and VB 9.0 – which are included with Visual Studio 2008

Other languages may also support Language Integrated Query syntax in the future.
There are many flavors of LINQ which we describe by the type of data it operates over. As you can see here, LINQ may operate over Objects, SQL, Datasets, and XML.

These are the four flavors of LINQ that we are shipping with the .NET Framework 3.5

LINQ to Objects
SQL-like queries for any .NET collection (or anything that implements Ienumerable)
The LINQ to Objects API supports queries over any .NET collection, such as arrays and generic lists.

This API is defined in the System.Linq namespaces inside System.Core.dll
LINQ to objects is enabled by including the System.Linq namespace.
Manipulating collections of objects, which can be related to each other to form a hierary or a graph. From a certain point of view, LINQ to Objects is the default implementation used by a LINQ query.

LINQ to SQL
Query enabled data access framework

LINQ to XML
Query enabled, smaller, faster XML DOM

The important thing to remember is that the querying syntax used in LINQ is consistent regardless of the type of data you’re working with.

FAQ

Will there be support for Oracle with LINQ to SQL?

There is no provider model for DLINQ. In order for a third party provider to support DLINQ, they would need to produce an entire API that mirrors DLINQ that covers everything from query generation to examining attributes on classes to providing a designer to interact with the database schema. Because there's a lower bar for enhancing a provider to support the Entity Framework (primarily just query generation), Oracle is only planning to support the Entity Framework.
 

Introducing LINQ




Orcas significantly improves the way developers handle data.
Traditionally developers have manipulated data differently depending on where the data resides and how the user connects to it.

With the introduction of Language Integrated Query developers can now deal with data using a consistent programmatic approach and perform data access with new data design surfaces.

LINQ aimes to reduce the complexity for developers and help boost their productivity through a set of extensions to the C# and Visual Basic programming languages as well as the Microsoft .NET Framework, which provides integrated querying for objects, databases, and XML data.

Using LINQ, developers will be able to write queries natively in C# or Visual Basic without having to use specialized languages, such as Structured Query Language (SQL) and Xpath.

With Visual Studio “Orcas”, you can work with data in the way that you want. You can create entire collections of objects from a database backend if you like. You can interact with data as rows or columns – whatever makes sense to your application.
Language Integrated Query or “LINQ” will dramatically change the way we work with and program against data. By creating a common querying language in LINQ, we’ve freed you, the developer to focus on things that matter most to you. LINQ will provide you the ease of use you’ve come to expect with Visual Studio offering both IntelliSense and Autocompletion right in the IDE.

Language Integrated Query provides native querying syntax in C# and VB.Net. This frees the developer from having to master independent data programmability technologies (e.g. Xpath, Xquery, T/SQL) and instead offers the developer a consistent way to query data.

The best part is that the LINQ code you write is consistent whether your data store is a SQL Server, contained in a ADO.NET DataSet, an XML document, an EDM you create or even objects you create in memory.

With Orcas, we have taken a more general approach and are adding general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data.

This facility is called .NET Language Integrated Query (LINQ).
With Orcas and ADO.NET 3.5, LINQ is an inherent part of the C# and VB.Net languages offering both IntelliSense and Autocompletion.

LINQ provides developers with a consistent query language which they in turn may use on various types of data. Be it Objects, XML, Datasets, SQL Server (or other databases with ADO.NET providers) and Entities. Any data that may be placed into a .NET collection of type IEnumerable can be queried by LINQ.

If you’ve written T/SQL in the past then LINQ will offer you familiar constructs for projections, restrictions, sorting and grouping such as Select, Where, GroupBy, and OrderBy.

You can also adapt the query operators to your liking by using extension methods which can override their default behavior.

.Net Framework and VS Roadmap



.NET Framework 3.0

First, if we travel back in time to November of 2006, Microsoft released the .NET Framework 3.0.

.NET Framework 3.0 was installed by default with Windows Vista, however, it was also available as a installable component for Windows XP SP2 and Windows Server 2003.

Visual Studio Extensions

When we released the .NET Framework 3.0, we also released a couple of extensions for Visual Studio.

The first extensions, called the Visual Studio 2005 Extensions for Windows Workflow Foundation, provided templates and design-time support for creating workflows within Visual Studio. It is worth noting that this was a complete and fully supported set of extensions.

The second extensions were the Visual Studio Extensions for the Windows Communication Foundation and Windows Presentation Foundation November CTP.

These extensions simply provided project and item templates for building WCF services and WPF applications.

ASP.NET Ajax

Shortly after the release of the .NET Framework 3.0, Microsoft also released the ASP.NET AJAX 1.0 extensions.
These extensions are designed to enable web developers to build dynamic applications with ASP.NET 2.0.

Visual Studio 2008 and .NET Framework 3.5

It’s important to understand these out-of-band releases as we look at Visual Studio 2008 and the .NET Framework 3.5. Visual Studio 2008 and the .NET Framework 3.5 include enhanced versions of the technologies that have been released out-of-band, such as AJAX and design time support for WF, WPF, and WCF applications.
At this point in time the beta 2 release of Visual Studio 2008 and the .NET Framework 3.5 are available.

It is also worth mentioning that there is a go-live license available with the .NET Framework 3.5. So you can deploy applications into production using this license. To be clear, there is a difference between licensed and supported. The .NET Framework 3.5 will not be supported until it is officially released.
Visual Studio 2008 and the .NET Framework 3.5 are scheduled to be released at the end of 2007 and they will launch with Windows Server 2008 and SQL Server 2008 on Februrary 27th.

Beyond the release of Visual Studio 2008 and the .NET Framework 3.5
After the release of these technologies, there will be an update to the .NET Framework that will be released with SQL Server 2008. This update will add support for the ADO.NET Entity Framework, which will enable flexible data access to a variety of data stores.

Finally, next year we plan to release a major update to Visual Studio Team System and Team Foundation Server codenamed “Rosario”.

What is .Net Framework 3.5 ?

Do you or any of your customers suffer from…version confusion? I’m referring to .NET Framework versioning confusion.I know that I have frequently been asked by customers questions like:

So what is the .NET Framework 3.5?

There is a fair amount of confusion about the different versions of the .NET Framework. It’s important that we spend a few minutes to clarify any confusion that might exist in this room.

Let’s walk through this diagram:




.NET Framework 3.5

The .NET Framework 3.5 is an incremental release of the .NET Framework. It provides several new enhancements including LINQ, ASP.NET 3.5, the CLR Add-in framework and several others.

The .NET Framework 3.5 builds upon the previous versions of the framework, namely the .NET Framework 2.0 and 3.0. More specifically, you can think of it as though the .NET Framework 3.5 has a dependency on the .NET Framework 3.0 with SP1 and 2.0 with SP1.

.NET Framework 3.0

The .NET Framework 3.0, which was formerly known as WinFx, introduced several key new technologies including:

Windows Presentation Foundation – provides the ability to build rich, interactive client applications
Windows Communication Foundation – provides a common programming model for building services and connecting applications
Windows Workflow Foundation – provides the ability to define declarative, long-running workflows
Windows CardSpace – provides a safer and more secure alternative to username and password authentication within web sites and rich client applications

.NET Framework 2.0

Finally, the .NET Framework 2.0, which was initially released in 2005 provides the common language runtime and base class libraries that are used by the .NET Framework 3.0 and 3.5 components.

So how will developers get the .NET Framework 3.5?

The .NET Framework 3.5 will be available as an optional update through Windows Update, as a bootstrapper installation, and as a full package.

With all of these packages, your machine will be examined during the installation and the .NET Framework 2.0 with SP1, 3.0 with SP1, and the new 3.5 assemblies will be installed.

The setup for the .NET Framework 3.5 will only install the necessary bits. So if the .NET Framework 2.0 or 3.0 is already installed, then only the service packs and the 3.5 bits will be added.

Saturday, May 23, 2009

Creating a WebService in ASP.NET , C#

This post deals with the basic theory of the web service.

What is a Web Service?

Web Services can convert your applications into Web-applications.

•Web services are application components
•Web services communicate using open protocols
•Web services are self-contained and self-describing
•Web services can be discovered using UDDI
•Web services can be used by other applications
•XML is the basis for Web services

How Does it Work?
The basic Web services platform is XML + HTTP.

XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.

The HTTP protocol is the most used Internet protocol.

Creating and consuming web service is done in 3 broader steps:

A. Create a Web Service class and method
B. Add Web-Reference to the project
C. Consume the created web service in the ASP.NET code.

A. Create a Web Service class and method

Step 1: Creating Web Project

Open Visual Studio and create a new Web Site. Name it whatever you want. Here, it is named WSDemo.



Step 2: Adding New Item

A new web project will open with a default.aspx and aspx.cs file. Right Click on project and click 'Add New Item'.



This will open the 'Add New Item' Dialoge box. Select template 'Web Service' and name it WS.asmx.



You will notice that two new files has been added: WS.aspx and WS.cs under App_Code



Adding a web service file will add WS.asmx file. If you open the WS.cs file, you will notice lot of pre-coded lines there.



A class must inherit System.Web.Services.WebService in order to behave like a web service.

Also, a HelloWorld method is added by default. The normal method can be converted to a webmethod by adding the following line on top of that method:

[WebMethod]

Step 3: Adding Custom Code:

My objective is to write a webmethod that will accept two parameters and return the sum of those two numbers. So, I removed the HelloWorld method and added my own Add Method.

[WebMethod]
public int Add(inta, int b)
{
return a+b;
}





At this point, your webservice clas is ready.

In order to test whether web service is created successfully or not, build the website and right click the WS.asmx and click 'View in Browser'. This action will open the webservice in browser and display the webmethod as a link.

Clicking on the WebMethod will ask for the input parameters that we defined (a, b) and submitting the form will show the result in a xml file.

B. Add Web-Reference to the project

Now when the web service has been developed, we need to add the web reference to the project. In order to do so , follow these steps:

Step 1: Click Add WebReference

Right click the project and select 'Add Web Reference'



Step 2: Browse for the web service

This action will open the 'Add Web Reference' wizard. It will ask use rto select the location where the web service is their. Since for our purpose, web service is in the solution, click 'Web Service in the solution'



Step 3: Selecting the web service:

Select the web service 'WS'. This will check the webservice 'WS' and list out all the WebMethods. During this process, you will see a progress bar liek this:



Step 4: Defining namespace and adding the reference:

After the internal process, wizard will list out the webmethods found in that webservice. If you chek the image below, there are few things to notice:

i. URL : That is the url fo the webservice. You can access the webservice WS directly from browser also.

ii. Webmethod Name: 'Add' is the name of our web method.

iii. Web Reference Name: This will be the namespace of the webservice.You can change it to your desired name. For demo purpose, I have kept it the default 'localhost'.





Clicking 'Add Reference' will add the web reference to the project and add the following files:



Here 'localhost' is the namespace. There are discovery file and WSDL file. I will explain the file types in next post..

This means web-reference has been added.

C. Consume the created web service in the ASP.NET code.

Now after creating and adding reference, we need to consume the web service.

Step 1: Modify the ASP.NET page:

In the default.aspx, add the following code:



<form id="form1" runat="server">
<div>
Enter value 1:<asp:TextBox ID="A" runat="server"/>
Enter value 2:<asp:TextBox ID="B" runat="server"/>
<asp:Button id="btnSubmit" runat="server" Text="Add" onclick="btnSubmit_Click" />
<hr />
Sub Result: <asp:Label id="lbl" runat="server"/>
</div>
</form>


Now we need to access the webservice from code. That we do by referring the namespace 'localhost'.

In the btnSubit Click event , add the following code:

localhost.WebService AddService=new localhost.WebService();
lbl.Text=AddService.Add(Int32.Parse(A.Text),Int32.Parse(B.Text)).ToString();




Finally, build the website and run the application, default.aspx will open .Enter two values and click 'Add'.
The result will be shown in the label.



Please feel free to contact me if you have any query..