add

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..

Thursday, May 21, 2009

Difference between .Dwp and .Webpart

In the development of webpart, we have encountered two types of files.

1. .Dwp and 2. .Webpart.

As you may know, they are both files used for describing where the code is for a web part.

The difference is .dwp was the file extension used in version 2 of SharePoint and .webpart is a new extension used in version 3.

Inside the files, the schemas are different and it is indicated as such by the version number on the xmlns attribute.

The main difference is that all properties passed to the web part are specified with a property element and a name attribute in version 3. Version 2 uses different element names for everything.

Wednesday, May 20, 2009

Various properties of PeopleEditor:

Various properties of PeopleEditor:

The PeopleEditor control has a number of properties that allow you to configure it. In the next section, we will discuss the properties that we think are most important.

The PlaceButtonsUnderEntityEditor property decides the location of the Names and Browse buttons of the people picker. If you set it to true, the buttons are placed at the bottom right corner of the account name text box, otherwise to the right of it.

The AllowEmpty property lets you define if the user is required to fill in a value in the people picker.

The SelectionSet property allows you to define the set of users and groups the people picker can choose from. This set can consist of users, Active Directory distribution lists, Active Directory security groups, and SharePoint groups.
The MultiSelect property lets you define if a user is allowed to specify multiple user accounts. The next code fragment shows how to add a people picker to a web part and how to configure it:

objEditor = new PeopleEditor();
objEditor.AutoPostBack = true;
objEditor.PlaceButtonsUnderEntityEditor = true;
objEditor.ID = "pplEditor";
objEditor.AllowEmpty = false;
objEditor.SelectionSet = "User,SecGroup,SPGroup";
objEditor.MultiSelect = false;
Controls.Add(objEditor);

You can retrieve the values selected in the people picker by looping through the ResolvedEntities collection of the PeopleEditor object.

How to get all the values of PeopleEditor in Sharepoint

If we need to acess oll the values in the PeopleEditor control, we can iterate through the entities present in PeopleEditor:

Suppose we have a PeopleEditor control PE1 so the code will be :


ArrayList entities = PE1.ResolvedEntities;
foreach (object entity in entities)
{
PickerEntity pickerEntity = (PickerEntity)entity;
string accountName = pickerEntity.Key;
string displayName = pickerEntity.DisplayText;
// pickerEntity.EntityDate[] has other values like first name, last name, etc you might be interested in.
}

How to check if PeopleEditor is blank ?

Sometimes, we need to check whether Sharepoint PeopleEditor is blank or not. We can do that very easily by accessing Length property of that control.

Suppose we have a PeopleEditor control with Id PE1 then check for the lenght like this:

Int32 intLength = PE1.CommaSeparatedAccounts.Length;

Then put your own business logic as :

if (intLength == 0)
{.... }

How to set current user in the PeopleEditor via Code

The following code sample will set the currently logged on user to a PeopleEditor:

using (SPWeb web = SPContext.Current.Web)
{
SPUser user = web.CurrentUser;
PickerEntity entity = new PickerEntity();
entity.Key = user.LoginName.ToString();
System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList();
entityArrayList.Add(entity);
PeopleEditorControl.UpdateEntities(entityArrayList);
}

How to check whether a List is a Document Library?

Many times, we face a situation where we iterate through list collection. Now if we need to check whether a list is a SPDocumentLibrary or not, we can check it in very simple manner:

Suppose we need to display list of document libraries present in a site in a dropdown control named 'lstTargetLibrary', we will iterate through list collection and check for List type:


SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;

lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}

How to Upload a File to a SharePoint Site from a Local Folder

This code sample will show how to upload a file from your local pc to Sharepoint site using object mode:

1. Create a project and import namespaces :

using System.IO;
using Microsoft.SharePoint;


2. The UploadFile funtion code:

public void UploadFile(string srcUrl, string destUrl)
{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}

SPWeb site = new SPSite(destUrl).OpenWeb();

FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}


The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A System.IO.FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

To upload a file from a local folder on the same server that is running Windows SharePoint Services, you can use a System.IO.FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call an UploadFile method, which in turn calls the previously described EnsureParentFolder method.

How to delete a List from Sharepoint ?

This small code snippets will demonstrate how to delete a SPList from a sharepoint site.

To delete a list, you must specify the GUID of the list as the parameter for the Delete method. Use the ID property of the SPList class to find the GUID.

SPWeb mySite = SPContext.Current.Web;
SPListCollection lists = mySite.Lists;

SPList list = lists[ListName];
System.Guid listGuid = list.ID;

lists.Delete(listGuid);

Tuesday, May 19, 2009

Difference between Update and SystemUpdate in Sharepoint

We all know that whenever we add a list item or do some modification, we update the list. Here we have two options:

1. List.Update() and 2. List.SystemUpdate()

The main difference betwwen two is that,

List.Update() creates automatically new version of list item as Update method is called.


List.SystemUpdate() avoids SharePoint 2007 to change modified date and modifier fields. Argument false tells that no new versions are expected.

SystemUpdate takes an boolean argument that set whether new version need to be created or not.

Example using SystemUpdate() :

SPList list = web.Lists["myList"];
SPListItem item = list.Items[0];
item["myField"] = "my value";

item.SystemUpdate(false);
list.Update();

Microsoft Office Sharepoint Authentication Explained

In order for people to use a MOSS web application, the web application must validate the person’s identity. This process is known as authentication. MOSS is not a directory service and the actual authentication process is handled by IIS, not MOSS.

However, MOSS is responsible for authorization to MOSS sites and content after a user successfully authenticates. Authentication happens like this: A user points their browser at a MOSS site and IIS performs the user validation using the authentication method that is configured for the environment.

If the user authentication is successful, then MOSS renders the web pages based on the access level of the user. If authentication fails, the user is denied access to the MOSS site. Authentication methods determine which type of identity directory can be used and how users are authenticated by IIS. MOSS supports three methods of authentication: Windows, ASP.NET Forms, and Web Single Sign-On.

Windows Authentication is the most common authentication type used in MOSS intranet deployments because it uses Active Directory to validate users. When Windows Authentication is configured, IIS uses the Windows authentication protocol that is configured in IIS. NTLM, Kerberos, certificates, basic, and digest protocols are supported. When Windows authentication is configured, the security policies which are applied to the user accounts are configured within Active Directory. For example, account expiration policies, password complexity policies, and password history policies are all defined in Active Directory and not in MOSS. When a user attempts to authenticate to a MOSS web application using Windows authentication, IIS validates the user against NTFS and Active Directory, and once the validation occurs the user is authenticated and the access levels of that user are then applied by MOSS.




Anonymous access is considered to be a Windows authentication method because it associates unknown users with an anonymous user account (IUSR_MACHINENAME). Anonymous access is commonly used in internet Web sites and in situations where web site users will not have their own user accounts. Since exposing content to unknown users is risky, this configuration is disabled by default. In order to configure anonymous access to a MOSS web application, anonymous access must be enabled in IIS, enabled in the MOSS web application, and the anonymous user account must be provisioned throughout the MOSS Web application. Even when anonymous access is configured, there are still several limitations compared to a Windows user. By default, anonymous users are only allowed to read, and they are unable to edit, update, or delete content. Additionally, anonymous users are not able to utilize personalization features such as Microsoft Office integration, check-in/check-out and email alerts. The ASP.NET Forms authentication method is commonly used in situations where a custom authentication provider is required. In other words, where a custom LDAP, SQL Server, or other type of identity repository will be storing user account information. This is common in extranet environments, such as partner collaboration sites, where it is not practical to create Active Directory user accounts for users or a different type of directory is required.

The Web Single Sign-On authentication method is used in environments that have federated identity systems or single sign-on systems configured. In this type of environment, an independent identity management system integrates user identities across heterogeneous directories and provides the user validation for IIS. Some examples of identity management systems with single sign-on capability include Microsoft Identity Information Server with Active Directory Federation Services, Oracle Identity Management with Single Sign-On and Web Access Control, Sun Microsystems Java System Identity Manager, and Netegrity SiteMinder.

Large enterprises often implement federated identity models to ease the administration of user provisioning and de-provisioning for systems that span across companies. Single Sign-On systems are used to consolidate user accounts across heterogeneous systems, allowing the end user to authenticate to systems with one set of credentials, rather than to use a different set of credentials for each unique system. In MOSS, it is possible to configure web applications to use a combination of authentication methods. This provides a great deal of flexibility because it makes it possible to serve a web application to different user bases which have different identity requirements. For example, an organization may have a Project Collaboration Web site that is used by employees and partners.

For security and compliance reasons, it is necessary to store employee user accounts in Active Directory and partner user accounts in a SQL Server database. In this case, MOSS can be configured to use Windows authentication and ASP.NET Forms authentication. This is achieved by defining various zones and associated authentication methods to the zones. In the example above, an intranet zone would be configured with Windows authentication and an extranet zone would be configured with ASP.NET Forms authentication.

MOSS Object Model : Sharepoint

Detailed MOSS Object Model

Monday, May 18, 2009

How to cretae a new SPlist instance using the WSS object model

The following code provides the code to create a list instance. Before creating the list, the code checks to make sure a list of the same title doesn’t already exist. You will notice that the code enumerates through the lists within the current site, checking each list to see if there is a matching title. If a list with a matching title does not exist, the code in this application then creates a new instance of the Announcements list type and adds a link to the Quick Launch menu for easy access.

using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}

if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}


The code shows how to create a SPLit of announcements. We can create any List type:


Document library
Used for collaborating on documents with support for versioning, check-in and check-out, and workflow. Includes support for deep integration with Microsoft Office.

Form library
Used to store XML documents and forms for use with Microsoft Office InfoPath.

Wiki page library
Used for collaborative Web pages based on wiki pages, which are dynamically generated and collaboratively edited Web pages.

Picture library
A specialized document library enhanced for use with pictures. Includes support for slide shows, thumbnails, and simple editing through Microsoft Office Picture Manager.

Announcements
Used for simple sharing of timely news with support for expiration.

Contacts
A list for tracking people and contact information, with support for integration into Microsoft Office Outlook and other WSS-compatible contacts applications.

Discussions
A simple list for threaded discussions with support for approval and managing discussion threads.

Links
A list for managing hyperlinks.

Calendar
A list for tracking upcoming events and deadlines. Includes support for integration and synchronization with Office Outlook.

Tasks
A list of activity-based items that can integrate with workflow.

Project tasks
An enhanced tasks list with support for Gannt chart rendering and integration with Microsoft Office Project.

Issue tracking
A list for tracking issues and resolution, with support for prioritization.

Custom list
An empty list definition for extending with custom columns, or created using Microsoft Office Excel spreadsheets.

what is Windows Workflow Foundation ?

The workflow functionality in Windows SharePoint Services 3.0 is built on the Windows Workflow Foundation (WF), a Microsoft Windows platform component that provides a programming infrastructure and tools for development and execution of workflow-based applications. WF simplifies the process of asynchronous programming to create stateful, long-running, and persistent workflow applications. The WF run-time engine manages workflow execution and allows workflows to remain active for long periods of time and to survive restarting the computer. Run-time services offer functionality such as transactions and persistence to manage errors gracefully and correctly.

The WF run-time engine provides the services that every workflow application needs, such as sequencing, state management, tracking capabilities, and transaction support. The WF run-time engine serves as a state machine responsible for loading and unloading workflows, as well as managing the current state of any workflows that are running. WF allows any application process or service container to run workflows by hosting WF — that is, loading WF within its process.

Windows SharePoint Services hosts the WF run-time engine. In place of the pluggable services that are included with WF, Windows SharePoint Services provides custom implementations of the following services for the engine: transaction, persistence, notifications, roles, tracking, and messaging. Developers can then create workflow solutions that run within Windows SharePoint Services.

Figure 1 shows the workflow architecture in Windows SharePoint Services. Windows SharePoint Services hosts the WF run-time engine within its process, and provides custom implementations of the necessary services. The functionality of the WF run-time engine, as well as the hosting functionality Windows SharePoint Services provides, is exposed through the Windows SharePoint Services object model.


Figure 1. Workflow architecture in Windows SharePoint Services 3.0

Saturday, May 16, 2009

Foundation book on sharepoint 2007

There are two major books for begineers :

1. Inside WSS 3.0 and 2. Inside MOSS 2007 from Mirosoft Press.

These two books will give a strong foundation to the new bie in sharepoint

Thursday, May 14, 2009

How to get distinct value from CAML query

Many times, we face a challenge to get unique rows froma CAML query. The main problem is that CAML does not have any feature to get the distinct rows in one go.

Way Around:

We all know that CAML query returns SPListItemCollection and we can convert the outcome to data table also.
We can convert the resultant datatable to dataview and again convert the dataview to datatable by using ToTable and arguments :
Distinct = true
and column name

So..
suppose we have SPWeb object as 'web' so

DataTable DT= web.GetSiteData(qry);
DataView v = new DataView(tbl);
return v.ToTable(true, "Type");


This code snippets returns the distinct rows by comparing column name "Type".