Showing posts with label MOSS 2007. Show all posts
Showing posts with label MOSS 2007. Show all posts

Friday, October 22, 2010

Site Definition in Microsoft SharePoint Server 2007

Following steps are included in creating a custom site definition:

  • Create a folder named “mySiteDef” at C:Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Template\Site Templates\ 
  • Create a subfolder “XML” and create the onet.xml in it. The following kinds of tasks can be performed in a custom Onet.xml to create a custom site definition: 
    • Specify an alternate cascading style sheet (CSS) file, JavaScript file, or ASPX header file for a site definition.
    • Modify navigation areas for the home page and list pages
    • Add a list definition as an option to the Create page
    • Add a document template for creating document libraries
    • Define one or more configurations for the site definition, specifying the lists, modules, files, and Web Parts that are included when a site definition configuration is instantiated
  • It contains the following tags to define various items in a site definition. A sample onet.xml can be found at 12\TEMPLATE\SiteTemplates\SPS\XML folder in sharepoint farm (Same can be done through by copy existing site definition).
  • Within the “C:/Program Files/Common Files/Microsoft Shared/web server extensions/12/Templates/1033/XML” directory create a new file called webtempSiteMinder.XML. At run time the compiler will merge the information contained in this file with the information contained in the original WEBTEMP.XML file to specify which site templates are available for creating new sites
  • Enter the following XML into the webtempSiteMinder file as follows to create the new site definition.
<?xml version="1.0" encoding="utf-8"?>
<!-- _lcid="1033" _version="12.0.4518" _dal="1" -->
<!-- _LocalBinding -->
<Templates xmlns:ows="Microsoft SharePoint">
<Template Name="MYSITEDEF" ID="325202">
<Configuration ID="1" Title="MYSITEDEF" Hidden="FALSE" ImageUrl="/_layouts/images/blogprev.png" Description="MYSITEDEF Subsite" DisplayCategory="Custom" > </Configuration>
</Template>
</Templates>

  • Each WEBTEMP.XML file contains a collection of Template elements and Configuration sub-elements, which identify to the compiler all the site definitions that can be instantiated. The Configuration elements define a title, a description, and a URL for the image displayed in the user interface, properties common to each Web Site created using the site definition.
  • It is important to make sure that each Template element defined in the WEBTEMP file contains the identical Name in all capital letters that is assigned to the new folder created above. Also, as a best practice when creating new templates to avoid conflicts with existing sites use a unique value that is greater than 10,000 for the ID attribute.
  • Once created the various site elements can be edited using Microsoft office sharepoint designer.

Tuesday, September 28, 2010

Scoping Master Pages in SharePoint

Master pages provide the look and feel and standard behavior that you want for all of the pages in your site. Together with content pages, they produce output that combines the layout of the master page with content from the content page. 
Because Windows SharePoint Services is built on top of Microsoft ASP.NET 2.0, it supports master pages for defining elements that are common to all pages. You can specify all of the shared elements of your site in the master page or pages, and add content page-specific elements to content pages.

Master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.
Windows SharePoint Services pages that end users can customize—list view pages, list form pages, and Web Part Pages—are content pages that contain the content to display. When a user requests a content page, it is merged with a master page to produce output that combines the layout of the master page with the content from the content page.
All content pages share the same page structure—the global breadcrumb, site title area, top navigation, page title area, and left navigation bar. In Windows SharePoint Services, this shared page structure is moved into a master page called default.master, which is used by all content pages, including the following:
  1. default.aspx
  2. AllItems.aspx, DispForm.aspx, NewForm.aspx, and EditForm.aspx: for all lists 
  3. Upload.aspx and Webfldr.aspx: for all document libraries 
  4. Any new content pages that are created in this site
 
There are three levels to attach content pages to a master page:
  • At the page level: you can use a page directive in each content page to bind it to a master page, as in the following code example. 
  • At the application level: By making a setting in the pages element of the application's configuration file (Web.config), you can specify that all ASP.NET pages (.aspx files) in the application automatically bind to a master page. The element might look like the following. If you use this strategy, all ASP.NET pages in the application that have Content controls are merged with the specified master page. (If an ASP.NET page does not contain Content controls, the master page is not applied.)
  • At the folder level: This strategy is like binding at the application level, except that you make the setting in a Web.config file in one folder only. The master-page bindings then apply to the ASP.NET pages in that folder.

Monday, September 27, 2010

Important Considerations for SharePoint Master Pages

Consider the following when you are working with master pages in Windows SharePoint Services:

1. Compilation mode for master pages works like the compilation mode for any other .aspx page. You can change the compilation mode at any time, and you can combine compilation modes for master and content pages, for example, a compiled master page and a content page that is not compiled. Remember, however, that although compiled master pages can contain inline script, after that page is customized in Office SharePoint Designer, or a similar tool, the page is no longer compiled and script no longer runs. For that reason, it is recommended that you do not include inline script in your master pages.

2. By default, Windows SharePoint Services does not use nested master pages, but does not block users from using them. You can create master pages at any level, and have a master page that refers to another master page. For example, you can reference one master page from another master page using the following directive:

<%@ Master master=MyParent.master %>

Some page editors may not effectively support nested master pages.

3. You cannot add Web Parts in zones to a master page. You can add static Web Parts (parts outside of a zone) to a master page, but you cannot add dynamic Web Parts to master pages. You can add zones to master pages and later add Web Parts to the zone in the browser, but the Web Parts are associated with the content page.

Friday, July 30, 2010

Why Feature stapling in SharePoint

sometimes you may want to attach your feature with site definition i.e. whenever someone create a site using particular site definition you might want to activate the feature by default, and in same scenario it may be possible that you do not own the site definition hence cannot modify the existing site definition to attach feature (like SharePoint default site def e.g. team site\publishing\collaboration).

In these cases you can write a feature and can attach the feature itself with the site definition.

From MSDN :
"Causes the attachment of a Feature to all new instances of sites that use a given site definition, without modifying the site definition or creating code routines to activate the Feature on each site. Also known as a feature site template association"

Following is an example of feature stapling that associates the Feature with only the STS site definition template

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<FeatureSiteTemplateAssociation Id="00BFE171-1B17-4F72-28CB-1171C0140130" TemplateName="STS#0" />
</Elements>

http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/5e27a15b-5ceb-4706-b660-aadad03e0f3c

Thursday, May 6, 2010

WSS3.0\MOSS2007 and "Integrated managed pipeline mode" of IIS7

Problem Description:
SharePoint site is on WIN2k8\IIS7\WSS3.0-SP2 and you have created a sample web app (blank site) which is running well with IIS7 "Classic managed pipeline mode" but when you change it to "Integrated managed pipeline mode", It does not work and throws an error message "500 internal server Error".
Discussion ,Action taken and Results:
As discussed, MOSS 2007 use “Classic application pool mode” in IIS 7 for the SharePoint site since MOSS 2007 use IIS 6.0/ISAPI functionality through an ISAPI module and that is part of “Classic application pool mode” .
If we will use the “ Integrated Request Pipeline” for the SharePoint 2007 site you will not be able to browse to the site.
Following is the TechNet article which talk about that SharePoint use “Classic application pool mode” for the Application pool.
1: http://msdn.microsoft.com/en-us/library/bb909693.aspx (How to: Verify or Correct the IIS Configuration for an Application Pool)
Details are:
1. On the Application Pools page, review all application pools for Team Foundation.
• Under .NET Framework Version, verify that v2.0 appears.
• Under Managed Pipeline Mode, verify that Classic appears.
2: http://technet.microsoft.com/en-us/library/cc262485.aspx (Determine hardware and software requirements (Office SharePoint Server))
Details are:
Windows components
After you have installed the operating system and applied all critical updates, you must configure the computer to be a Web server by enabling Internet Information Services (IIS) 6.0, including:
• Common files
• WWW
• Simple Mail Transfer Protocol (SMTP)
You must configure the server to use IIS 6.0 worker process isolation mode. This is the default setting in new installations. However, if you have upgraded from IIS 5.0 on Windows Server 2000, Run WWW in IIS 5.0 isolation mode is enabled, and you must change this setting to use IIS 6.0 worker process isolation mode.
To enable e-mail notifications, you need to configure incoming and outgoing e-mail settings. To configure sending e-mail alerts and notifications, you must specify an SMTP e-mail server. To configure your installation so that your SharePoint sites can accept and archive incoming e-mail, you must install the IIS SMTP service

Additional info:
Integrated Request Pipeline:
Think of the integrated request pipeline as the essential set of linear steps that must occur every time a page is served up (as seen in Figure 2). Typically, some sort of authentication must take place, followed by authorization to retrieve content, determination and execution of the handler needed for that content, performance of any necessary logging, and finally sending a response. The integrated request pipeline provides IIS 7.0 the flexibility to run different application frameworks at the same time. For example, you can run Forms authentication on top of PHP content with a custom logging module, all together in the same pipeline.

Each Web site on the server has an integrated request pipeline and can be run in one of two modes, Integrated and Classic. Integrated, the default, allows particular pieces of functionality to be plugged into the pipeline, giving you granular control over the request process. For compatibility, Classic mode reproduces IIS 6.0/ISAPI functionality through an ISAPI module into the pipeline. This is very helpful when migrating your applications to IIS 7.0.
More info : http://technet.microsoft.com/en-us/magazine/2008.03.iis7.aspx
Classic application pool mode:
When an application pool is in Classic mode, IIS 7 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.
This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.

Tuesday, April 6, 2010

A HTML Table based Chart control in ASP.NET\MOSS 2007

Content:
  • Introduction
  • Various options to display charts on web
  • Code Walkthrough
  • Advantages
  • Limitation
Introduction:
A chart is a visual representation of data represented in various code\colors. It represents the summary of large chunk of unorganized data in an easy to understand manner which becomes very helpful in analysis, decision making and trend setting. The extensive usage of data over the web makes it very important control nowadays. Most of the modern web2.0 websites uses charts as one of the techniques to convey data to site visitors.
The article below gives a summary to create a 3d column charts in asp.net which can be modified and used in various other web supported platforms

Various options to display charts on web
Following are options to use chart on web in .net plateform
Microsoft chart controls:
Microsoft recently launched the rich functionality chart controls for asp.net to work with .net framework 3.5. It can be downloaded from the link below and used as any other controls in asp.net
http://www.microsoft.com/downloads/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C
These chart controls will be part of visual studio 2010 release.
GDI+ charts:
GDI+ charts are traditionally used chart controls over the web. It uses various drawing API of com\.net to draw a picture at server end first and then transfer the picture on the web. These controls are very complex and resources consuming.
Creating 3d and nice look and feel also bit cumbersome
HTML Table based Charts:
The technique used below is to generate line charts with the help of html tables and 3d images. It draws the table calibrate a 3d image to fit in the row as per the given x\y axis value. Hence become very lightweight and supported on any .net framework\ other platforms. Below is the sample screen shot.
Code Walkthrough: There are mainly two code files in this project. A chart user control and a web page to host\call chart
Chart controls expose various properties to set the different parameters of chart like width, column height, y axis values, x axis values etc. DrawGraph() is called to draw chart based on the x axis and y axis values set in the properties. It normalize the values provides for x axis and resize it as per the chart width. Below are the algorithm steps.
  • Define the color image array to denote the x axis values
  • Find out the max value in the x axis collection
  • Get the mod by dividing chart width with max value
  • Draw a table and draw a row for each value
  • For each value in the collection multiply the mod with value to expand and divide chart width with standard param to contract
  • Set this value as the length of image
  • Repeat the colors if color array is less than the value specified
  • Emit the constructed html on div\label tag
 Advantages:
  • It really simple, lightweight, 3d bar chart with nice look and feel
  • The code\logic can be modified to work on any other platform\language
  • A html table base web chart renders well on all type of browsers
  • It can be used in any .net framework\SharePoint
  • Can be customized easily based on the requirements
Limitation:
  • Can’t use similar technique to draw pie charts
code available on request

Monday, March 15, 2010

Best Coding Practices For Using Sharepoint Object Model

Content:
  • Introduction
  • Using objects in event receivers
  • Disabling Event Firing
  • Working with folders and lists
  • Using SPQuey Objects
  • Dispose WSS Objects
  • Subfolder creation in a list 
Introduction:
WSS provides a highly structured server-side object model that makes it easy to access objects that represents the various aspects of a SharePoint Web site. From higher-level objects, we can drill down through the object hierarchy to obtain the required object to be used in our code.
Diagram depicting the WSS site architecture in relation to the collections and objects of the Microsoft. SharePoint namespace is as follows:

While creating a new application or to improve the performance, extensibility and scalability of existing application it is important to understand how to make the SharePoint object model work efficiently, and how to apply general programming techniques to the SharePoint platform specifically. These common best coding practices can make it easier to design our applications correctly, find and fix problem areas in our code, and avoid known pitfalls of using the SharePoint object model.

Using Objects in Event Receivers:

SPWeb, SPSite, SPList, or SPListItem objects should not be instantiated within an event receiver. Within Event Receivers instead of using these objects event properties should be used otherwise following problems may occur:

• They incur significant additional roundtrips to the database. (One write operation can result in up to five additional roundtrips in each event receiver.)

• Calling the Update method on these instances can cause subsequent Update calls in other registered event receivers to fail.

Disabling Event firing:
Event handlers are fired synchronously or asynchronously for every addition, update, and deletion etc. if also that is not required from different code execution and it can cause performance degradation and unnecessary execution of event handlers code. So these event handlers must be disabled whenever not required. Code for this is:

public static void EnableEventFiring()
{
SetEventFiringSwitch(false);
}
public static void DisableEventFiring()
{
SetEventFiringSwitch(true);
}
private static void SetEventFiringSwitch(bool value)
{
PropertyInfo pi = EventManagerType.GetProperty(_eventFiringSwitchName, System.Reflection.BindingFlags.Static
System.Reflection.BindingFlags.NonPublic);
pi.SetValue(null, value, null);
}
private static bool GetEventFiringSwitchValue()
{
PropertyInfo pi = EventManagerType.GetProperty(_eventFiringSwitchName, System.Reflection.BindingFlags.Static
System.Reflection.BindingFlags.NonPublic);
object val = pi.GetValue(null, null);
return (bool)val;
}
private static Type GetEventManagerType()
{
_eventManagerType = typeof(SPList).Assembly.GetType(_className, true);
return _eventManagerType;
}
Working with folders and lists:
Working with large lists and folders needs conventional design change to optimize performance which is as follows:

  • Instead of using SPList.Items use SPList.GetItems(SPQuery query) and apply appropriate filter on query to make it more efficient. If list contains more than 2000 items then paginate the list in increments of no more than 2000 items.
  • Instead of using SPList.Items.GetItemById use SPList.GetItemById.
  • While adding a new item in a list instead of using SPList.Items.Add use SPList.GetItems(q).Add where q is empty query. Code for this is:- const
string EmptyQuery = "0";
SPQuery q = new SPQuery { Query = EmptyQuery };
SPListItem item = List.GetItems(q).Add();
  • Do not enumerate entire SPList.Items collections or SPFolder.Files collections.
  • While retrieving SPList object instead of getting it by using list’s name use its GUID or URL of the list.
Using SPQuery Objects:
When SPQuery returns large result sets than that can cause performance problem so points to keep in mind while designing query are as follows:
  • Use RowLimit between 1 and 2000 for SPQuery and paginate through the list if required.
  • If List Item URL is known than query list by using FileRef like SPWeb.GetListItem(string strUrl, string field1, params string[] fields).
  • Whenever possible use indexed columns in where clause of SPQuery.

Dispose WSS Objects:
WSS object model contains objects that implement the IDisposable interface. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. It is not known that when garbage collector will execute. Furthermore, the garbage collector has no knowledge of unmanaged resources. So Dispose method of this interface should be explicitly called to release unmanaged resources in conjunction with the garbage collector.

SPSite and SPWeb objects are managed objects but use unmanaged code and memory to do majority of their work. The managed part of the object is much smaller than the unmanaged part. Because the smaller managed part does not put memory pressure on the garbage collector, the garbage collector does not release the object from memory in a timely manner. The object's use of a large amount of unmanaged memory can cause some of the unusual behaviors like poor performance, application crash, high memory use of IIS worker process. Calling applications that work with IDisposable objects in Windows SharePoint Services must dispose of the objects when the applications finish using them. We should not rely on the garbage collector to release them from memory automatically.
We can employ certain coding techniques to ensure object disposal. These techniques include using the following in our code:
  • Dispose method
  • using clause
  • try, catch, and finally blocks
Subfolder Creation in a list:
If list size exceeds 2000 items then Microsoft recommends having subfolders for every 2000 items in a list. Then use SPQuery.ViewAttributes = "Scope=\"Recursive\"" for querying data through SPQuery and if possible than query only from subfolder by giving its name.

Monday, January 4, 2010

Introduction to Web Parts in ASP.NET/MOSS 2007

Content:

• Introduction
• System requirement
• Web part framework
• Comparing with asp.net
• Creating a new web part solution
• Deploying and debugging



Introduction:

Microsoft ASP.NET 2.0 provides a Web Part infrastructure that helps you build custom Web Parts and deploy them to Web sites built using Microsoft Windows SharePoint Services 3.0. This article provides a walkthrough how to build custom Web Parts that work in both standard ASP.NET 2.0 Web sites and Windows SharePoint Services 3.0.



Web part framework:

A Web Part is an ASP.NET server control designed to be edited and modified by users in the browser. It works as a component of a SharePoint site that presents information pulled from multiple data sources. Web Part pages allows to personalize information relevant to the needs by updating the value of specific Web Part properties. SharePoint Web Parts are UI elements that support both customization and personalization.

The Web Part infrastructure in Microsoft Windows SharePoint Services 2.0 and Microsoft Office SharePoint Portal Server 2003 provides a framework to build custom Web Parts targeted to Microsoft SharePoint Products and Technologies by using managed code.

ASP.NET 2.0 includes a new Web Part control set that allows site customization and personalization on custom Web sites that are independent of MOSS. The Web Part infrastructure in Windows SharePoint Services 3.0 exists on a layer above the ASP.NET 2.0 Web Part infrastructure.






Comparing with asp.net:


Office SharePoint Server 2007 and Windows SharePoint Services 3.0 are built on top of the ASP.NET 2.0 Framework. Windows SharePoint Services 3.0 uses the ASP.NET 2.0 Web Part infrastructure to take advantage of features such as master pages and custom Web Part development while providing a complete set of Windows SharePoint Services features, such as document services, events, workflow, search, site columns, content types and more.

We can build Web Parts for Windows SharePoint Services 3.0 in two ways:

• Create custom ASP.NET 2.0 Web Parts.
• Create SharePoint-based Web Parts.

The following table provides a decision matrix to help you choose the best option depending on your business needs.


Creating a new web part solution:
 
To create a new Web Part solution
o Open VS 2005 > File menu> click New, and then select Project.
o In Project types, select Visual C#, and then select SharePoint.


o In Templates, select Web Part.


o Specify a new name, location, or solution name of Web Part, and then click OK. The extensions create a new Web Part solution project, which includes the following:

 References to the Microsoft.sharepoint

 AssemblyInfo.cs, a file that enables you to specify company and product information for the Web Part assembly, and version information

 Temporary.snk, a temporary signature key file for the Web Part assembly

 A Visual C# code file for the Web Part, named the same as the Web Part name

 By default, the code file for the Web Part contains the following:

 using statements for the necessary System and Windows SharePoint Services namespaces, such as Microsoft. SharePoint, Microsoft.SharePoint.WebControls, and Microsoft.SharePoint.WebPartPages

 An empty Web Part class that inherits from System.Web.UI.WebControls.WebParts.WebPart

o Add the code you want to the Web Part class.



Customizing the Web Part Solution Package


The Web Part project template automatically generates the XML files needed to package your Web Part as a MOSS 2007 feature for deployment and activation. The required GUIDs contained in the XML files are also generated automatically.

The extensions generate a .webpart file as the element.xml file for the Feature containing the Web Part. Every Web Part should have a .webpart file, which is an XML file that describes the Web Part. The .webpart file also makes your Web Part appear in the Web Part gallery in MOSS 2007.

we can customize the information in these XML files by editing solution, Feature, and element properties on the SharePoint Solution tab in project's Properties dialog box, as follows:



o Solution Information in this node is written into the manifest.xml file for the Feature. You can set the following solution property:

o Name The name of your Web Part solution.

o Feature Information in this node is written into the feature.xml file for the Feature. You can set the following feature properties:

o Folder Name The name of the folder to contain the files for this Feature.

o Title The title of the Feature. Limited to 255 characters.

o Description A longer representation of what the Feature does.

o Version Specifies a System.Version-compliant representation of the version of a Feature. This can be up to four numbers delimited by decimals that represent a version.

o Scope The Feature scope. Can contain one of the following values: Farm (farm), WebApplication (Web application), Site (site collection), or Web (Web site).

o Hidden Hides the feature. This attribute is FALSE by default.

o Default Resource File Indicates a common resource file for retrieving Feature XML resources.

o Element Information in this node is written into the element.xml file for the Feature. As mentioned earlier, this file contains the information usually contained in a .webpart file. You can set the following element properties:

o Title The title of your Web Part on web page.

o Description The description of your Web Part that you want to appear in the Windows SharePoint Services user interface.

o ImportErrorMessage The error string to display if Windows SharePoint Services is unable to import your Web Part solution.


Customizing the Web Part solution feature package


o In Solution Explorer, right-click the Web Part project, and then select Properties.

o In the Properties window, select SharePoint Solution. This tab lists the nodes that contain the properties for the solution package that the extensions will generate.

o Expand the Solution node, and then expand the Feature node and the Element node.

o To edit properties for a node, click a node, and then edit the properties. For example, click the Element node, and then edit the values for the Title, Description, and ImportErrorMessage keys.

o To commit your changes for a node, click in the Description value field.




Deploying and debugging:

We can deploy and start debugging of the Web Part simply by pressing F5.

When you press F5, the extensions automatically build, deploy, and initiate debugging of Web Part solution Feature. To accomplish this, the extensions perform the following actions automatically:

o Build the Web Part assembly.

o Package the Web Part solution as a Windows SharePoint Services Feature.

o If this Web Part solution was deployed previously, the extensions retract the previous version of the Web Part solution Feature.

o Install your Web Part assembly to the global assembly cache using gacutil utility

o Deploy and activate your Web Part solution Feature in Windows SharePoint Services.

o Add your Web Part to the Safe Controls list.

o Restart Microsoft Internet Information Services (IIS) by invoking the iisreset command.

o Attach to the w3wp processes to enable debugging.


Wednesday, March 18, 2009

Writing RSS Feeds in .net

This article will cover following topics

• About RSS feeds
• Various ways to generate RSS Feed
o Using HTTP handlers and Cache mechanism.
o Building an HTTP Handler
• RSS Library
• RSS XML Format
• Advantages
• Limitation and support
 About RSS Feeds:
RSS stands for really simple syndication. It’s one of the medium to deliver information to users’ offline directly in their mailbox/ offline RSS reader application on subscription. It mostly consist the frequently updated data in a website such as blog entries, web feeds, news & alerts, audio & video links etc. RSS feeds are updated on defined frequency depends on the new contents available on the site. It might be hourly, weekly, monthly etc. The users subscribe to the feed on which they like to get timely updates or to aggregate feeds from many sources to one application


An RSS document includes full text or summary based on content plus it’s related metadata such as date of publishing, author, web links etc. it can aggregated using an RSS reader application sometimes called aggregator also. A user provides a link to RSS document and thereafter RSS reader application checks for timely update on each feed subscribed. The RSS icon ("
 ") is very much popular among many web2.0 based websites.

RSS formats are specified using XML, a generic specification for the creation of data formats

Various ways to generate RSS Feed:
RSS Feeds can be generated in following three ways.

• Using HTTP handlers and Cache mechanism.
• Using a scheduler (Window services).
• Using default RSS provided by the MOSS Lists.

1.1 HTTP handlers and Cache mechanism:
1.1.1 When user clicks on the RSS icon attached to the web page/data list, the client browser or RSS reader requests an RSS document from the site.
1.1.2 IIS checks the .rss file extension and invokes .NET library to process it. It will be configured in IIS. The details steps are discussed later in the document
1.1.3 Based on information in the Web.Config file, .NET knows to invoke RSS library class (HTTP handler) to process the request.
1.1.4 RSS library class checks for a cached copy of the RSS document. If it exists, RSS library sends the document back to the browser and terminates. If the response has not been cached (or if it expired), then RSS library continues.
1.1.5 RSS library merges information from the datatable/list/xml with item data from the appropriate list to build the RSS document.
1.1.6 RSS library caches the RSS document and sends it back to the browser.

1.2 Building an HTTP Handler

Whenever a page request comes to IIS it checks the extension of the page requested which is in the Web server configuration that which file to serve on that particular request, since IIS initially handles the request.

An HTTP handler can be configured so that the browser request can ask for a file that doesn't physically exist under the Web site. For example, you won't find a file under the Web root called "example.rss." Instead, IIS sends all requests for .rss files to the .net assembly which is directed from the web configuration file, and .net assembly writes the response from memory.

An http handler be configured in the following way


• Open ISS, Click start, run and enter inetmgr
• Click on configuration button on home directory tab, Application configuration dialog popup
• click on add button in mapping tab, Add/edit application extension mapping dialog open up
• Select the path of the DLL in executable text box and set the extension to .rss
• Close all the dialog boxes and now IIS is ready to serve any request that comes from .rss extension
To configure handler to a file extension through .NET, add a section to the Web.Config file in the root folder of Web application. Here's an example that shows how to associat RSS library with rss file requests .

The httpHandlers "add" tag tells .NET to send all rss file requests (verb="*" path="*.rss") to the RssHandler class in the RSS library assembly (type="Forum3.RSS library.RssHandler, RSS library").




Fig: Sample Web.Config

An HTTP handler is nothing more than a simple class library with at least one class that implements the IHttpHandler interface. The interface has just two members
• ProcessRequest method
• IsReusable property.
IsReusable tells .NET whether or not instances of your class can be safely pooled and reused. RssHandler returns true because it doesn't maintain any state that would interfere with its reusability.

The ProcessRequest method is where all the fun stuff happens. The .NET worker process passes you a reference to the request's HTTP context, which gives you access to the Request and Response objects as well as the other standard elements of the context.

2. RSS Library:

RSS library (RSS library) is .net class file which defines all the methods related to fetch/search and cache the resulted output to RSS format. it can be use any data source to find the result as databases/ xml/MOSS list etc. RSS profile contains all the settings related to the particular RSS that has to served like connection setting, Web link to RSS, title of feed etc.

FIG: Format of well defined RSS
3. RSS Format:

RSS format contain the data according to RSS 2.0 specification.
Here each item depicts a new feed in the document with its metadata. The properties of an RSS feed is classified under channel node. It can title of RSS feed, short description, web link, publish date etc.
Channel node contains many item nodes which translate into specific information available for the user in RSS feed. Each item node contains similar properties like title, description, web link, date of publish etc



References: www.msdn.microsoft.com

Monday, January 28, 2008

Creating Sites and List folders in a SharePoint using C# programmatically

Purpose of the Content:
Objective of this document is to throw some light on object model in MOSS using C#
This article will cover following topics
1. Introduction
2. Prerequisites
3. SPWebCollection.Add Method
4. Creating sites in SharePoint
5.SPListItemCollection.Add Method:
6.Creating folders in SharePoint List:


Introduction
The Windows SharePoint Services object model consists of forty-two namespaces in ten assemblies that are used in SharePoint sites on the server that is running Windows SharePoint Services1. The Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces provide types and members that can be used with lists and sites, as well as to manage a server or collection of servers that are running Windows SharePoint Services.

Now creating sites programmatically is one of the features that SharePoint SDK provides. The following sections will focus on how we can achieve this functionality.



Prerequisites :
Creating sites may be one of the task or the only that a web part does। So one must know how to develop and configure the web parts using SharePoint. Here I m using a web part consist a button on click of which, the new site creation logic will execute.

While sites are created through SharePoint we associate a site template name with the site. So it will be helpful to know how to develop and configure custom site templates if you want to use in new site. You can also refer the existing site template provided by SharePoint

SPWebCollection.Add Method:
The method Creates a Web site object with the specified site-relative URL, title, description, locale ID, and site definition or site template object.

SPWebCollection.Add Method (String, String, String, UInt32, SPWebTemplate, Boolean, Boolean) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
public SPWeb Add (
string strWebUrl,
string strTitle,
string strDescription,
uint nLCID,
SPWebTemplate WebTemplate,
bool useUniquePermissions,
bool bConvertIfThere
)

Parameters:


strWebUrl :A string that contains the new Web site URL relative to the root Web site in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite, specify MyNewWebsite, or to create a Web site one level lower at http://MyServer/sites/MySiteCollection/Website/MyNewWebsite, specify Website/MyNewWebsite.

strTitle: A string that contains the title.

strDescription: A string that contains the description.

nLCID: An unsigned 32-bit integer that specifies the locale ID.

WebTemplate: An
SPWebTemplate object that represents the site definition or site template.

6· useUniquePermissions: true to create a subsite that does not inherit permissions from another site; otherwise, false.

bConvertIfThere: true to convert an existing folder of the same name to a SharePoint site. false to throw an exception that indicates that a URL path with the specified site name already exists.


Return ValueAn SPWeb object that represents the Web site.

Creating sites in SharePoint:

1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Place the site template in the following SharePoint directory
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\

4· Now call the following function with given required parameters
private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)

Usage:

SPWeb spEventWeb = this.CreateNewSite(spcurrentweb, ”MyNewSite”,”siteDescription”,”MyCustomTemplate”,”MyNewSiteURL”))

Where spcurrentweb is spweb object of current site
o siteName and siteDesc is the name and description of the new site to create
o siteTemplateName is name of the template of the new site
o strWebUrl is the relative URL of the new site which can be different or same as the siteName
Full function body is below

private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)
{
try
{
if (spCurrentWeb != null)
{
if (spCurrentWeb.Webs[siteName].Exists == false)
{
//get the template collection from site based on locale Id
SPWebTemplateCollection Templates = spCurrentWeb.Site.GetWebTemplates(Convert.ToUInt32(1033));
if (Templates != null)
{
//get the template object from template collection based on locale Id
SPWebTemplate siteTemplate = Templates[siteTemplateName];
if (siteTemplate != null)
{
//create a new site and add it in web collection of the parent web
using (SPWeb spChildWeb = spCurrentWeb.Webs.Add(strWebUrl, siteName, siteDesc, (uint)1033, siteTemplate, false, false))
{
if (spChildWeb != null)
{
spChildWeb.AllowUnsafeUpdates = true;
spChildWeb.Update();
return spChildWeb;
}
else
{
throw new Exception("Site " + siteName + "can't be created");
}
}
}
}
}
else
{
throw new Exception("Site " + siteName + " already exist");
}
}
return null;
}
catch (Exception ex)
{
LogException(ex, "Site can't be created!!! some exception has occoured");
return null;
}
finally
{
if (spCurrentWeb != null)
spCurrentWeb.Dispose();
}
}

SPListItemCollection.Add Method:

The following method Create an item that uses the specified folder URL, object type, and leaf name but requires the Update method to actually add the item to the list.

SPListItemCollection.Add Method (String, SPFileSystemObjectType, String) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

public SPListItem Add
(
string folderUrl,
SPFileSystemObjectType underlyingObjectType,
string leafName
)
Parameters

o folderUrl : A string that contains the server-relative URL of the folder, beginning with a forward slash; for example, /sites/mysite/subweb/Lists/mylist/myfolder.

underlyingObjectType : A
Microsoft.SharePoint.SPFileSystemObjectType value that indicates the object type. Only File and Folder are valid types for the underlying object type.


leafName: A string that contains the leaf name, which is everything after the last forward slash in the URL, including the file extension.

Return Value: A
Microsoft.SharePoint.SPListItem object that represents the new item.
Creating folders in SharePoint List:
1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Now call the following function with given required parameters


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
Usage:

spFolder spNewFolder = this.GetFolder(spcurrentweb, “MySiteLink”, “MyListName”, “MyFolderName”);
Where spcurrentweb is spweb object of current site
o MyListName and MyFolderName is the list name and folder name in the given list.
o MySiteLink is the relative URL of the new site which can be different or same as the siteName
Full function body is below


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
{
using (spCurrentWeb)
{
if (!string.IsNullOrEmpty(strFolderName))
{
//create a folder with the given name in the event list if don't exist, otherwise return the existing folder
if (spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName).Exists != true)
{
spCurrentWeb.AllowUnsafeUpdates = true;
SPList spListEvent = spCurrentWeb.Lists[strListName];
//create a new folder in the list
SPListItem spFolderEvent = spListEvent.Items.Add(strSiteLink + "/Lists/" + strListName, SPFileSystemObjectType.Folder, strFolderName);
spFolderEvent.Update();
spListEvent.Update();
spCurrentWeb.Update();
}
//return the existing folder from the list
return spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName);
}
return null;
}
}




References:
http://msdn2.microsoft.com/en-us/library/ms439689.aspx
http://msdn2.microsoft.com/en-us/library/ms448720.aspx

Thursday, August 30, 2007

Executing MOSS CAML Queries in Batch

Introduction:


In SharePoint we use SPQuery object to get filtered data from a list. We assign a CAML query to Query property of SPQuery object. The problem with SPQuery object is that it does not support all SQL operation like Joins, IN, Between etc. So to get filtered data we need to apply many ‘OR’ or ‘AND’ operation. Another problem is that lengths of string in its Query property have a limit. So an exception can occurs where we are creating query at run time with ‘OR’ or ‘AND’ operation. To overcome from this situation we have two solutions. One, use Data View object and then filter out the rows. Second, retrieve the rows in batches (execute each batch separately) and combine the result. In Batch execution we make a batch which can contain between 100-120 ‘OR’ or ‘And’ operation. In a batch we get data as a data table and merge this table with main table.
Example:-
Simple ‘Or’ or ‘And’:
This example illustrates the implementation of a function that runs a query(with only ‘Or’ operations) in batches and retuns the combined result as a data table.

///Class level variables
private const string C_Query = "<{3}>{2}";
private int _intBatch = 120; // Size of a batch.

/// This method returns a data table after applying passed filter.
/// 
Field name which will be used to get data from passed data table
Field name on which Or filter will be applied
Value types of field on which Or filter will be applied
List name
Data table whose values will be used in query
SPWeb object
///
public DataTable GetFilteredData(string sourceFieldName, string
queryFieldName, string queryFieldValueType, string queryListName, DataTable itemCollectionForCondition,
SPWeb webQuery)
{
SPQuery spQueryBatch;
DataTable dtbResult;
int intCount = 0;
int j;
int l;

// Get total items of DataTable object.
intCount = itemCollectionForCondition.Rows.Count;

if (intCount > 0)
{
// Create a object of a table in which we will
//merge all table.
dtbResult = new DataTable(queryListName);

for (int i = 0; i < intCount; i += _intBatch) { StringBuilder sbdBatchFilter = new StringBuilder(); int intOrCount = 0; sbdBatchFilter.Append("");
//Add all ‘Or’ condition.
for(j = i; j<(i + _intBatch)-1 && j < intCount -1; j++) { intOrCount += 1; sbdBatchFilter.Append("");
sbdBatchFilter.Append(string.Format(C_Query,
queryFieldName, queryFieldValueType,
itemCollectionForCondition.Rows[j]
[sourceFieldName], "Eq"));
}
sbdBatchFilter.Append(string.Format(C_Query,
queryFieldName, queryFieldValueType,

itemCollectionForCondition.Rows[j]
[sourceFieldName], "Eq"));
//Close all added ‘Or’.
for (int k = 0; k < intOrCount; k++) { sbdBatchFilter.Append("
");
}

sbdBatchFilter.Append("
");

spQueryBatch = new SPQuery();
spQueryBatch.Query = sbdBatchFilter.ToString();
// SPQuery can only get the items in the current
// folder; SPQuery will not get the items in
// subfolders. So we need to set following
// property.
spQueryBatch.ViewAttributes =
"Scope=\"Recursive\"";

if(webQuery.Lists[queryListName].GetItems
(spQueryBatch).Count>0)
// Add new result to data table.
dtbResult.Merge(webQuery.Lists[queryListName].
GetItems(spQueryBatch).GetDataTable());
}
}
else
{
return null;
}

return dtbResult;
}

To perform ‘AND’ operation in above example we can replace ‘’ and ‘’ tag with ‘’ and ‘’ tag.

Or’ with ‘And’:This example illustrates the implementation of a function that runs a query(with ‘Or’ and ‘And’ operation) in batches and retuns the combined result as a data table.

///Class level variables
private const string C_Query = "<{3}>{2}";
private int _intBatch = 100; // Size of a batch.

///
/// This method returns a data table after applying passed filter.
///

///

Field name which will be used to get
data from passed data table
///
Field name on which Or filter will be
applied
///
Value types of field on which Or
filter will be applied
///
List name
///
Data table whose values
will be used in query
///
SPWeb object
///
Array of string which contains all
field names on which AND Operation will be applied
///
Corresponding values of passed
fields
///
Corresponding value types of passed
fields
///
public DataTable GetFilteredData( string sourceFieldName,
string queryFieldName,
string queryFieldValueType,
string queryListName,
DataTable itemCollectionForCondition,
SPWeb webQuery,
string[] andFieldNames,
string[] andValues,
string[] andFieldValueType)
{
string[] strAndFieldNames;
string[] strAndValues;
string[] strAndFieldValueType;

SPQuery spQueryBatch;
DataTable dtbResult;
int intCount = 0;
int j;
int l;

strAndFieldNames = andFieldNames;
strAndValues = andValues;
strAndFieldValueType = andFieldValueType;

// Get total items of DataTable object.
intCount = itemCollectionForCondition.Rows.Count;

if (intCount > 0)
{
// Create a object of a table in which we will
//merge all table.
dtbResult = new DataTable(queryListName);

for (int i = 0; i < intCount; i += _intBatch) { StringBuilder sbdBatchFilter = new StringBuilder(); int intOrCount = 0; sbdBatchFilter.Append("");
//Add all ‘Or’ condition.
for (j = i; j < (i + _intBatch) - 1 && j < intCount - 1; j++) { intOrCount += 1; sbdBatchFilter.Append("");
sbdBatchFilter.Append(string.Format(C_Query,
queryFieldName,
queryFieldValueType,
itemCollectionForCondition
.Rows[j][sourceFieldName],
"Eq"));
}
sbdBatchFilter.Append(string.Format(C_Query,
queryFieldName, queryFieldValueType,
itemCollectionForCondition.Rows[j]
[sourceFieldName], "Eq"));
//Close all added ‘Or’.
for (int k = 0; k < intOrCount; k++) { sbdBatchFilter.Append("
");
}
// Check array for And operation. If it is not null
// then add all And conditions.
if (strAndFieldNames != null)
{
if (strAndFieldNames.Length > 0)
{
int intAndCount = 0;
sbdBatchFilter.Replace("",
"");

for(l=0; l < strAndFieldNames.Length - 1; l++) { intAndCount += 1; sbdBatchFilter.Append("");
sbdBatchFilter.Append(
string.Format(C_Query,
strAndFieldNames[l],
strAndFieldValueType[l],
strAndValues[l], "Eq"));
}
sbdBatchFilter.Append(string.Format(C_Query,
strAndFieldNames[l],strAndFieldValueType[l],
strAndValues[l], "Eq"));
//Close all added And's.
for (int k = 0; k <= intAndCount; k++) { sbdBatchFilter.Append("
");
}
}
}
sbdBatchFilter.Append("
");
spQueryBatch = new SPQuery();
spQueryBatch.Query = sbdBatchFilter.ToString();
spQueryBatch.ViewAttributes = Scope=\"Recursive\"";

if(webQuery.Lists[queryListName].GetItems
(spQueryBatch).Count>0)
// Add new result to data table.

dtbResult.Merge(webQuery.Lists[queryListName]
.GetItems(spQueryBatch).GetDataTable());
}
}
else
{
return null;
}

return dtbResult;
}

References: http://msdn2.microsoft.com/en-us/library/ms978519.aspx