Thursday, June 25, 2009

Partial in c#


In a nutshell, partial classes mean that your class definition can be split into multiple physical files.

So it is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

To split a class definition, use the partial keyword modifier, as shown here:

public partial class Employee
public void DoWork()

public partial class Employee
public void GoToLunch()

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace.


1. All the parts must use the partial keyword.
2. All the parts must be available at compile time to form the final type.
3. All the parts must have the same accessibility, such as public, private, and so on.
4. If any part is declared abstract, then the whole type is considered abstract.
5. If any part is declared sealed, then the whole type is considered sealed.
6. If any part declares a base type, then the whole type inherits that class. All the parts that specify a base class must agree, but parts that omit a base class still inherit the base type.
7. Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations.
8. Any class, struct, or interface members declared in a partial definition are available to all the other parts. The final type is the combination of all the parts at compile time.
9. The partial modifier is not available on delegate or enumeration declarations.

Nested Types with partial:

Nested types can be partial, even if the type they are nested within is not partial itself.

class Container
partial class Nested
void Test() { }
partial class Nested
void Test2() { }

Attributes with partial:

At compile time, attributes of partial-type definitions are merged. For example, consider the following declarations:

partial class Moon { }

partial class Moon { }

They are equivalent to the following declarations:

class Moon { }


1. All partial-type definitions meant to be parts of the same type must be modified with partial.
2. All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
3. The class name and generic-type parameters must match on all partial-type definitions. Generic types can be partial. Each partial declaration must use the same parameter names in the same order.
4. The following keywords on a partial-type definition are optional, but if present on one partial-type definition, cannot conflict with the keywords specified on another partial definition for the same type: public, private, protected, internal, abstract, sealed, base class, new modifier (nested parts), generic constraints.


They allow programmers on your team to work on different parts of a class without needing to share the same physical file. While this is useful for projects that involve big class files, be wary: If you find your class file getting too large, it may well signal a design fault and refactoring may be required.

The most compelling reason for using partial class is to separate your application business logic from the designer-generated code. For example, the code generated by Visual Studio 2005 for a Windows Form is kept separate from your business logic (we will discuss this in a later section). This will prevent developers from messing with the code that is used for the UI. At the same time, it will prevent you from losing your changes to the designer-generated code when you change the UI.

Partial Methods

Partial methods are methods living in partial classes which are marked as partial.


1. A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
2. Partial method declarations must begin with the contextual keyword partial and the method must return void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
6. Partial methods can have static and unsafe modifiers.
7. Partial methods can be generic.
8. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.
9. You can make a delegate to a partial method that has been defined and implemented, but not to a partial method that has only been defined.

C# Generics


Generics are the most powerful feature of C# 2.0 which allow you to define type-safe data structures, without committing to actual data types. We can use generics in classes and in structs.

To do that, use the < and > brackets, enclosing a generic type parameter.


public class MyStack
T[] myItems;
public void Push(T item)
public T Pop()

MyStack stack = new MyStack();
int number = stack.Pop();

When using a generic stack, you have to instruct the compiler which type to use instead of the generic type parameter T, both when declaring the variable and when instantiating it:

MyStack stack = new MyStack();

The advantage of this programming model is that the internal algorithms and data manipulation remain the same while the actual data type can change based on the way the client uses your server code.

Problem with object based solution

Performance isuue due to boxing/unboxing
No compile-time type safety


Significant performance boost
Higher quality code
Reuseable code and the effort
Type-safe at compile-time.
Gives no boxing, no casting advantage.

New to ASP.Net 2.0

1. Master Pages: It is meant for applying a consistent look and feel for a whole web site.It is a template for other pages, with shared layout and functionality. The master page defines placeholders for content pages. The result page is a combination (merge) of the master page and the content page.

2. Themes: It allow developers to create a customized look for web applications.

3. Web Parts: WebParts are all about personalization. It allows user customization of style and content based on User's preferences.

4. Navigation: Added controls like Site Maps, Dynamic HTML menus, Tree Views.

5. Security: Added controls like Login, LoginStatus, LoginName, LoginView, CreateUserWizard, PasswordRecovery.

6. Roles and Personalization: For storing user details.

7. Globalization: Improved support for multiple languages.

8. Data Access: Added new data controls, removing much of the need for programming and in-depth knowledge of data connections. E.g., SqlDataSource, AccessDataSource, XMLDataSource, ObjectDataSource, SiteMapDataSource.

9. Mobility Support: The Microsoft Mobile Internet Toolkit (MMIT) provided this support. MMIT is no longer needed because mobile support is built into all controls.

10. Images: Added new controls for handling images: The ImageMap control (image map support) and the DynamicImage control (image support for different browsers).

11. Automatic Compilation: All files within a directory will be compiled on the first run, including support for WSDL, and XSD files.

12. Compiled Deployment (Installation) and Source Protection: It provides pre-compilation. An entire web site can be pre-compiled. This provides an easy way to deploy (upload to a server) compiled applications, and because only compiled files are deployed, the source code is protected.

13. Site Management: It has three new features for web site configuration and management - Local management console, programmable management functions (API) and web-based management tool .

14. Development Tools: Visual Studio 2005

ASP.Net 2.0 has added numbers of new controls. You can find the complete list here along with their brief overview.

New ASP.Net 2.0 Controls

1. ImageMap: This control extends the Image control with a collection of clickable hot spots. You can create (and configure the dimensions of) as many rectangle, circle, and polygon hotspots as you need. The HotSpotMode property can be used to specify whether the user’s click should cause a postback or navigate the user directly to a URL.

2. BulletedList: When you need to display a bulleted list on your page, this control is a perfect fit. In addition to the databinding capabilities , there are also such useful properties as BulletStyle, which can be set to circles, squares, numbers, roman numerals, custom images, etc. With the DisplayMode property you can specify that the list items be represented by standard text, HyperLinks, or LinkButtons.

3. MultiView: The MultiView control manages multiple View controls to ensure only one is visible at a time. Using the ActiveViewIndex property of the MultiView control we can specify which View should be visible at any particular time. Each View control acts as a content container, and behaves very much like a Panel control at design time.

4. View: Each View control can contain any combination of controls you desire.

5. GridView: A feature-rich replacement for the DataGrid. The DataGrid control was good for its time, but its time is over. It still exists for backward compatibility purposes, but it’s no longer listed in the Visual Studio 2005 toolbox by default. The replacement is the new GridView control, which is better in every way. The paging and sorting functionality is now far more automated, and yet still extensible in case you want to get your hands dirty. The GridView control renders more efficiently than the DataGrid control did, and it supports a wider variety of column types: BoundField, ButtonField, CheckboxField, CommandField, HyperLinkField, ImageField, and TemplateField.

6. DetailsView: The DetailsView control displays the details of a database record on a page. The automated display and editing capabilities provide the potential to eliminate lots of boilerplate code. Like the GridView, it automatically displays appropriate controls when in edit mode and allows for detailed customizations via templates. The DetailsView control can be used by itself, but when combined with the GridView control it provides an elegant solution to many common Master/Detail scenarios.

7. FormView: The FormView control contains seven templates, which can be modified and displayed in varying combinations to support a variety of functionality. The view must be configured via templates at run time or else nothing will appear on the form at run time.

8. LoginView: Displays different sets of controls based on the user’s login status.

9. TreeView: One of the most feature-rich controls of ASP.NET 2.0, but not truly a View control in the same sense as these other View controls.

10. Wizard: This new control takes the MultiView concept to the next level. This rich control lets you create a fully functional wizard to lead users through a sequential set of steps. You can create and configure as many steps as you need in the wizard at design time via the new SmartTag technology of the Visual Studio 2005 designer. The designs you can create are highly customizable because of a flexible object model that permits the use of Templates to represent one or more of the steps. The wizard manages the Back and Next buttons appropriately and persists all control values between each step so you don’t have to worry about such mundane details.

11. Substitution: This new control works in cooperation with the OutputCache directive that’s been around since ASP.NET 1.x. Specifically, it acts as an exception to the OutputCache directive. Set the MethodName property to a valid function name in the page. Every time the page is requested, this function will be called and the return value will be automatically displayed in the Substitution control. This way you can be sure the contents displayed in the control will always be fresh, even though the rest of the page may be pulled from the cache.

12. SqlDataSource: Used for data binding to a Microsoft SQL Server (or SQL Server Express) database.

13. AccessDataSource: Used for data binding to a Microsoft Access database.

14. XMLDataSource: Used for data binding to XML files and streams.

15. ObjectDataSource: Used for data binding to custom middle-tier business objects.

16. SiteMapDataSource: Used for binding to a Site Map, which is stored in XML by default.

17. SiteMapPath: The new SiteMapPath control displays the user’s current location in the navigational hierarchy of the Web site. Each level is represented with a hyperlink so the user can quickly jump to their desired destinations.

18. Menu: This high-quality hierarchical menu control can appear vertically or horizontally. This exceptionally configurable navigation control can be bound to a SiteMapDataSource control or edited independently.

19. Treeview: The ImageSet property lets you automatically display a variety of useful and attractive images in front of each node. While the default behavior is to post back between each node click and raise a SelectedNodeChanged event, the Target property lets you specify another frame in which to display the address in the NavigateURL property, so no postback is required. You can also use the SelectAction property to specify other behaviors, such as expanding the node without a postback, doing nothing, or expanding the node and raising a postback event. Each node can optionally have a checkbox. The TreeView nodes can be configured at design time, bound to a SiteMapDataSource control, or, for larger tree structures, sub nodes can be loaded on demand to conserve server resources. This requires a postback after many of the user’s mouse clicks — except for uplevel browsers, which can take advantage of the automatically generated client-side AJAX code to call back to the server and fill in the nodes without requiring a full-page postback.

20. Login: The new Login control provides a user name and password screen that you may have created dozens of times before. However, you’ll never need to create one ever again, now that it’s been done in such a thoroughly reusable and extensible way.

21. LoginStatus: The new LoginStatus control displays in two different states. If the user is not logged in, it provides a hyperlink to the login page. If the user is logged in, it provides a hyperlink that logs them out. In either case, you can configure the hyperlink text that is displayed.

22.LoginView: The LoginView control is similar to the LoginStatus control, except instead of displaying a simple link, it will display whatever set of controls you’d like based on the user’s login status. It can display one set of controls for logged-out users, and another set of controls for logged-in users. It can also display varying sets of controls based on the current user’s role.

23. ChangePassword: Any decent authentication system must provide users with a way to change their password. The ChangePassword control provides such functionality by providing the standard three-textbox user interface for old password, new password, and verify new password. By default it accepts only strong passwords, and you can configure it to accept whatever combination of letters, numbers, and symbols your requirements demand.

24. PasswordRecovery: Any decent authentication system must also provide a way to deal with forgotten passwords. That’s where the new PasswordRecovery control comes in handy. This flexible control can handle a variety of common techniques for dealing with forgotten passwords, such as secret question/answer pairs, e-mailing a person their password, and/or generating a new password.

25. LoginName: The LoginName control displays the person’s user name when they’re logged in (or when it’s available automatically through Windows Authentication); it’s invisible when the user is not logged in.

26. CreateUserWizard: The CreateUserWizard control is a functionally rich control that allows a user to enter all the standard information a site generally requires to create a new user, such as their desired username, password, e-mail address, etc. It’s fully extensible, allowing you to add whatever custom fields you require. Because it inherits from the Wizard Web control, you can easily divide the user registration process into as many steps as you desire.

27. WebPartManager: The WebPartManager control’s purpose is to manage and orchestrate all the WebPart controls on the page. It is not visible at run time.

28. WebPartZone: Each instance of the WebPartZone control can hold one or more WebParts. Each WebPartZone can be minimized, moved, deleted, or added by the developer and (if configured to do so) by the user. Each user can configure the page to their own liking and the customizations will be remembered and persisted between each of their visits.

29. CatalogZone: The CatalogZone control contains CatalogPart controls, such as DeclarativeCatalogPart, PageCatalogPart, and ImportCatalogPart. These controls are used to create a catalog of WebParts that users can choose to add to their page.

30. EditorPart: EditorPart controls (such as the AppearanceEditorPart, BehaviorEditorPart, LayoutEditorPart, and PropertyGridEditorPart) can only be placed within an EditorZone control. These controls are used to allow users to edit and personalize pages.

31. ConnectionZone: The ConnectionZone control contains ConnectionPart controls. These are used to create connections between WebParts on a page. They permit one WebPart to send information to another WebPart.

32. ProxyWebPartManager: The ProxyWebPartManager control provides a way to specify static connections inside a content page when the WebPageMaster class has been added to a Master Page.

33. Report Viewer: The new Report Viewer control allows you to design reports visually from a DataSet or other data source. It can cache reports, generate reports on demand, retrieve pre-generated reports from SQL Server 2005 Reporting Services, and more.

34. CrystalReportPartsViewer and CrystalReportSource: CrystalReportViewer control from ASP.NET 1.x has been joined by two new companion controls: CrystalReportPartsViewer and CrystalReportSource. Both of these controls are invisible at run time. The CrystalReportSource control manages report data sources, parameters, and caching.

Apart from these new controls many of the older controls have enhancements. For example:

1. Button controls now support posting to other pages and have a declarative client-side OnClientClick event.
2. The Panel control now has scrollbar support so you can easily create scrolling areas within your page.
3. The Validation controls have been enhanced to support multiple independent validation groups within a single page.

Tuesday, June 23, 2009

Access Modifiers in c#

Access Modifiers in C#
Access Modifiers (Access Specifiers) describes as the scope of accessibility of an Object and its members. All C# types and type members have an accessibility level . We can control the scope of the member object of a class using access specifiers. We are using access modifiers for providing security of our applications. When we specify the accessibility of a type or member we have to declare it by using any of the access modifiers provided by C# language.

C# provide five access specifiers , they are as follows:

1. public: Access is not restricted.
2. protected: Access is limited to the containing class or types derived from the containing class.
3. internal: Access is limited to the current assembly.
4. protected internal: Access is limited to the current assembly or types derived from the containing class.
5. private: Access is limited to the containing type.

Default and allowed access modifiers for members

Default: public
Allowed: None

Default: public
Allowed: None

Default: private
Allowed: public, protected, internal, private, protected internal

Default: private
Allowed: public, internal, private

System.String Vs System.Text.StringBuilder

The System.String object is immutable, once set, the content of a String object cannot be modified. Trying to change its value succeeds, but this actually destroys the old String object and creates a new one, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. It will not create a new string object but instead append to the existing string. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

The StringBuilder's initial capacity is set to 16 by default. The capacity then increases by an order of 2 whenever the current capacity is passed.

The size of a StringBuilder object's storage can be obtained from the class' Capacity property. The length of the string in a StringBuilder object can be obtained from its Length property. The capacity can be increased or decreased with the Capacity property or EnsureCapacity method, but it cannot be less than the value of the Length property.

Web Farm Vs Web Gardening

Web Farm:

A web farm is a multi-server scenario. A Web farm allows you to expand a Web Site across multiple servers. E.g., we may have a server in each state of US. If the load on one server is in excess then the other servers step in to bear the brunt. The main reason behind the scene is to distribute the load over the multiple server. Load balancer is used to distribute the load on those server.

It can based on various models:

1. RoundRobin. (All servers share load equally)
2. NLB (economical)
3. HLB (expensive but can scale up to 8192 servers)
4. Hybrid (of 2 and 3).
5. CLB (Component load balancer).

Web Garden:

By default Each Application Pool runs with a Single Worker Process (W3Wp.exe). We can Assign multiple Worker Process With a Single Application Pool. An Application Poll with multiple Worker process is called Web Garden. Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time.

A Web garden allows you to expand a Web Site across multiple CPUs within a single server. So a web garden is a multi-processor setup. i.e., a single server. In a Web garden, HTTP.sys distributes the requests among the set of worker processes in the application pool.

It can based on various models:

1. inproc (non web farm but fast when you have very few customers).
2. StateServer (for webfarm)
3. SqlServer (for webfarm)

Creating a Web garden for an application pool can also enhance performance in the following situations:

-> Robust processing of requests: When a worker process in an application pool is tied up (for example, when a script engine stops responding), other worker processes can accept and process requests for the application pool.

-> Reduced contention for resources: When a Web garden reaches a steady state, each new TCP/IP connection is assigned, according to a round-robin scheme, to a worker process in the Web garden. This helps smooth out workloads and reduce contention for resources that are bound to a worker process.

Note: There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process. For Avoid this Type of problem we should have to use Session Mode "out proc" and we can use "Session State Server" or "SQL-Server Session State".

More details: InProc is handled by Worker Process. Its keeps data insides its memory object. Now if we have multiple Worker Process, then it would be very difficult to handled the session because, each and every Worker process has it own memory, so if the first request goes to WP1 and its keep the session data and Second Request goes to WP2 and when we try to retrieve session data, it will not able to return . Which will throw error. So we should always avoid Web Garden in InProc Session Mode.

Monday, June 22, 2009

IEnumerable and IEnumerator

In the .NET Framework, these two interfaces are designed to allow you to iterate easily over collections of objects as you would typically do in a for loop. Many classes in the .NET Framework have implemented these interfaces and do their work behind the scenes so we don’t have to worry about how it is done.

Any classes implementing these two interfaces are classified as an enumerable collection. This means that User-defined class behaves like any other collection object written by Microsoft, such as an ArrayList.

There are many features that define an enumerable collection, and by implementing these two interfaces, the framework guarantees that this object has these features. For example, an enumerable collection must have a method called MoveNext, which moves the cursor within the collection one step forward. By implementing the IEnumerator interface, the class is promising (and is required) to implement this method.

IEnumerator and IEnumerable interfaces are defined in System.Collections namespace.


MSDN describes the IEnumerator class as "Supports a simple iteration over a collection.", as well as:

"IEnumerator is the base interface for all enumerators. Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. Reset also brings the enumerator back to this position. At this position, calling Current throws an exception. Therefore, you must call MoveNext to advance the enumerator to the first element of the collection before reading the value of Current."

IEnumerator is an interface that has following members:

-> Property: Current
-> Method: MoveNext
-> Method: Reset

Presumably, any element in a collection can be retrieved through its index property. But instead of element index, the IEnumerator provides two abstract methods and a property to pull a particular element in a collection. And they are Reset(), MoveNext() and Current.

public interface IEnumerator
bool MoveNext(); //An enumerator is always positioned before the
//first element of the collection, first call to MoveNext
//moves the enumerator over the first element of the
object Current { get ; } //Returns current object from the collection
void Reset(); //Resets enumerator to just above the first element of the collection.


IEnumerable is an interface that has 1 method called GetEnumerator. The MSDN documentation describes the GetEnumerator method as "Exposes the enumerator, which supports a simple iteration over a collection."... It then goes on to say "IEnumerable must be implemented to support the ForEach semantics of Microsoft Visual Basic. COM classes that allow enumerators also implement this interface".

IEnumerable is an interface that has following member:

-> Method: GetEnumerator

public interface IEnumerable
//The signature of GetEnumerator() is as follows:
public IEnumerator GetEnumerator()
//return IEnumerator of our Custom Type

Note: IEnumerator interface is meant to be used as accessors and is not helpful to make any changes in the collection or elements of the collection.

Abstract class vs. Interface

You can think of an Interface as an abstract class with all the implementation stripped out and everything that is not public removed.

-> An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
-> Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
-> The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
-> A class can inherit one or more interfaces, but only one abstract class.
-> Abstract Class defines abstract member signatures which derived classes must implement. Otherwise, the derived class itself will be abstract. In Interface, compiler throws an error.
-> In Abstract Classes, we can include data fields. In Interface, we cannot include data fields. However, abstract properties may be declared.

Interface in C#

An interface can be a member of a namespace or a class and can contain signatures of the following members: Methods, Properties, Indexers, Events. The actual implementation is done in the class that implements the interface.

interface IIntelligence
/// Method declaration within the interface
bool intelligent_behavior();

/// Indexer declaration within the interface
object this[int index]
/// Event declaration within an interface
/// testEvent should also be declared as a delegate before
event testEvent IQEvent;

/// Property declaration within an interface
string IQProperty

-> An interface can inherit from one or more base interfaces.
-> A class or struct can inherit more than one interface.
-> An interface cannot contain fields.
-> The interface can't contain constants, data fields, constructors, destructors and static members.
-> Interfaces members are automatically public.
-> When a base type list contains a base class and interfaces, the base class must come first in the list.
-> A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface, for example:

interface IPoint
// Property signatures:
int x
{ get; set; }

int y
get; set; }

class Point : IPoint
// Fields:
private int _x;
private int _y;

// Constructor:
public Point(int x, int y)
_x = x;
_y = y;

// Property implementation:
public int x
{ return _x; }

{ _x = value; }

public int y
{ return _y; }
{ _y = value; }

class MainClass
static void PrintPoint(IPoint p)
Console.WriteLine("x={0}, y={1}", p.x, p.y);

static void Main()
Point p = new Point(2, 3);
Console.Write("My Point: ");

-> To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member.
-> Properties and indexers on a class can define extra accessors for a property or indexer defined on an interface. For example, an interface may declare a property with a get accessor, but the class implementing the interface can declare the same property with both a get and set accessor. However, if the property or indexer uses explicit implementation, the accessors must match.

Using "Is" and "As" Operators to Verify the Implementation of an Interface

"is" keyword is used to verify whether the method exists in the class implementing the given interface or not.

if(human is IIntelligence)

IIntelligence humanIQ = (IIntelligence)human;

In the example case above, when you will run it, it will give a warning that "the given expression is always of the provided type" and the validity is also been checked twice: one in using the "is" operator and the other when casting it to the interface type.

But we can also use the "as" operator to cast and check the types more efficiently. The "as" operator returns an object type and null if the type mismatched whereas the "is" operator returns a Boolean value. Here, no warning will be generated.

IIntelligence humanIQ = human as IIntelligence;

if(null != humanIQ)


Note: Microsoft STRONGLY recommends that ALL interfaces begin with the character 'I'.

Abstract in C#

The abstract modifier can be used with classes, methods, properties, indexers, and events.


Abstract modifier in a class declaration indicates that the class is intended only to be a base class of other classes. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

-> An abstract class can contain either abstract methods or non abstract methods. An abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members.
-> An abstract class cannot be instantiated.
-> An abstract class cannot be a sealed class.
-> A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
-> An abstract class must provide implementation for all interface members. An abstract class that implements an interface might map the interface methods onto abstract methods.
-> The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class.


abstract class MyBaseClass // Abstract class
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

public abstract int GetX // Abstract property

public abstract int GetY // Abstract property

class MyDerivedC: MyBaseClass
public override void MyMethod()

public override int GetX // overriding property
return x+10;

public override int GetY // overriding property
return y+10;

public static void Main()
MyDerivedClass mC = new MyDerivedClass();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);


-> Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
-> An abstract method is implicitly a virtual method.
-> Abstract method declarations are only permitted in abstract classes.
-> Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example: public abstract void MyMethod();
-> The implementation is provided by an overriding method, which is a member of a non-abstract class.
-> It is an error to use the static or virtual modifiers in an abstract method declaration.


Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

-> It is an error to use the abstract modifier on a static property.
-> An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

Thursday, June 11, 2009

Windows Presentation Foundation


The Windows Presentation Foundation , formerly code-named Avalon, is a graphical subsystem in .NET Framework 3.0, which uses a markup language, known as XAML, for rich user interface development. It is an entirely new UI technology based on the DirectX engine which facilitates the creation of vector based user interfaces rather than the conventional Windows bitmap based UI.

Windows Presentation Foundation (WPF) is a next-generation presentation system for building applications. With WPF, you can create a wide range of both standalone and browser-hosted applications. The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware.

It provides a consistent programming model for building applications and provides a clear separation between the user interface and the business logic. A WPF application can be deployed on the desktop or hosted in a web browser. It also enables rich control, design, and development of the visual aspects of Windows programs. It aims to unify a number of application services: user interface, 2D and 3D drawing, fixed and adaptive documents, advanced typography, vector graphics, raster graphics, animation, data binding, audio and video.

WPF features include:

1. Client Profile enables faster redistribution with a smaller download
2. 2D and 3D graphics and hardware accelerated effects
3. Common file format (XAML) allowing designers and developers to collaborate
4. Scalability to different form factors
5. Controls, data binding and extensibility enable developers to quickly build high fidelity applications

Windows CardSpace

What is Windows CardSpace?

Windows CardSpace (codenamed InfoCard) is client software that enables users to provide their digital identity to online services in a simple, secure, and trusted way. CardSpace provides a consistent UI that enables people to easily use these identities in applications and web sites where they are accepted.

Each card has some identity data associated with it—though this data is not actually stored in the card—that has either been given to the user by an identity provider such as bank, employer, or government, or created by the users themselves.

Information cards are managed on client computers by a software component called an identity selector. An identity selector is a user interface (UI) that appears when a user attempts to authenticate to a Web site that requests an information card. The following figure shows Windows CardSpace—the Microsoft implementation of an identity selector for Windows—in response to a demand for credentials by a Web site.

What Windows CardSpace Provides?

Four aspects of this technology stand out as most important:

1. Support for any digital identity system
2. Consistent user control of digital identity
3. Replacement of password-based Web login
4. Improved user confidence in the identity of remote applications

Advantages of information cards?

1. Information cards are more flexible than simple user names and passwords.
2. Information cards employ strong cryptography, which makes their use more secure than passwords.
3. Information cards can potentially present any type of identity claim that makes sense to all of the interacting parties and which users are willing to release.

Windows Communication Foundation

What is WCF?

WCF (Indigo was the code name for WCF) is a unification of .NET framework communication technologies. It is a unification technology, which unites the following technologies:
• NET remoting
• Web services
• COM+

WCF is based on SOA. Windows Communication Foundation is Microsoft infrastructure for Service Oriented architecture. Because WCF is part of the .NET Framework, applications that use WCF can be developed in any programming language that can target the .NET runtime.

What are the main components of WCF Service?

A WCF Service is composed of three parts/components:
1. Service class: implements the service to be provided,
2. Hosting environment: to host the service, and
3. End point: one or more endpoints to which clients will connect.

All communications with the WCF service will happen via the endpoints. The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods. The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.

Note: Web Services and Services are not identical. One main difference is Web Services use HTTP protocol, but Services can use any protocol and this is an important difference.

What are the advantages of WCF?

Windows Communication Foundation has some important enhancements in comparison with preceding technologies.

· It merges all older separate technologies in one place and allows you to do things easier.
· It has rich communication capabilities.
· It comes with many powerful and ready to use enterprise features.
· It can be integrated with other technologies and has great interoperability.


WCF’s single programming model unifies the capabilities in ASMX, WSE, Remoting, COM+, and MSMQ; therefore developers need to learn only one programming model.

In addition, WCF services now offer more design flexibility by supporting architecture such as Representational State Transfer (REST), JavaScript Object Notation (JSON), and Plain Old XML (POX) encoding.

Windows Workflow Foundation


It is a set of actions that is executed asynchronously by the engine provided by Windows WF. WFs are basically a set of activities. Activity is a step in workflow and is the unit of execution

One of the most interesting aspects of Windows Workflow Foundation (WF) is the separation between business process code and the actual implementation, often a requirement in Service Oriented Architecture (SOA). Before Windows Workflow Foundation the typical scenario would be to write both the business logic and the actual implementation in C#, Visual Basic .NET or another .NET language. The result was no clear separation between business logic and its implementation. With the release of Windows Workflow Foundation (WF) the business logic can be defined in the workflow while the actual underlying implementation is done in C#, Visual Basic .NET or another .NET language. So basically the what is done in the workflow and the how is done in traditional programming code.

Windows Workflow Foundation is basically a library consisting of an execution engine, a rules engine, a number of activities, a number of supporting runtime services and a designer allowing developers to design their workflows graphical in Visual Studio 2005 (VS2005). Since Windows Workflow Foundation is a library, not a standalone platform or service, the developer is completely free to include the Windows Workflow Foundation library in process in his own application or web site/service.

Base Components/Architecture:

• Host Process: Responsible for providing various runtime services to the workflow runtime engine.
• Runtime Engine: Responsible for workflow execution and state management
• Runtime Services: Provides additional functionality to the runtime engine.
• Base Activity Library: Set of general purpose activities for defining workflows.
• Visual Designer: Graphical and code-based construction

Hosting Model:

The WF runtime can be hosted in any .NET process
1) ASP.NET ( IIS ),
2) Windows Service,
3) Console applications,
4) Windows Forms applications,
5) Web Services ( IIS ).

Types of Workflow:

There are two main kinds of workflows:

1. Sequential (Sequential structure prescribes processing order): Its actions are executed in some predefined order with a beginning and an end. Examples of sequential workflows may include installations.

When to use Sequential Workflow:

-> The Workflow model can be express as a sequence of activities
-> The Workflow is in control of sequence of activities
-> The Workflow of its nature, encodes all the possible sequences of behavior in its structure
-> It is self driven

2. State machines (External events drive processing order): These workflows don't have a path, but it's represented as a set of states and transitions between states. Examples are a web shop: you may need approval for mailing, the user could pay via credit card or with a cheque, and each user is in one state and may go to any order depending on previous questions.

When to use State Machine Workflow:

-> The Workflow model does not have a defined path of execution
-> It may not be possible to model all the paths using a sequential workflow
-> The sequence of events is unpredictable
-> The Workflow to model is driven by external events

Few important terminology:

-> Activities: Windows Workflow Foundation provides a number of activities that you can use to send e-mail, handle errors, run code, or execute other tasks

-> Activity Framework: The activity framework provides a range of common functions used by many activities, such as validation, fault handling, and compilation

-> Workflow Runtime: The workflow runtime is the component that executes workflow instances with a host application

-> Persistence Service: Persistence services can be used to save a workflow instance to a data store if a workflow contains a long-running process

-> Transaction Service: We can use transaction services to ensure your data consistency in the event of communication or other failure

-> Tracking Service: Tracking services can be used to record which activities will execute in each workflow instance. They can also record when each activity executes. Use tracking services to troubleshoot or debug workflows

-> Scheduling Service: Scheduling services can be used to control how a workflow runtime creates threads for the instances of your workflow

.Net Framework 3.0


The .NET Framework 3.0 (formerly known as WinFX) is the next step as the platforms on which developers build get better and better. The .NET Framework 3.0 is an evolution, adding more to what version 2.0 of the Framework already provides.

The .NET Framework 3.0 does add four new components:
1. Windows Workflow Foundation,
2. Windows Communication Foundation,
3. Windows CardSpace, and
4. Windows Presentation Foundation.

Challenges Vs. Solutions:

Challenge 1: Organizations are increasingly taking a process-oriented view of what they do. Since most applications automate some part of a business process, it can be useful to make the steps in this process explicit in the code. An effective way to do this is by using workflow technology, an approach that requires support for workflow-based applications.

Solution: Windows Workflow Foundation (Support for Workflow-Based Applications)

Challenge 2: Applications commonly communicate with other applications, both inside and outside the organization. Modern applications also must often fit into a service-oriented architecture (SOA), exposing some of their functionality as interoperable services accessible by other software. Achieving these goals requires support for service-oriented applications.

Solution: Windows Communication Foundation (Support for Service-Oriented Applications)

Challenge 3: The people who use an application commonly need a way to convey information about who they are. Many different technologies for defining and using a digital identity are in use, and problems such as phishing are common. Given this, a modern application and the people who use it can benefit from consistent user control of digital identities.

Solution: Windows CardSpace (Consistent User Control of Digital Identities)

Challenge 4: The requirements for a modern user interface have grown significantly. Providing real business value can commonly require working with various kinds of documents, using two- and three-dimensional graphics, displaying video, and more. All of this also needs to be available for both native Windows clients and Web browsers. Meeting these needs requires a unified approach to diverse user interfaces.

Solution: Windows Presentation Foundation (A Unified Approach to Diverse User Interfaces)


In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.

Tuesday, June 9, 2009

Problem using Response.Redirect and Response.End in Try/Catch block

If we are using Response.End or Response.Redirect statements in TRY/CATCH block, code in catch block is still executed.

ASP.NET executes these 2 methods on Response object by throwing ThreadAbort Exception. When written in simple Try/Catch block this results in Catch block catching this exception and processing code written in catch block. This causes unwanted code execution which is generally written in Catch block.

To resolve this, we should always handle ThreadAbort exception separately and do nothing if it is thrown.

// Your code
catch (ThreadAbortException exc)
// This should be first catch block i.e. before generic Exception
// This Catch block is to absorb exception thrown by Response.End or Response.Redirect
catch (Exception exc)
// Your actual error handling code

However we can avoid this scenerio in case of Response.Redirect. Response.Redirect fails within a Try catch block because the thread stops execution when it reaches this line and it could be avoided by specifying the endExecution optional parameter as false in the statement.

E.g., Response.Redirect("your redirection url", false);

Retaining last scroll position after postback

When a request is submitted to the server through any auto-postback enabled control, after the postback, by default user is returned to the top of the page. Last week we have a requirement to scroll down the user automatically to the last position on the page after the postback.

After a bit of GOOGLING, we came to know that we can do this in different levels, like Application level, Page level or even using our code. MaintainScrollPositionOnPostBack page property should be used to acheive this.

1. Application level: This way the functionality will be applicable to all the pages in the application/website. Add the following attribute to the pages node in your respective web.config file:

<pages maintainScrollPositionOnPostBack="true">

2. Page Level: This way the functionality will be applicable to a particular page in the application/website. Open the aspx page and set the property in the page directive as shown below:

<%@ Page MaintainScrollPositionOnPostback="true" ... />

3. Code level: To set this property programmatically(C# code below), you can write the following line of code:

Page.MaintainScrollPositionOnPostBack = true;

Note: We have tested this in IE 6+ and FF 3+. In both the cases this works fine.

Wednesday, June 3, 2009

Part 2: Get all the Lists Items of a List using Lists.asmx webservice

This series is in continuation of demonstrating how to access SharePoint data “behind the scenes” without having to run the program on the SharePoint server. In Part 1 of this series, I have demonstrated how to access the SharePoint service using a web reference as well as how to access all the lists of a particular site. In this session, I will demonstrate how to get all items of a particular sharepoint list.

Step 1: First you need to create a Visual Studio Project. You can create a Webpart or Web Control or Console Application as per your requirement.

Step 2: Add the following code at the beginning:
using System.Xml;
using System.Data;
using System.Net;
using Microsoft.SharePoint;
/* Optional */

Step 3: Add a Web reference with the following URL:
http://[your site url]/_vti_bin/Lists.asmx and name it as "WS" (or anything else, you just need to update that accordingly in the code block shown below).

Step 4: Add the following code:

WS.Lists listService = new WS.Lists();

/* This line is optional for root level site. If the site is a sub-site or under /sites/, then you need to write this, otherwise the code will always try to find a list in the root. */
listService.Url = "http://[your site url]/_vti_bin/Lists.asmx";

listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

XmlDocument xmlDoc = new System.Xml.XmlDocument();

XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

/* The commented statements below is optional. If applicable if you want to pass any queries, or need some specific columns to return, or need to pass any query options. */
/*ndQuery.InnerXml = "<where><and><gt><fieldref name='Field1'>" +
"<value type='Number'>5000</value></gt><gt><fieldref name='Field2'>" +
"<value type='DateTime'>2009-05-01T00:00:00</value></gt></and></where>";
ndViewFields.InnerXml = "<fieldref name='Field1'><fieldref name='Field2'>";
ndQueryOptions.InnerXml =
"<includemandatorycolumns>FALSE</includemandatorycolumns>" +

/* "My List" below is the name of the sharepoint list. */
XmlNode ndListItems = listService.GetListItems("My List", null, ndQuery, ndViewFields, null, ndQueryOptions, null);

/* Here I have used DataSet and Datatable, but you can also parse the returned XML directly */
XmlReader reader = new XmlNodeReader(ndListItems);
DataSet ds = new DataSet();

/* You can find two tables, one is "data" and the other one is "row". We will get all the items in the later one */

foreach (DataRow dr in ds.Tables[1].Rows)
/* You can replace Console.WriteLine accordingly if you are not using Console Application */

The code above will return all the lists item's Title column value of the particular List. If you need other column's value, you can use the corresponding column name. You can find out the other column names using the following code:

foreach (DataColumn dc in ds.Tables[1].Columns)

Part 1: Get all Lists using Lists.asmx webservice

There are two ways you can reference SharePoint when writing code:
• Reference and use the classes the Microsoft.Sharepoint library
• Make a web reference to the SharePoint services.

While referencing and using the classes in the Microsoft.SharePoint library is the easier coding method of the two, but it requires that you run the program on the same server where SharePoint is installed. You may have a situation where you don’t want to run the code on the same server as SharePoint.

This series will demonstrate how to access SharePoint data “behind the scenes” without having to run the program on the SharePoint server. In Part 1 of this series, I will demonstrate how to access the SharePoint service using a web reference as well as how to access all the lists of a particular site. In Part 2 of this series, I will demonstrate how to get all items in a particular list.

Step 1: First you need to create a Visual Studio Project. You can create a Webpart or Web Control or Console Application as per your requirement.

Step 2: Add the following code at the begenning:
using System.Xml;
using System.Data;
using System.Net;
using Microsoft.SharePoint; /* Optional */

Step 3: Add a Web reference with the following URL:
http://[your site url]/_vti_bin/Lists.asmx and name it as "WS" (or anything else, you just need to update that accordingly in the code block shown below).

Step 4: Add the following code:

private static void GetAllList()
WS.Lists listService = new WS.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

XmlNode ndLists = listService.GetListCollection();

/* Here we have used DataSet and Datatable, but you can also parse the returned XML directly */
XmlReader reader = new XmlNodeReader(ndLists);
DataSet ds = new DataSet();

foreach (DataRow dr in ds.Tables[0].Rows)
/* You can replace Console.WriteLine accordingly if you are not using Console Application */
Console.WriteLine(dr["Title"].ToString()); /* dr["Name"].ToString() will return the GUID*/

The code above will return all the lists and document libraries including galaries like masterpage, webparts, etc. If you need anything specific, you can filter that using other fields available. You can find out the other fields using the following code:

foreach (DataColumn dc in ds.Tables[0].Columns)

Tuesday, June 2, 2009

Static Webpart Vs. Dynamic Webpart

Static Webpart Vs. Dynamic Webpart: A Web Part zone typically contains one or two Web Parts. However, Web Parts do not have to be placed into a zone on the Web Part Page.
Static WebpartDynamic Webpart
Web Parts that are placed outside of a Web Part zone are called static Web Parts.Web Parts that are contained within a Web Part zone are called dynamic Web Parts.
They are treated and act just like a standard Web control.They are treated and act just like a standard Web part.
A static Web Part and its properties are stored within the Web Part Page (.aspx) file.The properties of a dynamic Web Part are saved to a content database.
A user cannot interact with a static Web Part or modify it within a browser.Users can access the properties and manipulate these properties.

Show detailed error message in SharePoint

Exceptions that are caught by SharePoint are generally displayed in a friendly error message instead of a detailed error message with stack trace.

To display the full exception needed for debugging make the following changes to your SharePoint site’s web.config file (Inetpub\wwwroot\wss\VirtualDirectories\[respective Port Number]\web.config).

· Find: <SafeMode CallStack="true" />
· Replace with: <SafeMode CallStack="false" />

· Find: <customErrors mode="On" />
· Replace with: <customErrors mode="On" />

· Find: <compilation debug="false" />
· Replace with: <compilation debug="false" />

Reproduce the problem and the true exception will be displayed.

Application pages beneath _layouts have a separate web.config file that needs updated to enable more detailed error messages.

Open \Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\web.config

Add the following XML block immediately after the <configuration element.

<SafeMode CallStack="true">

· Find: <compilation debug="false" />
· Replace with: <compilation debug="true" />

Note: Always remember to disable debug mode before deploying a production application or conducting any performance measurements. If debug mode is enabled, the performance of your application can suffer a great deal.

MOSS out-of-box Usage Report

The Site Usage Reports that MOSS provide can be useful for site admin in determining the Usages of the Site. If you haven't got any other tools for tracking site usage, these Reports can be useful. But the only problem is that the information they present is not really explained anywhere.

Few days back one of my Client was asking me to explain the Report, but I had some tough time to do that. I searched a lot for any proper documentation from Microsoft, but didn't helped me out. After couple of day's searching, I finally able to explain my Client about the figues that is getting displayed in the Reports. Thanks to Mark Arend's Blog @ MSDN. He has really explained the logic in a well documented attachment with his post.

SharePoint Membership Webpart

This out-of-box webpart displays your site memberships. In other words, it will list all the sites where you have memberships.

The basic criteria to get the membership feature to function correctly are
as follows:

- You need to have an SSP created and all your sites need to be associated
with it.

- Having access to a site and being a member of the site are two different
things. The users need to be part of the site's Members group.

How to confirm: If you navigate to the site you want to show up in your membership web part, then go to Site Actions / Site Settings / People and Groups. Click on Actions and Setup Groups. Once in this screen, insure that you are in the group that is listed in the section called Members.

How to setup: If you do not have a member group, you can create one by navigating to the site, Clicking on Site Actions / Site Settings / People and Groups / Actions / Setup Groups.

Site Memberships are all sites in which you are explicitly included in the "~Members" group for the site (where ~ is your site name). Other users who are also explicitly included in the ~Members group on those sites are suggested as your colleagues. This information is collected by a WSS profile synchronization timer job.

- You need to have a Office Search full crawl scheduled and at least 1
successful full crawl completed. The population of user memberships is also closely tied to the full SharePoint crawl schedule. After each addition/deletion of memberships, we must execute a full crawl.

- the membership functionality does not work with AD Groups (I know... it's silly). Each user has to be explicitly added to the Members group within the site.

Once you have all these components in place, the membership web part should
function correctly.

Note: There are couple of additional configurations which need to be performed. Although I have never faced any issues without these configurations, still I am mentioning them in case it helps somebody.

- In order for the Membership functionality to work correctly, you need to make sure the users are clicking on the "Set as default My Site" link in the top right corner of the My Site screen. Until they do this, the membership functions will not work.

- You are using Office 2007, then only you will be able to use this webpart to it's fullest.

Monday, June 1, 2009

Open SharePoint Link List Item in new window

One of the frequently asked questions from SharePoint developers, "How to open Links from Links List in a new window?".

There are lots of way that we can find doing some simple googling:

1. Directly update the List Schema file. But this is only applicable if this need to be done for all the applications. Otherwise this is not a best practice. reference 1 reference 2
2. Create a new style for the Content Query web part to use by modifying ItemStyle.xsl reference
3. Using the Summary Links web part instead. This web part will allow you to designate how each link opens up (in a new browser or the current one).
4. Using some tricks with javascript. But the reference that follows required additional effort for end users. reference
5. Using dataview webpart. reference

If any of the above metho doesn't suit your taste, and in case you are a JavaScript fan, there is an easy process to acheive this:

Step 1: Open the page where you have added the Links webpart.
Step 2: Add a "Content Editor Web Part" to the page.
Step 3: Move the "Content Editor Web Part" below the Links webpart.
Step 4: Edit the "Content Editor Webpart" from corresponding "Modify Shared Web Part".
Step 5: Do either of the following activities:
a. Copy and paste the JavaScript code below and paste it to Content Editor's "Source Editor....".

<script language="javascript" type="text/javascript">
var tbl = document.getElementsByTagName('table');
for(var i = 0; i < tbl.length; i++)
if(tbl[i].getAttribute("Summary") == "Links")
var anc = tbl[i].getElementsByTagName('a');
for(var j = 0; j < anc.length; j++)
anc[j].setAttribute('target', '_blank');

b. Create a separate .js file with the JavaScript code above and upload the file in a Library. Next add the path of the .js file to the Content Editor Web Part's "Content link" textbox.

That's all. Using this process, you can add the javascript to a particular page, or even to the master pages. But this javascript code should always appear after the Links webpart (as mentioned in Step 3 above).