Friday, October 28, 2011

The Disposable Pattern in SharePoint Development



If you don’t properly dispose of objects in the SharePoint object model that implement
IDisposable, you will have memory usage problems in your application. Under heavy
load, SharePoint may perform poorly or even exit when memory allocation fails. So
it is critical to properly dispose of these IDisposable objects. The objects to
be most careful of are SPSite and SPWeb, which must be disposed of because they
consume large amounts of unmanaged memory.


But I Thought Garbage Collection Took Care of Memory Management?

You might wonder why you must dispose of these objects yourself and why garbage collection doesn’t just take care of these things. The answer is that an object like SPSite uses a mix of managed and unmanaged code. 
The memory usage of the managed side of SPSite is monitored by the .NET garbage collector, and when enough memory is used by the managed code, the garbage collector will kick in. The problem is  that the .NET garbage collector doesn’t watch the unmanaged code’s use of memory and the unmanaged memory use is much greater than the managed memory use. So you
can quickly run out of memory on the unmanaged side without .NET ever feeling like it needs to do a garbage collection.
How to spot the problem?
  1. The memory usage of Does your application pool recycle frequently, especially under heavy loads (assuming that the application pool is set to recycle when a memory threshold is reached)?
    (The memory threshold should be 800 MB–1.5 GB (assuming at least 2 GB of RAM). Setting the recycle of the application pool to occur closer to 1 GB gives the best results, but experiment to determine what settings work best for your environment. If the recycle setting is too low, you experience performance issues because of frequent application pool recycles. If the setting is too high, your system experiences performance problems because of page swapping, memory fragmentation, and other issues.)
  2. Does your system perform poorly, especially under heavy loads? (As memory usage begins to increase, the system must compensate, for example, by paging memory and handling memory fragmentation.)
  3. Does your system crash or do users experience unexpected errors such as timeouts or page-not-available errors, especially under heavy loads?
  4. Does your system use custom or third-party Web Parts or custom applications?

1st Approach

If your sites are displaying any of the unusual behaviors described previously, you can determine whether the cause is a memory leak due to incorrectly disposed objects by checking the ULS logs (available at C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\LOGS) for entries related to the SPRequest object.Each instance of SPSite and SPWeb contains a reference to an SPRequest object that,in turn, contains a reference to an unmanaged COM object that handles communications with the database server. Windows SharePoint Services monitors the number of SPRequest objects that exist in each specific thread and in parallel threads, and adds useful entries to the logs. For more information on this click here:


2nd Approach:

Microsoft provides a tool to help you detect and track down objects you aren’t disposing of properly called the SharePoint Dispose Checker tool. That tool is found here: http://code.msdn.microsoft.com/SPDisposeCheck

Coding Techniques to Ensure Object Disposal

You can employ certain coding techniques to ensure object disposal. These techniques include using the following in your code:
  • Dispose method
  • using clause
  • try, catch, and finally blocks
Dispose method

The basic idea behind using the Dispose method is you call it on an IDisposable object when you are done with it. At the point you call Dispose on the object the managed and unmanaged memory associated with the object is reclaimed. The object is also no longer usable after you call Dispose on it—any subsequent calls to the object will result in an error.

              Example

                SPSite mySite = new SPSite("http://mySite");
                //do something with mysite
                mySite.Dispose(); //disposes of memory used by mysite
               //now don’t use mySite object as it will throw error

The using Clause

You can automatically dispose of SharePoint objects that implement the IDisposable interface by using the Microsoft Visual C# using statement.

             Example

             String str;

             using(SPSite oSPsite = new SPSite("http://Myserver"))
            {
                  using(SPWeb oSPWeb = oSPSite.OpenWeb())
                  {
                          str = oSPWeb.Title;
                          str = oSPWeb.Url;
                   }
            }

It also makes your code more clear and makes it impossible for you to accidentally call into the object after it has been disposed because it also goes out of scope when you are done with it.

The try, catch, and finally Blocks

Using try, catch, and finally blocks obviously makes sense whenever you need to handle exceptions. Any code within a try/catch block should have a governing finally clause, which ensures that the objects that implement IDisposable are disposed.
There are cases in your code where you may be creating objects that are IDisposable that may not be as obvious. For example, you may have a foreach loop that iterates over a collection that returns SPSite or SPWeb objects. For these cases you use a try, finally block in the iterator to ensure that each IDisposable object created in the foreach loop is disposed of properly.
                
Example
                  using (SPSite spSite = new SPSite('http://mysite/'))
                 {
                      foreach (SPWeb spweb in spSite.AllWebs)
                       {
                             try
                             {
                                   Console.WriteLine(spweb.Name);
                             }
                             finally
                            {
                                  if (spweb != null)
                                  {
                                           spweb.Dispose();
                                  }
                            }
                       }
                  }

Wednesday, October 26, 2011

Sandboxed Solutions versus Farm Solutions

Sandboxed Solutions versus Farm Solutions


Why Sandbox came into Existence?

Each server in the farm can have multiple web applications running on it. A web application can in turn have one or more site collections, and a site collection has one or more sites. Farm solutions can impact the entire SharePoint system and are available to all site collections and sites in the farm. This is sometimes desirable, but sometimes can have undesired effects because a farm solution that is misbehaving can impact all sites and site collections in the system.
  • Sandboxed solutions are deployed at the site collection level rather than the farm level, so this lets you isolate a solution so it is only available to one site collection within the farm.
  • Sandboxed solutions also run in a separate process from the main SharePoint IIS web application
  • Process and the separate process is throttled and monitored with quotas to protect the SharePoint site from becoming unresponsive due to a misbehaving sandboxed solution.
  • It is worth mentioning that sandboxed solutions solve an organizational problem as well—in many organizations it is difficult to get permission to install a farm solution because of the possible impact that could have on the SharePoint system. System administrators in charge of running a Share-Point site have been reluctant in the past to allow custom solutions to run on their sites. With the advent of SharePoint 2010, there is now a robust system in place to monitor and throttle these custom solutions so that system administrators don’t have to worry about a custom solution bringing the entire SharePoint site down.
If all good with Sandbox then, why we require Farm Solution?

There are restrictions on the kinds of solutions you can build with a sandboxed solution.

The most significant restrictions disallow creation of
  • application pages
  • visual web parts
  • code-based workflows with a sandboxed solution.
So in the end, the choice between sandboxed and farm solutions should come down to whether or not you need to create an application page or a workflow with code in it. For these kinds of solutions, you should pick a farm solution. For all other solutions, pick a sandboxed solution. The only other reason to use a farm solution over a sandboxed solution is if you really have some code that needs to run at the web application or farm level, perhaps because it needs to interact with or move data between multiple site collections. In this case, you would create a farm solution as well.

Friday, June 3, 2011

Deploying A User Control In SharePoint Site

1) Create a web application called SharedUserControls.

2) Remove your web.config and default.aspx page.

3) Create a web user control called (.ascx page) in the same project and add whichever controls you want to add in this web user control.




In the Source of your user control(ascx page) include the ClassName attribute, for classname, give any name with any extension. Here the classname is MyCntrl.as



4) Here we have created a text box, a label and a button which displays the textbox text on button click in the label.
5) Add the web deployment project to the same project by selecting "Add Web Project Project..." from the Build menu. In Vsts 2008, you will need an extension for Adding Web Deployment Project. Download the same and then this option will be available inside the Build Menu.


6) It will create a new web deployment project, Keep the default name as it is and click OK.



7) Double click the new project to get the project property pages.

Uncheck the last check box - "Allow this precompiled site to be updatable".
8) Go to the "Output Assemblies" tab
9) Select "Merge all pages and control outputs to a single assembly"
10) Call the assembly name: "SharedUserControlMerged”



Assign strong names to both the dlls(i.e. both for the user controls(SharedUserControls.dll and the SharedUserMerged.dll)
11) Build the solution and put the SharedUserControlMerged.dll into the GAC.
12) Open the Sharepoint designer site where you want to use the User Control(aspx page)
13) Register the UserControl, by adding the code

<%@ Register tagprefix="PrintfuncLibrary" namespace="MyCtrl" assembly="SharedUserControlMerged, Version=1.0.0.0, Culture=neutral, PublicKeyToken=af7fd7f230293b2e" %>

14) Once registered, add the UserControl, in the place of your choice by adding the following code.
Next to the tag prefix , give the same extension that you gave in your user control source. Here the extension used was as.

<form id="form1" runat="server">
<?XML:NAMESPACE PREFIX = PrintfuncLibrary /><printfunclibrary:as id="SharedUserControls" runat="server"></form>

16) In the web.config of your sharepoint site, Register your assembly as a safe control. The namespace will be the same as the className in the source of your User Control(ascx page) and assembly name and Public Token Key will be that of the Merged dll that you put in the GAC.

<safecontrols>
<safecontrol allowremotedesigner="True" safe="True" typename="*" namespace="MyCtrl" assembly="SharedUserControlMerged, Version=1.0.0.0, Culture=neutral, PublicKeyToken=af7fd7f230293b2e">

17) Preview your sharepoint site in the browser, you will notice that the user control you deployed in asp.net appears in the sharepoint site.

Thursday, December 31, 2009

Custom Feature to Create a Content Type : Part 2

1) Create a new project (class Library) and then we will be creating a directory structure where we will create a directory called MyContentType which we will be deploying to the SharePoint feature folder. [Hence we are mimicking or shadowing the directory structure as is present in the SharePoint 12 hive].

2) Then we will create a XML file called feature.xml which contains a Feature element and it defines a feature and specifies the location of assemblies, files, dependencies, or properties that support the Feature.


< Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="08A7F171-A9A2-4a9b-8CC2-E1686C6F35A2"
Title="My First Content Types"
Description=" Content Type of the Site"
Version="1.0.0.0" Scope="Site" Hidden="False" >
< elementmanifests >
< elementmanifest location="MyContentType.xml" >
< elementmanifest location="MyContentTypeColumn.xml" >
</elementmanifests >
</feature >


The feature element is the root element which contains the following attributes:
Id (a guid)
Title (Title of the feature)
description (description of the feature)
version (1.0.0.0, current feature version)
Scope (web, site, web application, farm) for content type we have to keep at Site.
xmlns (http://schemas.microsoft.com/sharepoint/, generally just the SharePoint namespace).

Notice the "ElementManifest" elements, these reference separate xml files "MyContentType.xml" and "MyContentTypeColumn.xml" which have yet to be created. These referenced xml files will contain field/column references that will be used in our content-type.

3) Create two xml files in your MyContentType folder, "MyContentType.xml" and “MyContentTypeColumn.xml". The "MyContentType.xml" file will define our content-types and contain references to the fields we create in our "MyContentTypeColumn.xml" file. The "MyContentTypeColumn.xml" file will define the fields and columns available for our content types.

4) First we will create a top level element called Elements inside which we will be adding the element called ContentType

< Elements xmlns=http://schemas.microsoft.com/sharepoint/ >
< ContentType ID="0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390053F95050258F46abA22C328B17956A00"
Name="MyContent" Group="Custom Content Types"
Description="Custom Content type designed by Hemant"
Hidden="FALSE" >
< FieldRefs >
< FieldRef ID ="{7FE28353-9609-455d-B716-6E32E98084E5}" Name="MyHobby"/>
< FieldRef ID ="{B6014DB3-B39E-4ef2-8924-AF209F099BFD}" Name="MyBestMovie"/>
</FieldRefs>
</ContentType>
</Elements>


The "ContentType" element contains a few attributes:
Name (name of ContentType)
Group (group the ContentType belongs to)
Description (description of the ContentType)
Version(version of ContentType)

The "Id" attribute is a concatenation of a reference to its parent(s) content-type(s) and its own unique identifier. Our content-types inherit from the Publishing Content Types called Page who’s Id is underlined as shown above and then we add our own unique Id.

The "FieldRef" element, which is wrapped by the "FieldRefs" element, contains attributes referencing directly to the fields used within our content-type. The "ID" attributes references a unique ID of the Field that we wish and the name reference the name of that Field. The fields that we are referencing are all custom but could very well be an already existing field (you can find existing fields in the feature directory of the MOSS 12 hive).

5) Again we will be creating an XML file called Elements.xml named “MyContentTypeColumn.xml" In this file we define each of the fields referenced by our content-type in the previous xml file "MyContentType.xml”. The "Field" element contains a few attributes that we need to create our custom fields:

ID (guid, unique identifier for our field)
Name (the internal name of the field)
StaticName (the static name field)
SourceID (a reference to the sharepoint v3 namespace)
Group the group where the column will appear
DisplayName (the name that appears in our content-type)
Type (the data-type of the field i.e text, number, lookup)
Format (the format that thefield is presented)
Required (boolean, whether the field is required in our content-type)
Sealed (see schema at the end)

< Elements xmlns="
http://schemas.microsoft.com/sharepoint/" >
< Field ID ="{7FE28353-9609-455d-B716-6E32E98084E5}" Name="MyHobby"
Type="HTML" Title="MyHobby"
DisplayName="MyHobby" RichTextMode="FullHtml"
Group="MyCustomTypes" StaticName="MyHobby" RichText="TRUE" >
</Field >
<Field ID ="{B6014DB3-B39E-4ef2-8924-AF209F099BFD}" Name="MyBestMovie"
Type="HTML" Title="MyBestMovie"
DisplayName="MyBestMovie" RichTextMode="FullHtml"
Group="MyCustomTypes" StaticName="MyBestMovie" RichText="TRUE" >
</Field >
</Elements >


6) Now that it's ready, save all the files and copy it into the "Feature" directory of the 12 hive (12/Template/Features).Once copied, open up the "stsadm" command-line tool and enter the following commands:
stsadm -o installfeature -name CustomContentTypes –force

7) Now feature is waiting to be activated on the site of your choice, it can be activated from the command line or through the “Modify all Site Settings” in Site Action.

stsadm -o activatefeature -filename MyCustomContentTask Feature.xml -URL
http://localhost:82/

Monday, December 14, 2009

Features in wss3.0 - Part 1


Why Features came into existence?


When a site was created in wssv2, it was not easy to add new functionality to the site at the later date without writing some custom code to implement the changes. In addition, when some sort of functionality was reused across multiple site definitions or site template in wssv2, the functionality was literally copied to each site definition or template.Another benefit of using Features is in the use of site definition (ONET.xml) files. ONET.xml files provide Windows SharePoint Services with information about the navigation, lists, and document libraries that users can create. In the previous version of SharePoint, ONET.xml files have a tendency to get very large. With the advent of Features, the ONET.xml file shrinks because Features can now contain the information that was previously defined in the ONET.xml file.

Onet.xml
When you install Windows SharePoint Services 3.0, six Onet.xml files are placed within the setup directory, one in \Program Files\Common Files\Microsoft Shared\Web Server Extensions \12\TEMPLATE\GLOBAL\XML that applies globally to the deployment, and five in different folders within ...\TEMPLATE\SiteTemplates that apply to each of the five site definitions that ship with Windows SharePoint Services 3.0. They are Blog sites, the central administration site, Wiki sites, Meeting Workspace sites, and team SharePoint sites. Only the last two of these families contain more than one site definition configuration in Windows SharePoint Services 3.0. The global Onet.xml file defines list templates for hidden lists, list base types, a default definition configuration, and modules that apply globally to the deployment. The five Onet.xml files in the \SiteTemplates directory define navigational areas, list templates, document templates, configurations, modules, components, and server e-mail footer sections used in the five site definitions.

Working with Features

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.
Exploring the Components of a FeatureFeatures are typically stored on the SharePoint server at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES. Each Feature has its own sub-directory that resides in this directory. Inside each Feature's sub-directory, you will find, as a minimum, a header file named feature.xml. The feature.xml file points to a manifest file that tells SharePoint where to find the code and XML that defines the Feature. The feature.xml file contains the Feature element that specifies the location of assemblies, files, dependencies, or properties that support the Feature. Optionally, the Feature element may point to an XML file that contains an Element element which defines the components and types that make up the Feature.The following are samples of the components that comprise a Feature.The Feature.xml File
The feature.xml file defines the metadata associated with a Feature.



< Feature Id="00BFEA71-E717-4E80-AA19-D0CBE412FFA6"
Title="Hello World Feature"
Description="$Resources: core,documentlibraryDesc;"
Version="1.0.0.0" Scope="Web" Hidden="FALSE"
DefaultResourceFile="documentLibrary"
ImageUrl="menuprofile.gif >
< elementmanifests >
<elementmanifest location="elements.xml" >
</elementmanifests >
</feature >

The following metadata is contained in the element in this XML file.
• ID: The GUID that uniquely identifies the Feature. This value must be unique across the server farm.
• Title: The name of the Feature. In an actual scenario, you will see the name of the Feature displayed on the Site Features web page inside the Site Settings section for a given SharePoint site.
• Description: The description of the Feature. Notice that in this sample, the description is retrieved from a resource file (a file with a .resx extension) instead of hard-coded in the file. The strings are stored as key/value pairs within the resource file. The following is a segment from a resource file named documentLibrary.resx that provides the description of the sample Feature.
• Version: The version of the Feature. This value can be incremented for successive versions of the Feature.
• Scope: Web or Site are the typical values. The scope defines the context in which the Feature can be activated or deactivated. Setting the scope equal to Web means that the Feature can be activated or deactivated within the context of the site. A setting of Site means that the Feature can be activated or deactivated within the scope of a site collection. The scope is set to the site collection displayed to the administrator in the Site Collection Features page. There are also WebApplication and Farm values.
• Hidden: TRUE or FALSE are allowable values here. This setting specifies if the Feature is visible in the list of Features on the Site Features web page. Setting the attribute to TRUE makes the Feature visible to users who want to activate it. Hidden Features must be activated either from the command line, in custom code, or through the dependency of another Feature.
• DefaultResourceFile: Specifies the central location for settings and other items that may change frequently.
• ImageUrl: Points to an image file that will be displayed next to the Feature in the user interface. element: The container element for elements.
element: Contains the location of the manifest file that contains the different elements that this Feature implements. The path to sub-directories and files is a relative path.


The Element.xml File


The Element.xml manifest file contains details of the different components or actions that make up a Feature.


< Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
< Field ID="{0B9E3314-3F9F-2aa8-4BCD-7CB89A6FB32D}"
Name="ProductName"
SourceID=http://schemas.microsoft.com/sharepoint/v3 StaticName="ProductName"
Group="ProductColumns"
DisplayName="Product Name" Type="Text" >
< /field >
< /elements >

Here, the manifest file defines a field that might be used in a list column.