Pages

Subscribe:

Wednesday, January 18, 2012

Programmatically Create a Site from Custom Site Template in SharePoint 2010


Here is the code snippet to create a Site using a Custom Site Template in SharePoint 2010.
     
using (SPSite site = new SPSite("http://sp2010:1234/"))
      {
                    using (SPWeb newWeb = site.OpenWeb())
                    {                         
                        newWeb.AllowUnsafeUpdates = true;                      
                        SPWebCollection subsites = newWeb.Webs;
                        SPWeb newSubWeb = subsites.Add("Site url", " Site name ", "Site description", 1033, {Name of the Site Template}, true, false);
                        newWeb.Update();
                    }
                }


 for eg: {Name of the Site Template} --> "{9D26F676-B943-451B-BED4-A8657A9C0FDF}#1InternalProject"


To get the custom Site Template GUID and Site Template Name you can use the below code in SharePoint 2010 even if the Template is in Solution Gallery. 
SPWebTemplateCollection templates = newWeb.GetAvailableWebTemplates(1033, true);
                        foreach (SPWebTemplate template in templates)
                        {
                           lblTemplate.Text  +=  template.Name;
                        }

Tuesday, January 10, 2012

TryGetList method in SharePoint 2010

Generally when we writing the code to get a list from the web, we will get  the error if the list does not exist. For that we will loop through the lists collection and checks whether it exists or not

           SPSite Site = SPContext.Current.Site;
            SPWeb Web = Site.OpenWeb();
            SPList  List = Web.Lists["List Name"];


If there is no list with the name ListName, it throughs null reference exception. To avoid this, In 2010 OM a new method is introduced in the SPListCollection .Simply use this method instead of looping all the lists and check its existance

            SPList List = Web.Lists.TryGetList("List Name");

            if (List != null)
              {
                 Response.Write("List Exist");
              }
           else 
                 Response.Write("List Doesnot Exist");

Happy Coding..!!!!

The List is too large to save as a template

The List is too large to save as a template. The size of a template cannot exceed 10485760 bytes.



If you try to save a list as a list template, you may see the following error due to the list being too large: The list is too large to save as a template. The size of a template cannot exceed 10485760 bytes.
You can increase the maximum size of a list / site template by running the following command (note that 500mb is the largest you can go):

stsadm -o setproperty -propertyname max-template-document-size -propertyvalue 50000000

Wednesday, December 14, 2011

Disposing SharePoint Objects

If you are using SharePoint object model, then it is very much important to correctly release resources. It should ensure that any unmannaged resources should be released as soon as they are no longer needed.Though garbage collector automatically releases memory allocated to unused objects, but it will release ina unpredictable manner. The .NET Framework provides the IDisposable interface, which exposes a Dispose method that you should call to explicitly release these unmanaged resources. To invoke Dispose method, you can use the using keyword, you can use the try/finaly code block or you can explicitely invoke Dispose method.
Example of using keyword:
using (SPSite site = new SPSite("URL of the Site Collection"))
{
// Code here
}

Internally the compiler converts the using block to try/finally block as shown below.
SPSite site = null;
try
{
site = new SPSite("URL of the Site Collection");
// Code here
}
finally
{
if (site != null)
site.Dispose();
}

The SPSite and SPWeb types both implement the IDisposable interface, and both allocate unmanaged memory. If you do not correctly release SPSite and SPWeb instances, you will probably experience memory leaks, crashes, and frequent application pool recycles.

But if they are derived from the context object then the framework will take care of releasing resources, you should not release the resources.
For example SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb().
Here the web object is derived from the SPContext, so we should not dispose that. Here SPWeb object web.Dispose() automatically called.

Create SharePoint list programmatically C#

In this article I am going to show how to create a SharePoint List and fields Programmatically using c#
public void CreateList()
{
    //choose your site
    SPSite site = new SPSite("http://sps2010");
    SPWeb web = site.OpenWeb();
    SPListCollection lists = web.Lists;

    //create new Generic list called "Custom List"
    lists.Add("Custom List ", "list Description",SPListTemplateType.GenericList);
    SPList newList = web.Lists["Custom List "];

    //create Text type new column called "Name"
    newList.Fields.Add("Name", SPFieldType.Text, true);

/*create lookup type new column called "Lookup Column"
    Here I am going to get the information from the "Title"
    column of a list called "LookUp List"
   * /
    SPList lookupList = web.Lists["LookUp List"];
    newList.Fields.AddLookup("Lookup Column", lookupList.ID, false);
    SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Lookup Column"];
    lkp.LookupField = targetList.Fields["Title"].InternalName;
    lkp.Update();

    //make new column visible in default view
    SPView view = list.DefaultView;
    view.ViewFields.Add("Name");
    view.ViewFields.Add("Lookup Column ");
    view.Update();
}

Thursday, December 1, 2011

Custom Error Page

With 2007, you can cancel events and return an error message to the user, but that provides limited interactivity  and not much help to the user beyond what your error message says. With 2010 events, you can cancel the event on your synchronous events and redirect the user to a custom error page that you create. The custom error pages and redirection will only work for pre-synchronous events,so you cannot do this for post-synchronous events such as ListAdded.


The way to implement custom error pages is to set the status property on your property bag for your event receiver to SPEventReceiverStatus.CancelWithRedirectedUrl, set the RedirectUrl property to a relative URL for your error page, and set the cancel property to true.


      properties.Cancel = true;
      properties.Status = SPEventReceiverStatus.CancelWithRedirectedUrl;
      properties.RedirectUrl = "/_layouts/mycustomerror.aspx";

Create a User Profile Using the Object Model


public void CreateUserProfile()
{
//We have to get the Context of the service application
strUrl = "http://site";
SPSite spSite = new SPSite(strUrl);
        ServerContext siteContext = ServerContext.GetContext(spSite);
        
       //UserProfileManager class contains member for profiles
       UserProfileManager upManager = new UserProfileManager(siteContext);       
       string strUserName = "domain\\user";
       if (!upManager.UserExists(strUserName ))
       upManager.CreateUserProfile(strUserName);
}