Thursday, May 20, 2010

How to add webpart programmatically in SharePoint webpart page

Adding webpart programmatically in SharePoint webpart page

There are two scenarios:
1. you add a web part that is displaying data for a list, which is called List View Webpart. List view webpart will be created automatically when you create a list.

Here is the code to achieve that.

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Contacts"];

// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();

// Get the web part collection
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);

// Add the web part
coll.Add(wp);

2. you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The




// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();

// Get the web part collection
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);
string dwp = @" Left SmartPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=dd064a5b12b5277a SmartPart.UserControlWebpart ~\UserControls";

coll.Add(dwp);

The first section is the same, get a reference to your site and the WebPartCollection (you don’t need a reference to a list). Next you need to build a XML string containing the information about the web part you want to add. The contents of that string are the same as the DWP file that you need to create to use your custom web parts. A trick to figure out what needs to be in there (especially if you want to specify values for some properties) is to put the web part on a page (using the web interface), and choose “Export” from the dropdown menu of the web part. This will save the contents of the DWP in a file. Finally you can add the web part by calling the Add method of the WebPartCollection and using the dwp string as a parameter.

Tuesday, May 18, 2010

Creating a SharePoint List programmatically using the object model

Creating a SharePoint List programmatically using the object model

There are two ways to create a SharePoint list programmatically

1. Creating a List programmatically by using out of the box List Template Types, there are many OOTB list templates are available in the SharePoint, list of some of them is geven below.
You can create a list by picking one of the List Template Types available in the SPListTemplateType object

SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", SPListTemplateType.GenericList);
SPList list = web.Lists[listId];
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();

OOTB List Templates


Events
Contacts
Tasks
PictureLibrary
DiscussionBoard
Survey
DocumentLibrary
Links
Document Library
Announcements
GenericList
WorkflowHistory
DataConnectionLibrary
DataSources
GanttTasks
CustomGrid
NoCodeWorkflows
XMLForm
WebPageLibrary
WorkflowProcess
Form Library
wiki
Wiki Page Library
Picture Library
Picture
Contacts
Calendar
Discussion Board
Project Tasks
Issue Tracking
Custom List
Custom List in Datasheet View
Survey Survey
Custom Workflow Process
Languages and Translators
Translation Management Library
DataSources
Data Connection Library
Workflow History
No Code Workflows




2. Creating a List programmatically with Custom List Template Types
If you have created your own custom list template, you will need to reference the id by enumerating what List Template Types are available at the Site Collection.


SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;

SPListTemplateCollection listTemplates = site.GetCustomListTemplates(mySite);
SPListTemplate template = listTemplates["Enter template name here"];
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", template);
SPList list = web.Lists[listId];

web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();


There are some otherways also like using Feature etc to create a sharepoint list, which I am going to explain it in my next post.

Thanks
Sanjay Tiwari
Dallas, Texas

Thursday, May 13, 2010

how to Add a Web Part to SharePoint Page Dynamically

THere will be two steps involved in adding an existing webpart to an existing webpart page.
1. Get the webpart from the webpart gallery.
2. Then add it to the page into the target web part zone.
All manipulations with a web part on a page are governed by the SPLimitedWebPartManager class, which is a scaled down version of SPWebPartManager class.

public string AddWebPartToPage(
SPWeb web,
string pageUrl,
string webPartName,
string zoneID,
int zoneIndex)
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart =
CreateWebPart(web, webPartName))
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
manager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
}
}

The CreateWebPart() method first constructs a CAML query, which will look up the web part in a web part gallery. Certainly this means that for the method to work the web part must already be in the web part gallery


private System.Web.UI.WebControls.WebParts.WebPart
CreateWebPart(SPWeb web, string webPartName)
{
SPQuery query = new SPQuery();
query.Query = String.Format(
"{0}",
webPartName);

SPList webPartGallery = null;

if (null == web.ParentWeb)
{
// This is the root web.
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
// This is a sub-web.
webPartGallery = web.ParentWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}

SPListItemCollection webParts = webPartGallery.GetItems(query);

string typeName = webParts[0].GetFormattedValue("WebPartTypeName");
string assemblyName = webParts[0].GetFormattedValue("WebPartAssembly");
ObjectHandle webPartHandle = Activator.CreateInstance(
assemblyName, typeName);

System.Web.UI.WebControls.WebParts.WebPart webPart =
(System.Web.UI.WebControls.WebParts.WebPart)webPartHandle.Unwrap();
return webPart;
}

Thursday, May 6, 2010

How to use elevated priviledge in Sharepoint/how to Impersonate a user in the code.

There are actually many ways to acieve that, I am going to explain two of them here.


1. Using RunWithElevatedPrivileges of SPSecurity class.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.

The premise is that you wrap the RunWithElevatedPrivileges method around your code. And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.



//Using RunWithElevatedPrivileges. code written in this section will run with higher priviledges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb(myWeb.ID))
{
web.AllowUnsafeUpdates = true;
//Write the code here to do the operation.
web.AllowUnsafeUpdates = false;

}
}
}

Another way to use this method is , define a public method that acts simply as a front end to the method that does the "real" work.

public void ProcessMethod()
{
SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated( ProcessMethodAsElevated);
SPSecurity.RunWithElevatedPrivileges(elevatedMethod);
}

The code uses a method from SPSecurity to indicate the name of the method that will run with Full Control(Basically using Application Pool Account).
In the first line, simply pass in the name of the method as the parameter. In the second line, you execute that method with elevated privileges.

Now create the method that does the real work. It is called by the first method (delegate), but executes with Full Control(under Application Pool Account):
private void ProcessMethodAsElevated()
{

//code goes here to do our work

}


2. Using windows impersonation.

Using this you want to run some code under the context of another user, you will need to hook into advapi32.dll library. following libraries are to be included

using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;


Then you need to declare an external reference at class level.

[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static public extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, ref IntPtr accessToken);


using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Data.SqlClient;

class TestClass
{

private const int LOGON_TYPE_INTERACTIVE = 2;
private const int LOGON_TYPE_PROVIDER_DEFAULT = 0;

[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static public extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, ref IntPtr accessToken);
static void ImpersonationCode()
{
IntPtr accessToken = IntPtr.Zero;
if (LogonUser("userName", "domain", "password", LOGON_TYPE_INTERACTIVE, LOGON_TYPE_PROVIDER_DEFAULT, ref accessToken))
{
using (WindowsIdentity identity = new WindowsIdentity(accessToken))
{
using (WindowsImpersonationContext context = identity.Impersonate())
{
// ... Write your code to implement logic here
context.Undo();
}
}
}

}

Now there is very important point, if you are doing any operation like adding a new item into library, it will leave the signature of system account and not the logged in current user. Now you may want to run the code in elevated priviledge but want to keep signature of current logged in user....coming in my next post.

Sanjay Tiwari
Dallas, Texas