It is a place for all SharePoint lover and it is completely dedicated to SharePoint and ASP.Net
Sunday, December 27, 2009
Creating a Basic Event Handler
Link: http://msdn.microsoft.com/en-us/library/ms437502.aspx
Working with List Objects and Collections in SharePoint
Objects
Most classes in the Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces start with SP. Generally, classes in the Microsoft.SharePoint assembly that don't start with this prefix represent Web form controls.
Windows SharePoint Services typically does not save modifications of object properties to the database until you call the Update method on the given object. The following example shows how to change the title and description for the Tasks list.
Sample Code:
SPList myList = myWeb.Lists["Tasks"];
myList.Title="New_Title";
myList.Description="List_Description";
myList.Update();
Collections
Just as lists are at the center of a SharePoint site, so are collections at the center of its object models. You can use each collection to add, delete, enumerate, and update a type of object. Collection classes generally share the following traits:
Has a name that ends in "Collection."
Implements the System.Collections.ICollection interface.
Has a Count property of type Int32.
Has an Int32 indexer that can be used to get the nth item in the collection.
Has an indexer that takes an item identifier.
Has Add and Delete methods.
Calling the Add method for a collection usually updates the database on the back-end server with the appropriate data, except when additional information is required in order to update data. In this case, using the Add method returns an object that you can use to gather the information. For example, to add an item to a list, first use the Add method of the Microsoft.SharePoint.SPListItemCollection class to return an SPListItem object, assign values to appropriate properties of the object, and then call the Update method to effect changes within the content database.
Indexers
Indexers provide a useful means to access individual items in collections. To return an item, use square brackets ([]) in C# to contain either an index or a string that identifies the item within the collection.
For example, if mySite represents an instance of the SPWeb class, then SPList myList = mySite.Lists["Announcements"] returns the Announcements list in C#.
To return only a subset of items from the list, you can call the list object's GetItems method and pass an SPQuery object to specify the subset:
SPListItemCollection myItems = myList.GetItems(myQuery)
You can use an indexer to return a specific field from a list (for example, myList.Items["Field_Name"] in C#. You can also specify a field name in an indexer and iterate through the collection of items in a list in order to return values from the field. This example displays the Due Date, Status, and Title values for each item in a list:
Sample Code
foreach(SPListItem myItem in myItems)
{
Response.Write(SPEncode.HtmlEncode(myItem["Due Date"].ToString()) + "
");
Response.Write(SPEncode.HtmlEncode(myItem["Status"].ToString()) + "
");
Response.Write(SPEncode.HtmlEncode(myItem["Title"].ToString()) + "
");
}
The next example shows how to return all Title and Status values for the Tasks list on a SharePoint Web site.
SPWeb mySite = SPContext.Current.Web;
SPList myTasks = mySite.Lists["Tasks"];SPListItemCollection myItems=myTasks.Items;
foreach(SPListItem myItem in myItems)
{
Response.Write(SPEncode.HtmlEncode(myItem["Title"].ToString()) + " :: " + SPEncode.HtmlEncode(myItem["Status"].ToString()) + "
");
}
You can also use indexers to modify values in a list. In the following example, a new list item is added to a collection and the values for a URL column are assigned to the item:
SPListItem myNewItem = myList.Items.Add();
myNewItem["URL_Field_Name"] ="URL, Field_Description";
myNewItem.Update();
The following example sets the Status and Title values for a list item.
SPListItem myItem = myItems[0];
myItem["Status"]="Task_Status";
myItem["Title"]="Task_Title";
myItem.Update();
An indexer throws an ArgumentOutOfRange exception if it does not find the specified item.
[Courtsey MSDN]
Thursday, December 24, 2009
ASP.Net Request Architecture
http://www.codeproject.com/KB/aspnet/ExploringIIS.aspx
A few useful link on the same topic are -
http://www.codeproject.com/KB/aspnet/aspnetrequestarchitecture.aspx
http://dotnetslackers.com/articles/iis/ASPNETInternalsIISAndTheProcessModel.aspx
And the father of all link is -
http://msdn.microsoft.com/en-us/library/ms525977.aspx
Friday, December 4, 2009
For Beginners: Add a custom ASP.NET page in your SharePoint Application
2. You have created your .Aspx page in Visual Studio --> MyPage.aspx. (Remember to provide Complete details in 'Inherit' field of the 'Page' attribute present in the start of the .aspx page including Fully qualified page name, namespace, version, culture and public key token)
3. You have compiled the application and placed the error free dll in the GAC.
3. Go to 12 Hives --> C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES
4. Create a new folder named MyPageFeature and copy & add an existing feature structure there. Then add a new entry for your page i.e., MyPage.aspx in the Elements.xml file and delete all the other old links.
5. now open command prompt and navigate to --> C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
6. write the following command --> stsadm -o installfeature -name MyPageFeature -force
7. After the installation of your feature, you need to activate it by the following command --> stsadm -o activatefeature -name MyPageFeature -url http://ServerName:PortNumber
8. After operations completed succesfully, close the command prompt.
9. Reset IIS or the respective Application Pool.
10. Write the complete url (Eg: http://ServerName:PortNumber/MyPageFeature/MyPage.aspx) and hit enter to find your new page running in SharePoint environment.
Wednesday, September 30, 2009
Understanding the Event Model
http://msdn.microsoft.com/en-us/library/ms533023(VS.85).aspx
Friday, August 28, 2009
ASP.NET Page Life Cycle - Interview Huh !!!
General Page Life-cycle Stages (Courtsy MSDN, CP, UsualDosage, Several Blogs...)
In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page.
Putting together an acronym for the page life cycle is easy enough. Since the Page Request technically isn't a part of the life cycle (it only indicates whether we actually will start the cycle or load a cached page) we won't include it in the acronym.
S � Start
I � Initialize
L � Load
V � Validate
E � Event Handling
R � Render
That gives us "SILVER", which is very easy to remember. However, it is important remember that the last part of the cycle is unload. You can remember it as "SILVER-U" or "SILVER-YOU" if that helps !!! Now that it's easy to remember the order of steps for the page lifecycle, we'll summarize exactly what happens and what events are pertinent to each stage.
1. Start
This is where page properties such as Request, Response, IsPostBack and UICulture are set. As a developer, you most likely won't really need to do anything in this stage of the cycle. If you need to access or override behavior for this step, use the PreInit method to create or re-create dynamic controls, set a master page or theme or read or set profile property values. It is important to note that if the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
2. Initialize
This stage can be very important to developers. Here, themes are applied, and unique ids are generated and set for controls. Developers have access to the Init, InitComplete and PreLoad methods in this stage. Microsoft's recommended usage for these methods is as follows:
Init � This event is raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete � This event is raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad - Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
3. Load
This stage is perhaps the most utilized by developers. In this stage controls are loaded with information retrieved from view and control states. The OnLoad is the event method that fires during this stage. This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.
4. Validation
If you have controls that require validation, they are validated here and you can now check the IsValid property of the control. The event associated with this is Validate, which contains one overloaded method that accepts a validation group string. The overloaded method instructs the controls in the specified group to validate.
5. Event Handling
The event handling for server controls occurs during this stage. This means that events such as Click, SelectedIndexChanged, etc are applied to your server controls, and, in the case of a postback, these event handlers are fired by the control. The accessible events of note in this stage are as follows:
LoadComplete � At this step, all of the controls for the page have been loaded.
PreRender � A few things of import happen here. First, the page object will call EnsureChildControls for each control, and finally for the page. Additionally, any data bound control that has a DataSourceID set will call its DataBind method. It is important to note that the PreRender event occurs for each control on the page. At the conclusion of this event, ViewState will be saved for the page and all of the controls.
SaveStateComplete � ViewState has been saved. If you have actions that do not require changes to controls but require ViewState to have been saved, you can handle the SaveStateComplete event.
6. Render
Render is not really an event. Rather, the page object calls this method on each control, which in turn writes out the HTML markup for the control to the browser. This stage is keenly important to developers who create custom controls, because the standard approach is to override the Render method for the control in order to output the custom markup. If your control inherits from a standard ASP.NET server control, you probably won't need to override the Render method unless you want to exhibit a different behavior than the control's default. This is outside the scope of this document, but for more reading, you can reference Microsoft's Developing Custom ASP.NET Server Controls. (http://msdn2.microsoft.com/en-us/library/zt27tfhy.aspx)
7. Unload
This final event occurs first for each control, then, finally, for the page. At this point, all controls have been rendered to the output stream and cannot be changed. During this event any attempt to access the response stream will result in an exception being thrown. This event is primarily for cleanup routines such as closing open database connections and open file streams, or, event logging and other tasks.
Methods
The following methods (which can all be overridden) occur in order during the lifecycle of an ASP.NET page. Please realize that some of these methods are called recursively, and multiple times depending on the content of the page. This list is the generalized order in which methods fire when a page loads. You can test this by creating a default ASP.NET application, overloading each of the below methods, and setting a breakpoint on each.
1. Construct
2. ProcessRequest
3. FrameworkInitialize
4. InitializeCulture
5. If child controls are present:
a. AddParsedSubObject
b. CreateControlCollection
c. AddedControl
d. ResolveAdapter
6. DeterminePostBackMode
7. OnPreInit
8. OnInit
9. TrackViewState
10. OnInitComplete
11. OnPreLoad
12. OnLoad
13. OnLoadComplete
14. EnsureChildControls
a. CreateChildControls
15. OnPreRender
16. OnPreRenderComplete
17. SaveViewState
18. OnSaveStateComplete
19. CreateHtmlTextWriter
20. RenderControl
a. Render
b. RenderChildren
21. VerifyRenderingInServerForm
22. OnUnload
23. Dispose
So, after theory comes the Practical Lab... Here, comes a code stub, which one can very easily use to learn clearly about page life cycle.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("protected void Page_Load" + "
");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("protected void Page_PreRender" + "
");
}
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("protected void Page_PreInit" + "
");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("protected void Page_Init" + "
");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("protected void Page_InitComplete" + "
");
}
protected void Page_PreLoad(object sender, EventArgs e)
{
Response.Write("protected void Page_PreLoad" + "
");
}
protected void Page_ControlEvents(object sender, EventArgs e)
{
Response.Write("protected void Page_ControlEvents" + "
");
}
protected void Page_SaveStateComplete(object sender, EventArgs e)
{
Response.Write("protected void Page_SaveStateComplete" + "
");
}
protected void Page_Render(object sender, EventArgs e)
{
Response.Write("protected void Page_Render" + "
");
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Response is not available in this context.
}
/////////////////////////////////////////////////////////////
protected override void AddedControl(Control control, int index)
{
Response.Write("AddedControl Fired on " + control.ID + "
");
base.AddedControl(control, index);
}
protected override void AddParsedSubObject(object obj)
{
base.AddParsedSubObject(obj);
Response.Write("AddParsedSubObject" + obj.ToString() + "
");
}
public override void ApplyStyleSheetSkin(Page page)
{
base.ApplyStyleSheetSkin(page);
Response.Write("ApplyStyleSheetSkin " + page.ToString() + "
");
}
protected override void Construct()
{
base.Construct();
// No Response Object here yet!
}
protected override void CreateChildControls()
{
base.CreateChildControls();
Response.Write("CreateChildControls
");
}
protected override ControlCollection CreateControlCollection()
{
Response.Write("CreateControlCollection
");
return base.CreateControlCollection();
}
// etc. etc. just type the keyword "override" and select from the list! protected void Page_Load(object sender, EventArgs e)
}
Ref: http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://69.10.233.10/KB/aspnet/ASPNET_Page_Lifecycle.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.page_events.aspx
In depth Pic Analysis: (Courtsy: Léon Andrianarivony)
Windows SharePoint Services - Architectural Perspective
Functional Architecture
WSS is designed to support a broad range of deployments. At a high level, four different types of systems are involved:
1. The End-User Client (EUC) is a computer on which an individual user is requesting specific file operations. These requests are communicated using HTTP-based protocols, including HTTP, DAV and Microsoft FrontPage Server Extensions.
2. The Web Front-End (WFE) is a computer that receives requests from an EUC and provides WSS capabilities by manipulating information stored in a database. These database requests are expressed in the T-SQL language and communicated using the TDS protocol.
3. The Back-End Database (BEDS) is a computer that runs Microsoft® SQL™ Server and responds to requests from the WFE server.
4. An Active Directory server responds to authentication requests from the EUC, WFE, and BEDS. These components could use an alternate authentication mechanism besides Active Directory.
These systems are shown in the following diagram.
Figure 1: Intersystem protocol relationships
WFE and BEDS are considered part of the WSS deployment; the EUC is normally a user's desktop or laptop computer that connects to WSS services, and Active Directory is part of the generally available infrastructure. Both WFE and BEDS can run on a single computer, so the simplest WSS deployment could be just a single server. Alternatively, multiple instances of WFE and BED computers can be installed for greater throughput and redundancy.
Storage Architecture
WSS provides a flexible model for storage which allows for a robust variety of data management and organization techniques. The following diagram presents a high-level view of the containers in this hierarchy. These containers provide important organizational and management tools for content stored in WSS, and also form the core securable objects.
Figure 2: SharePoint storage object hierarchy
Advanced Storage Concepts
In addition to basic file system concepts, WSS provides a variety of specialized file system objects and operations as described below -
Thickets
For some complex HTML documents, WSS provides the capability to store the document separated into its component sibling documents. This group of documents is treated like a single document for most file operations, but is stored as a set of related documents within the file store location.
Ghosting
Sites and Lists tend to share a relatively small set of common system files across many instances within the BEDS. To avoid having to store these files repeatedly for every Site or List in the BEDS, WSS allows files to be ghosted, meaning that the content of the file is not actually stored in the BEDS. Instead, a reference to a location on the WFE where the source of the file can be found is stored in the file metadata.
Versioning
WSS can be configured on a per-List or per-Document Library basis to store multiple versions of Documents. If versioning is configured for a storage location, each new version of a Document is stored with an incrementing version number that can be either in the form 'Major Version Number' (#) or 'Major Version Number.Minor Version Number' (#.#).
If Major Version Number.Minor Version Number version numbering is used, individual Documents start their numbering at 0.1, and the version can be promoted to a Major Version using the Publishing feature. Prior versions of a document can be retrieved by users with the appropriate access rights.
Publishing
WSS can be configured on a per-List or per-Document Library basis to allow publishing features with Documents. If publishing features are configured for a storage location, each version of a Document can be configured as a draft, and therefore, not be available to be viewed by users without the appropriate access rights for viewing unpublished versions.
Large File Access
When dealing with very large files, obtaining the complete file contents in a single buffer as part of one operation can be a burden on system resources. Instead, the BEDS provides functionality to return files larger than a specified size to the WFE in a series of smaller chunks that can be processed more smoothly.
BLOB Storage Outside the Content Database
WSS provides the ability to allow file metadata to be stored by WSS in a Content Database, while allowing the actual file contents to be stored in an external file system. The term Binary Large Object (BLOB) refers to the SQL Server concept of unstructured, binary data streams that are commonly associated with files.
WSS does not natively provide a BLOB store. There are two APIs that allow a BLOB storage provider to be built and registered with WSS:
External BLOB Storage: For more information about External BLOB Storage, see [MSDN-WSSEBS].
Remote BLOB Storage: For more information about Remote BLOB Storage, see [MSDN-SQLRBS]. Windows SharePoint Services 4.0 supports Remote BLOB Storage providers.
Content Databases
A Content Database stores and manages end-user content. Each Web Application will have one or more Content Databases. The WSS Content Database stores the data and documents that end-users have associated with their SharePoint Site. The contents of this database are fully normalized in order to efficiently perform the kinds of operations required for the high-scale, highly-configurable system previously described. The role of a WSS WFE is to fetch the appropriate data from these multiple locations within SQL using the appropriate set of queries and stored procedures and to correctly interpret and map the results into a correct response to the EUC.
Configuration Database
The Configuration Database describes the topology of the farm and global settings. Each farm will have only one Configuration Database. The Configuration Database is essentially the definition of the WSS deployment, for either a single instance of WSS or for a farm. In the farm context, the Configuration Database contains information representing the global settings that are required to provide consistent operation across all servers within the farm, and to map requests to particular Content Databases.
Thursday, August 27, 2009
WSP and WSPBuilder --- Penicillin in the life of a SharePoint Developer!!!
The solution framework provides the following advantages:
1. A unified infrastructure for deploying solutions.
A solution package is a cabinet (.cab) file with a .wsp file name extension and a manifest file. It can contain the following components:
1. Site definitions
2. Feature definitions and their corresponding element definitions and files
3. Web Part files (*.webpart, *.dwp)
4. Template files and root files, which can include the following:
a. _layouts files
b. Resources (*.resx)
c. Resource files (for example, *.doc or *.xls)
5. Assemblies, which can include the following:
a. Safe control entries
b. Resources
6. Code access security policies
Solution files have a hierarchical structure—a manifest file is at the root—while feature, resource, or site definition directories are contained in subdirectories. In turn, feature definitions define where associated files are located inside of the solution.
The solution creator can define the remaining structure; however, it is recommended that files for a particular feature or site definition be placed in that feature or site definition's subdirectory.
Following is the structure of a manifest.xml file -
What is a solution feature.xml file ?
Features reduce the complexity involved in making simple site customizations, and are robust when upgrades are applied to a deployment. Features eliminate the need to copy large chunks of code to change simple functionality. Features thus reduce versioning and inconsistency issues that may arise among front-end Web servers. Features make it easier to activate or deactivate functionality in the course of a deployment, and administrators can easily transform the template or definition of a site by simply toggling a particular Feature on or off in the user interface.
Features provide the following capabilities:
1. Scoping semantics for determining where custom code runs
2. Pluggable behavior for installing or uninstalling Features within a deployment
3. Pluggable behavior for activating or deactivating Features at a given scope
4. A scoped property bag for storing data required by a Feature within its scope
5. The basis of a unified framework for distributed deployment of Windows SharePoint Services solutions
Feature Implementation
To implement a Feature you add a subfolder containing a Feature definition within the Features setup directory (Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES). The Feature subfolder includes a Feature.xml file that defines the base properties of the Feature and lists elements bound to it, such as XML files containing element manifests and any other supporting files. A Feature folder may contain only a Feature.xml file, or it may contain a Feature.xml file and any number of supporting element files, including XML files, but also .aspx, .htm, .xsn, .resx, .dll, and other file types.
Following is the structure of a feature.xml file -
Note:
When you create a folder within the Features directory through Windows Explorer by right-clicking a folder, pointing to New, and then clicking Folder, the new folder does not have inherited permissions. If you deploy a Feature in the folder, then some Windows SharePoint Services pages, such as for site settings or list views, throw an exception. You can fix this problem by right-clicking the new folder, click Properties, click Security, and then click Advanced. On the Permissions tab, delete uninherited permissions from the folder. You can also fix this problem by creating the new folder at the command prompt through the md command.
After creating the Feature folder, you can install and activate the Feature through command-line operations of stsadm.exe, or through the object model. You can also activate a Feature through the user interface. Installing a Feature makes its definition and elements known throughout a server farm, and activating the Feature makes the feature available at a particular scope.
What is a solution elements.xml file ?
Elements.xml is referred via Feature.xml. Here, Module URLs are targets within MOSS; File URLs are relative to the Module URL. Following is the structure of a feature.xml file -
So, after the basics of WSP, we need to learn WSPBuilder...
You can download it from the following link -
http://www.codeplex.com/wspbuilder
A very good documentation cum tutorial can be found from -
http://www.zimmergren.net/archive/2009/04/08/wspbuilder-walkthrough-of-the-visual-studio-add-in.aspx
So, before ending this post lets summarize the whole thing in novice statements -
Manifest.xml: Instructs SharePoint where to deploy the files held in the cabinet. File paths depend on the containing XML element: assembly paths are relative to the target /bin directory, TemplateFiles are relative to the 12-hive's TEMPLATE directory, DwpFiles are relative to the wwwroot\wss\VirtualDirectories\wpcatalog directory, and FeatureManifests and Resources are both relative to the 12-hive's TEMPLATE\FEATURES directory.
Feature.xml: ElementFile locations are relative to the directory structure where the feature is installed (eg. as specified in Manfiest.xml)
Elements.xml (via Feature.xml): Module URLs are targets within MOSS; File URLs are relative to the Module URL
Web Deployment Projects with Visual Studio 2005 ??? WHY ???
More control over assembly naming and output.
Custom pre-processing and post-processing for the build.
The ability to exclude, add, and transform files and directories during builds.
The ability to modify the Web.config file to change database connection strings, application settings, or the URLs for Web references, depending on the build configuration. (For example, it might be necessary to use different values for development, test, staging, and release settings).
For details, just visit the following link :
http://msdn.microsoft.com/en-us/library/aa479568.aspx
To merge the assemblies created during ASP.NET 2.0 pre-compilation
To solve this kind of irritating problem, Microsoft provides an add-in that consists of a tool to merge the assemblies created during ASP.NET 2.0 pre-compilation, and provides a comprehensive UI within Visual Studio 2005 to manage build configurations, merging, and using pre-build and post-build tasks with MSBuild.
You can download the add-in from the following location -
http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx
After downloading and Installation, open up your solution. Select Web Application Project in the Solution Explorer, riht click and select Add Web Deployment Project. Next give the name and location for it and select OK.
Now, In Solution Explorer, select Web Deployment Project that you have just added and right click on it and select Property. In the property dialog box, you can manipulate its behaving patterns, like - strong name key, assembly name, version etc. etc. When you are done save it and Then Build the Web Deployment Project. Next, go to the location in your hard drive where the web deployment project physically resides. There you will find the Bin folder, inside which your new born sweet assembly resides... :)
Monday, August 24, 2009
Delegates and SPSecurity.RunWithElevatedPrivileges()
It is quite common to get a code stub from seniors for a particular purpose and pasting it inside own class, changing the logic and pressing F5!!! :) ... Visual Studio always rocks...
When I first started learning SharePoint, the code stub given to me by my seniors, always looks very peculiar to me!!! Specially the following line -
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ospSite = new SPSite(ConfigurationManager.AppSettings["SiteURL"].ToString()))
{
ospWeb = ospSite.OpenWeb();
}
});
So lets drill down it. First comes Delegates.
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:
public delegate int PerformCalculation(int x, int y);
Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.
Delegates Overview
Delegates have the following properties:
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods don't need to match the delegate signature exactly.
C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
Now, Here comes an exciting question : When to Use Delegates Instead of Interfaces ?
Both delegates and interfaces allow a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct; a delegate can created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object with no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should they use an interface?
Use a delegate when:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need access other properties, methods, or interfaces on the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the method.
Use an interface when:
There are a group of related methods that may be called.
A class only needs one implementation of the method.
The class using the interface will want to cast that interface to other interface or class types.
The method being implemented is linked to the type or identity of the class: for example, comparison methods.
Now, here comes the main subject of today's post: running code in sharepoint with elevated rights, an operation sometimes required, sometimes abused and often misunderstood.
The WSS Object Model provides a huge number of classes, some of which can carry-out potentially dodgy actions, so require elevation to run. Ordinarily you'd just deal with this by logging in as a user with rights to carry out the operation, but occasionally this isn't practical or possible, and that's where today's subject comes in.
Let's say, just as an example, you're creating an anonymously-accessible site. In a Control on on of the pages you want to enumerate subsites of your site, and grab some properties thereof, maybe for display, maybe for some other operation in your code - however, this isn't something an anonymous identity can do.
In steps our hero - RunWithElevatedPrivileges()
Used correctly, this method allows a specified block of code to run in the context of the SharePoint System Account, a powerful method with much potential. Here's the summary from the SDK:
[SharePointPermissionAttribute(SecurityAction.Demand, Impersonate=true)] [SharePointPermissionAttribute(SecurityAction.Demand, ObjectModel=true)] public static void RunWithElevatedPrivileges ( CodeToRunElevated secureCode)
Now the CodeToRunElevated parameter can be a reference to a void, parameterless method or an anonymous method via delegate() - please, follow the SDK link if that's unclear.
Pretty simple, huh? Yep, well as always there's a catch or two.
1. If you're manipulating any Object Model elements within your elevated method, you need to get a fresh SPSite reference inside this call. For example
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite mySite = new SPSite(http://sharepoint/);
SPWeb myWeb = SPSite.OpenWeb();
// further implementation omitted
});
2. You can't just use SPContext.Current.Site to get your SPSite reference - or you'll ber handed the object with the security context of the anonymous (or non-elevated) user and your elevation will not work as expected.
3. If you need to Update() anything inside this block, you'll need to call SPSite.AllowUnsafeUpdates() on your new site reference (or web reference) as per this SDK entry.
So those are the gotchas. Following those we have the obvious security warnings - be careful what you do within this call, as the system identity has full control over SharePoint and could do Very Bad Things if incorrectly used. Sanitise any user input very carefully if you're going to let it anywhere near this method - you certainly don't want a user finding some injectable exploit into this code. Exercise caution over what you do, for this power must be used wisely.
Sunday, August 23, 2009
Exploring Content Type & Creating a Custom Content Type with Event Receivers
Content Types, a core concept used throughout the functionality and services offered in Windows SharePoint Services 3.0, are designed to help users organize their SharePoint content in a more meaningful way. A content type is a reusable collection of settings you want to apply to a certain category of content. Content types enable you to manage the metadata and behaviors of a document or item type in a centralized, reusable way.
For example, consider the following two types of documents: software specifications and legal contracts. It is reasonable that you might want to store documents of those two types in the same document library. However, the metadata you would want to gather and store about each of these document types would be very different. In addition, you would most likely want to assign very different workflows to the two types of documents.
So, What is METADATA ???
Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is inserted into one portion of the file, while your code is converted to Microsoft intermediate language (MSIL) and inserted into another portion of the file. Every type and member defined and referenced in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on.
Metadata describes every type and member defined in your code in a language-neutral manner. Metadata stores the following information:
Description of the assembly.
Identity (name, version, culture, public key).
The types that are exported.
Other assemblies that this assembly depends on.
Security permissions needed to run.
Description of types.
Name, visibility, base class, and interfaces implemented.
Members (methods, fields, properties, events, nested types).
Attributes.
Additional descriptive elements that modify types and members.
Benefits of Metadata
Metadata is the key to a simpler programming model, eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference. Metadata allows .NET languages to describe themselves automatically in a language-neutral manner, unseen by both the developer and the user. Additionally, metadata is extensible through the use of attributes. Metadata provides the following major benefits:
1. Self-describing files.
2. Language interoperability and easier component-based design.
3. Attributes.
Now, back to content type: A content type can include the following information:
The metadata, or properties, you want to assign to this type. These are represented by columns added to the list or document library when you add the content type.
Custom New, Edit, and Display forms to use with this content type.
Workflows available for items of this content type. These can be defined to start automatically based on a selected event or condition, or through user selection.
For document content types, the document template on which to base documents of this type.
Any information necessary for custom solutions associated with this content type. You can store this information in the content type as one or more XML documents
So, after theory comes the practical part. Now, for How to: Create a Custom Content Type with Event Receivers please go through the following simple step by step document available in the MSDN -
http://msdn.microsoft.com/en-us/library/dd206944.aspx
Debugging SharePoint Applications
1. Debugging with Visual Studio extensions for Windows SharePoint Services
Press the F5 key to begin debugging with Visual Studio extensions for Windows SharePoint Services. The following procedure demonstrates how to enable F5 debugging.
To enable F5 debugging
Locate and open the target SharePoint application's Web.config file. By default, it is located in C:\Inetpub\wwwroot\wss\VirtualDirectories\80.
Find the following line of code and change the debug attribute to true.
Save the changes to the Web.config file.
In Visual Studio, right-click the SharePoint project, and then click Properties.
Click the Debug tab, and then type the target SharePoint URL in the Start browser with URL box.
Place a breakpoint in the code, and then press F5.
2. Performing Manual Debugging
You can debug a SharePoint application without using Visual Studio extensions for Windows SharePoint Services by attaching it to the W3wp.exe process. The following procedure demonstrates how to do this.
To attach to the W3wp.exe process
Make sure that the SharePoint application is using the latest compiled source code. This may require that you recompile your source and install the assemblies into the global assembly cache. Alternatively, you may need to copy the assemblies to the bin folder of SharePoint's virtual directory. In either case, you must run the Microsoft Internet Information Services (IIS) command-line utility Iisreset.exe.
Place a breakpoint in the code you want to debug.
On the Debug menu, click Attach to Process.
In the list of available processes, find the W3wp.exe process, and then do the following, as applicable:
If the W3wp.exe process is not listed, make sure that the Show processes from all users and Show processes in all sessions check boxes are selected.
If the W3wp.exe process still is not listed, open a Web browser and navigate to the application's SharePoint site. After you navigate to the SharePoint site, return to Visual Studio. In the Attach to Process dialog box, click the Refresh button to locate the W3wp.exe process.
If you see multiple W3wp.exe processes listed and are not sure which one of them is running the code, click them all.
Click the Attach button.
3. Performing Remote Debugging
You can debug a SharePoint application when it is running on a remote computer by attaching it to the remote W3wp.exe process. The following procedure demonstrates how to do this.
To attach to a remote W3wp.exe process
Make sure that the remote SharePoint application is using the latest compiled source code. This may mean that you must recompile your source and install the assemblies into the global assembly cache of the remote server. Alternatively, you may need to copy the assemblies to the bin folder of SharePoint's virtual directory on the remote computer. In either case, you must run the Microsoft Internet Information Services (IIS) command-line utility Iisreset.exe.
Make sure that the Visual Studio 2008 Remote Debugger is installed on the remote computer.
Start the Visual Studio 2008 Remote Debugger on the remote computer. For more information about using the remote debugger, see How to: Run the Remote Debugging Monitor on MSDN.
In Visual Studio on the local computer, open the solution, and then set a breakpoint.
On the Debug menu, click Attach to Process.
In the Qualifier text box, type the name of the remote computer, and then click Refresh.
In the Available Processes list, find the W3wp.exe process, and then do the following, as applicable:
If the W3wp.exe process is not listed, make sure that the Show processes from all users and Show processes in all sessions check boxes are selected.
If the W3wp.exe process still is not listed, open a Web browser and navigate to the application's SharePoint site. After you navigate to the SharePoint site, return to Visual Studio. In the Attach to Process dialog box, click the Refresh button to locate the W3wp.exe process.
If you see multiple W3wp.exe processes listed and are not sure which one of them is running the code, click them all. Click Attach.
Saturday, August 22, 2009
The SharePoint Object Model
Server and Site Architecture: Object Model Overview (Courtsy MSDN)
Windows SharePoint Services offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, you can drill down through the object hierarchy to obtain the object that contains the members you need to use in your code.
Entry Points
Depending on the type of custom application or solution that you are creating, you use different entry points into the object model to obtain the appropriate object from which to start. For example, if you are customizing administration and configuration of a deployment, you can use the static ContentService property to return the current Web service object and its collection of Web applications. To modify settings in the administrative Web application, instead use the AdministrationService property. Collection classes that derive from the Microsoft.SharePoint.Administration.SPPersistedObjectCollection class inherit a GetValue method that you can use to return a specific object from a collection.
Note:
If you are creating a Web Part, custom Web service, or Web application to work with site collections, individual sites, or lists, you can use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. When you create a Web application in the /_layouts virtual directory, its functionality becomes available to all sites on the Web server. Outside of an HTTP context, such as in a console application or a Windows application, use a constructor of the SPSite class to obtain a specific site collection and to reach various objects within the collection. For more information, see Getting References to Sites, Web Applications, and other Key Objects.
Server Architecture
The following diagram shows the Windows SharePoint Services server architecture in relation to the collections and objects of the Microsoft.SharePoint.Administration namespace.
The SPFarm object is the highest object within the Windows SharePoint Services object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.
Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
Each SPService object represents a logical service or application installed in the server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, Microsoft SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the Microsoft Office system.
An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.
An SPDatabaseServiceInstance object represents a single instance of a database service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
Each SPWebApplication object represents a load-balanced Web application based in Internet Information Services (IIS). The SPWebApplication object provides access to credentials and other server farm wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; that is, a set of one or more physical servers that appear as a single server to users.
An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
An SPSiteCollection object represents the collection of site collections within the Web application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection.
Site Architecture
The following diagram shows the Windows SharePoint Services site architecture in relation to the collections and objects of the Microsoft.SharePoint namespace.
Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
Each SPField object has members that contain settings for the field.
Each SPListItem object represents a single row in the list.
If you install "Infrastructure Update for Windows SharePoint Services 3.0 (KB951695)," custom solutions may fail if they call the SharePoint object model while impersonation is suspended. If you use Windows authentication and your code calls the SharePoint object model from an IIS worker process, the request must impersonate the calling user’s identity. Windows SharePoint Services configures ASP.NET to impersonate the calling user automatically, but your code may work unexpectedly, or fail, if you suspend impersonation--for example, by calling the RevertToSelf function of the Windows API, or by calling the System.Security.Principal.WindowsIdentity.Impersonate method and passing IntPtr.Zero as the value of the user token parameter. Even if your code does not explicitly revert to self, it might be called by ASP.NET after it reverts to self, such as happens when implementing a virtual path provider; if your code does not impersonate the calling user, it might not function properly.
Next to the Object Model, it is always good to learn some best coding practices when using SharePoint object model. So here you can find that -
Monday, August 17, 2009
SharePoint Site back up and restoration
1. Open Command Prompt and Go to Program Files->Common Files->Microsofft Shared->Web Server Extension->12->Bin
2. next write - For site collection backup
stsadm -o backup -url <"URL name"> -filename <"file name with full path"> [-nositelock] [-overwrite]
3. Check if the back up has been successfully completed or not.
4. If yes, then create one web application from the central admin and note down the url of the web application
5. now, in the command prompt write -
For site collection restore
stsadm -o restore -url <"web app URL name"> -filename <"back up file name with path"> [-hostheaderwebapplicationurl] <"Web application URL"> [-overwrite]
6. now reflect necessary changes in the config files and start using restored site.
Thursday, August 6, 2009
Resolving "Session State not enabled" error when creating workflow in SharePoint Site
Next, uncomment the highligted section shown below -
Now, go back to the site and press F5 and you are done.
Wednesday, July 29, 2009
Tag Driven Information Architecture using MOSS 2007
Saturday, June 13, 2009
Creating workflows using SharePoint designer
http://www.codeproject.com/KB/sharepoint/8StepsWorkflows.aspx
Tuesday, May 12, 2009
Making assemblies CLSCompliant
1. Unsigned types should not be part of the public interface of the class.
What this means is public fields should not have unsigned types like uint or ulong, public methods should not return unsigned types, parameters passed to public function
should not have unsigned types. However unsigned types can be part of private members.
2. Unsafe types like pointers should not be used with public members.
However they can be used with private members.
3. Class names and member names should not differ only based on their case.
For example we cannot have two methods named MyMethod and MYMETHOD.
4. Only properties and methods may be overloaded, Operators should not be overloaded.
The above-mentioned rules should be followed only for the types and member that are
publicly exposed by your program. Private classes, private methods and local variables need to follow the rules.
By default the C# complier does not check for CLS compliance of the code.
We should explicitly make the C# compiler check for CLS compliance by using the CLSCompliantAttribute class. By specifying the value of true to this attribute we specify that the C# compiler should check for the CLS compliance of the code. The CLSCompliantAttribute can be applied to assemblies, modules, types, and members.
To make an assembly CLSCompliant, add the following line in the AssemblyInfo.cs file of that project -
[assembly: CLSCompliant(true)]
Friday, May 8, 2009
How to list all SharePoint sites in the Site Gallery
When you create a site collection in SharePoint based on the OOTB starter template "Collaboration Portal Template" you get a series of sub sites such as "Document Center", "News", "Reports", "Search" and "Sites". Typically if your organisations has just installed SharePoint or are evaluating SharePoint this "Collaboration Portal Template" is the first place an end user will start their interaction with SharePoint.
One main point to note is that the slight variation of the available templates under the "Publishing" tab in Central Administration and on an existing SharePoint site which has been based on the "Collaboration Portal Template" which is available the first time you create your starter site collection in the Central Administration Site when you first install and configure SharePoint. Typically this is done by your SharePoint Administrator at the beginning.
Available via Central Administration | |
Available via an existing SharePoint Site
I want go into too much details about these templates now since the point of this post is to highlight how you can list all your SharePoint sites in the "Site Directory".
One of the Site Templates that you can use to categorise and view all of your SharePoint sites is the "Site Directory" Template. Often the Site Directory template features and functionality are not used effectively due to the not so apparent configuration options that you or your SharePoint administrator need to configure to ensure that any SharePoint site and site collection created in your SharePoint farm is categorised and listed to provide you with a list of all sites. Effectively you can almost create a global categorisation of all your sites in your SharePoint deployment.
This process involves some thinking and a few configuration options that I will highlight. Scenario: You want to create a single list of all your SharePoint site's that are being used in your organisation and you also want to minimise the overhead of categorising these manually. You also want your users with rights to create sites the ability to categorise the sites they create when they are creating them.
Master Site Directory
To ensure that any site and site collection being created within your SharePoint farm is listed in your "Site Directory" you need to add/configure the URL of your "Site Directory" in Central Administration. Go to Central Administration and to the Operations Tab. Under "Global Configuration" click on "Master site directory settings".
Once the URL of your master site directory has been set you can enforce the listing of new site collections in the Site Directory and ensure that you capture the correct Categorisation meta data for your sites. This settings effectively provides the Global location for your Master Site Directory. You may think that this is all it's required to list all the sites in the Site Directory but you also need to configure this at your site collection level in your deployment.
Site Directory Settings
Next step involves that you configure the "Site directory settings" to capture site categorisation when users create sites in an existing site collection. Go to Site Settings and select "Site directory settings".
Once you configure the settings in the next screen accordingly you can enforce your site's to be listed in the Site Directory and capture the correct meta data against your sites. One decision that you may need to make is if you should allow users to create "Site Collections". Site Collections effectively provide isolation and portability. In large deployments particular types of sites depending on their use and functionality maybe better created as Site Collections. For users to be able to create site collections Administrators need to enable "Self-Service Site Management" for the SharePoint web application.
Once you enforce the listing of sites and site categorisations any site that is created by an end user will always be listed in the "Master Site Directory" .
To add some context to this consider this scenario. In my example I have a SharePoint Intranet/Portal where all employees are directed to access organisational information. The Intranet/Portal provides access to various functional business applications such as Collaboration sites and document management sites etc. The URL of this SharePoint site is http://intranet/ In this deployment my SharePoint Administrator sets the Global Site Directory setting URL as http://intranet/SiteDirectory in Central Administration. I want all sites created within my organisation to be listed in this directory. Since I am the "Owner" of the Intranet I can enforce this at the Intranet/Portal level.
Furthermore certain departmental leads have the "Create Site Collection Permission" and are allowed to create own "Site Collections". The authority to create site collections is delegated by IT to these groups. Since the global setting enforces all sites and site collections to be listed in the "Site Directory" users are able to find any new site that is created in my deployment.
Also any new SharePoint web applications that are created in my Farm can be effectively listed in the Global Site Directory since the global setting enforces new Site Collections created via Central Administration on the same Farm to be listed in the Site Directory. When a new Site is created under the existing site structure the site can now be categorised and listed in the "Site Directory"
Once the site is created the site is listed under the correct Category.
Site Directory Links Scan
Another most often overlooked functional part of maintaining the Site Directory is hidden away in Central Administration. This is called "Site Directory Links Scan"
Effectively you can check for broken site links and get a report as well as update your site description listings in the Site Directory using Site Directory Links Scan. Site Directory Links Scan is available via the Operations tab in Central Administration.
The site property update is automated to reflect any changes you may apply to how the sites are categorised and listed in the Sites list in your Site Directory.
Once you have enabled Site Directory Links Scan you can also go to your SharePoint Site and from your Site Directory site select Site Settings and "Scan for Broken Links" which will initiate a manual scan. This will search the "Sites" list located in the Site Directory site for any changed or broken links.
The scanner will provide you with options of what View you would like to scan and update you of the Scan progress.
Resources for Planning Sites and Site Collections
Default SharePoint Site Templates - End/Power User Oriented Content
Planning Process for creating Sites - TechNet IT Pro Content @ Chandima Kulathilake
Thursday, May 7, 2009
Index for Stsadm operations and properties (Office SharePoint Server)
http://technet.microsoft.com/en-us/library/cc263384.aspx
Find and delete broken links in the Site Directory in SharePoint automatically
On the top navigation bar, click Operations.
On the Operations page, in the Global Configuration section, click Site directory links scan.
On the Site Directory Links Scan page, in the Choose views to scan section, type the URLs of the site directory views that you want to scan for broken links in the Site directory view URLs box (for example, type http://[ServerName]/sitedirectory/lists/sites/allitems.aspx). Separate the URLs by using commas.
Note:
The site directory is updated the next time that the site directory timer job is run. By default, this timer job is scheduled to run daily.
In the Update Site Properties section, select the Update title and description of links in the site directory automatically check box if you want the site directory links scan to automatically update link titles and descriptions.
Important:
This overwrites previous title and description values in the site directory.
Click OK.
Use the command line to schedule the site directory links scan to run automatically
You can use the Stsadm command-line tool to schedule a job to run the site directory links scan.
Note:
You must be a member of the Administrators group on the local computer to use the Stsadm command-line tool.
To use the command line to schedule this job, perform the following steps:
On the drive where SharePoint Products and Technologies are installed, change the directory to %COMMONPROGRAMFILES%\Microsoft shared\Web server extensions\12\Bin.
At the command prompt, type stsadm -o setsitedirectoryscanschedule -schedule recurrence string
The recurrence string indicates the frequency or the date and time at which to run the job.
Examples include:
every 5 minutes between 0 and 59
hourly between 0 and 59
daily at 15:00:00
weekly between Fri 22:00:00 and Sun 06:00:00
monthly at 15 15:00:00" "yearly at Jan 1 15:00:00
To view the current schedule for this job, you can use the following operation:
stsadm -o getsitedirectoryscanschedule