Sunday, December 19, 2010

Getting Data from Subsites to TopSite with Null Checking.



using System;
using System.Web.UI;

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using Microsoft.SharePoint;
using System.Data;
namespace TestSampleCode001.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
string Title = string.Empty;
string Status = string.Empty;
string AssignedTo = string.Empty;
string WebTitle = string.Empty;
var query = from SPWeb subWeb in
SPContext.Current.Web.GetSubwebsForCurrentUser()
from SPListItem item in
subWeb.Lists["Tasks"].Items
orderby item["ID"] descending
select new
{

Title=item["Title"].ToString(),
Status=(item["Status"]==null) ? "Data
UnAvailable" : item["Status"].ToString(),
Priority = (item["Priority"] == null)
? "Data UnAvailable" : item["Status"].ToString(),
AssignedTo = (item["AssignedTo"] ==
null) ? "Data UnAvailable" :
item["AssignedTo"].ToString().Substring(item["AssignedTo"].ToString().
LastIndexOf("\\") + 1),
WebTitle=subWeb.Title
};

if (query.Count() > 0)
{
sgvTest.DataSource = query;
sgvTest.DataBind();
}

}
catch (Exception ex)
{

this.Controls.Add(new LiteralControl(ex.ToString()));

}

}

}

}

Wednesday, December 1, 2010

Converting an ASP.NET site into a SharePoint site

Introduction

There are a lot of ASP.NET web developers who are moving to SharePoint site creation. This article will explain in detail how an ASP.NET webpage developed in Visual Studio can be converted into a SharePoint site. If there is a requirement for a website created in Visual Studio, just the old fashioned way with the code-behind logic and other layers like Data Access and Business Logic, to be converted into a SharePoint site, and still make it work the same way with the same code-behind, you are in the right place. This article deals with right that.

Scenario

There is an ASP.NET website solution that contains three layers viz. Code-Behind Layer, Business-Logic Layer, and the Data-Access Layer. The website has functionality implemented in all these layers. The Business-Logic and the Data-Access layers are in a different Class Library project. We have to convert this website into a SharePoint site. Also, we want to use the same look and feel of the SharePoint site. So, we have to use the SharePoint master page instead of the one that we are having (we can also use our own master page; just that you have to add some default Place Holders that are required for the SharePoint functionalities). In this article, we are dealing with a website with the same look and feel as a SharePoint site.

Steps Overview

There are three steps that are explained in the article which will help you to transform your ASP.NET Web Application into a SharePoint site.
Step1: Add a Web Deployment Project to your website solution that will create a single DLL for the website. This step will give us the code-behind DLL and other dependency DLLs for the website.
Step2: Copy the bin folder items (DLLs) into the SharePoint site, and tweak the web configuration file of the SharePoint site to use the copied DLLs.
Step3: Open your created SharePoint site in SharePoint Designer and import the web pages from our web application and link it to the appropriate DLLs.

Step 1: Adding a web deployment project to your website solution that will create a single DLL for the website

  1. The first step is to make sure you have added the proper namespaces and avoided class name duplications within a namespace before going to step 2.
  2. Add a web deployment project into your website solution. This can be done by right clicking on the website project and choosing 'Add Web Deployment Project' option.
  3. Note: This option will be available once you have installed the Web Deployment Setup.
  4. Add a strong name key to the solution which we will be using to sign all the DLLs.
  5. Now, we have to set the deployment project properties. Right-click on the deployment project and click 'Property Pages'.
  6. Go to the 'Output Assemblies' tab, and choose the 'Merge all assemblies to single assembly' option (this is the default option), and give the assembly name.


  1. Next, go to the Signing tab and choose the 'Enable strong naming' option, and choose the strong name key that you have created in step 3.


  1. Also check the option 'Mark the assemblies with AllowPartiallyTrustedCallersAttribute (APTCA)'. This will make the DLL partially trusted, and thus the SharePoint site can use them. Click on OK.
  2. The Data Access, Business Logic, or any other assemblies that are a dependency to the web application must be strong named with a strong name key.


  1. Also, we have to allow partially trusted callers for the dependency DLLs. This can be done by opening the Assembly.info file of the Class Library project and putting the following line of code as shown above:
  2. Collapse
    [assembly: System.Security.AllowPartiallyTrustedCallers]
  3. Build the deployment project under Release mode (any mode).
  4. Go to the path where the deployment project has put the output. Here, in the bin directory, you will find the web deployment DLL file. If there are any dependency projects such as the Business Layer and the Data-Access Layer, those DLLs also will be copied to this bin folder.
Now, we have the DLLs that can be used in our SharePoint site for using the same functionality as in our ASP.NET site.

Step 2: Copy the bin folder items (DLLs) into the SharePoint site and tweak the web configuration file of the SharePoint site to use the copied DLLs

The next step in our SharePoint site creation is linking the DLLs that we have created in the procedure above into our already existing blank SharePoint site. There are also some changes that are required in our SharePoint site's web.config file (By default found in C:\Inetpub\wwwroot\wss\VirtualDirectories\<PortNo>). Following are the steps that has to be done:
  1. Copy the bin folder contents from your ASP.NET deployment folder into the bin folder of your SharePoint site (usually in C:\Inetpub\wwwroot\wss\VirtualDirectories\<PortNo>\bin).
  2. Open the web.config file of your SharePoint site.
  3. Add the following line in under the <PageParserPath> section:
  4. Collapse
    <PageParserPath VirtualPath="/*" CompilationMode="Always" 
       AllowServerSideScript="true" IncludeSubFolders="true" />
  5. Register the assemblies that will be used in the SharePoint site (web deployment DLL which has the code-behind code, the Business Layer and Data Access DLLs) as a SafeControl. For this, add the following under the <SafeControls> section:
  6. Collapse
    <SafeControl Assembly="SampleWebSiteAssembly" 
       Namespace="SampleSiteNamespace" TypeName="*" Safe="True" />
  7. Also add all the other dependency DLLs that your site will be using. Note that all these DLLs must be strong named and marked AllowPartiallyTrusted.
  8. Change the trust level from Minimal to Medium by changing the level attribute of the <trust> section from 'WSS_Minimal' to 'WSS_Medium'.
  9. Note: You can also do the following to enable the original errors being shown in the SharePoint site screen for easy error identification. You have to change the mode attribute of the <customErrors> section to Off. Also, change the CallStack attribute of the <SafeMode> section to True.

Step 3: Open your created SharePoint site in SharePoint Designer and import the web pages from our web application

Let us say we have a link in our SharePoint site in the left navigation panel, on the click of which you want to display one of your ASP.NET pages in the content place holder of the SharePoint site. This is what we do:
  1. Open your SharePoint site in the SharePoint Designer (in this article, we are using SharePoint Designer 2007).
  2. Click on File-->Import-->File. This will open the Import dialog box.
  3. Click on 'Add File' and choose the ASPX page that you have created from your local folder. Please note that you have to take the ASPX file from the deployment folder and not the ASPX page that is there in the project. Click OK. This will import the page into your SharePoint site.
  4. Now, double-click on the newly imported page. Click on the Split option in the Design/Split/Code option in the centre pane (bottom left of the pane).
  5. As soon as you do this, you will see in the designer window an error that says: The Master Page file cannot be loaded. This is because the master file that we have used in the project is different from the master page that the SharePoint site uses. You can either import the master page or use SharePoint's default master page. In this article, we are going to use SharePoint's default master page.
  6. Change the 'MasterPageFile' attribute in the Page directive of the web page to a value same as the default.aspx in the SharePoint site, which is ~masterurl/default.master.
  7. Delete the 'CodeFile' attribute from the Page directive as this is only for Visual Studio purposes.
  8. Now, change the ContentPlaceHolderID of the place holders in the ASP.NET page to a relevant SharePoint site place holder. For example, the ContenPlaceHolderID of the main content place holder of the ASP.NET page must be changed to 'PlaceHolderMain'.
  9. After mapping the place holders of the ASP.NET page to that of the SharePoint master page, the page will render in the design view with the default master page.
  10. Now, we have to change the Inherits attribute to add the assembly name. For example, if the namespace is 'SampleSiteNamespace' and the assembly name that the page uses for code-behind is SampleWebSiteAssembly, then we set Inherits="SampleSiteNamespace.SampleWebSiteAssembly", and this assembly must be in the bin of the SharePoint site as added in Step 2 above.
Now, we have our ASP.NET site as a SharePoint site, ready to run with the same look and feel of the SharePoint site.

  

    

Usefull Links

 http://blogs.msdn.com/b/kaevans/archive/2010/07/09/sql-server-provider-for-claims-based-authentication-in-sharepoint-2010.aspx


 http://blogs.msdn.com/b/kaevans/archive/2011/04/02/code-behind-page-layouts-with-visual-studio-2010.aspx


http://blogs.msdn.com/b/kaevans/archive/2010/06/25/enable-javascript-intellisense-for-sharepoint-development.aspx

http://praveenbattula.blogspot.com/

http://www.codeproject.com/KB/sharepoint/ASPNET_to_Sharepoint.aspx

Deleting all library items in a document library.

  1. private static void DeleteAllItemsUsingBatch()  
  2.         {  
  3.             using (SPSite site = new SPSite("http://mysharepointserver"))  
  4.             {  
  5.                 SPWeb web = site.OpenWeb("/");  
  6.                 SPList list = web.Lists["Documents"];  
  7.                 StringBuilder sb = new StringBuilder();  
  8.                 sb.Append("<batch>");  
  9.                 string batchCommand = "<method><setlist scope=\"Request\">" + list.ID + "</setlist><setvar name=\"ID\">{0}</setvar><setvar name=\"Cmd\">DELETE</setvar><setvar name=\"owsfileref\">{1}</setvar></method>";  
  10.                 foreach (SPListItem item in list.Items)  
  11.                 {  
  12.                     sb.AppendFormat(batchCommand, item.ID.ToString(), item.File.ServerRelativeUrl);  
  13.                 }  
  14.                 sb.Append("</batch>");  
  15.   
  16.                 web.AllowUnsafeUpdates = true;  
  17.                 site.RootWeb.ProcessBatchData(sb.ToString());  
  18.                 web.AllowUnsafeUpdates = false;  
  19.                 web.Close();  
  20.             }  
  21.         } 

To delete all the list items in a SharePoint list

  1. private void DeleteAllItemsUsingBatch()  
  2.     {  
  3.         using (SPSite site = new SPSite("http://mySharePointServer"))  
  4.         {  
  5.             SPWeb web = site.OpenWeb("/");  
  6.             SPList list = web.Lists["Links"];  
  7.             StringBuilder sb = new StringBuilder();  
  8.             sb.Append("<batch>");  
  9.             string batchCommand = "<method><setlist scope=\"Request\">" + list.ID + "</setlist><setvar name=\"ID\">{0}</setvar><setvar name=\"Cmd\">DELETE</setvar></method>";  
  10.             foreach (SPListItem item in list.Items)  
  11.             {  
  12.                 sb.Append(string.Format(batchCommand, item.ID.ToString()));  
  13.             }  
  14.             sb.Append("</batch>");  
  15.             web.AllowUnsafeUpdates = true;  
  16.             site.RootWeb.ProcessBatchData(sb.ToString());  
  17.             web.AllowUnsafeUpdates = false;  
  18.             web.Close();  
  19.         }  
  20.     } 

Tuesday, October 26, 2010

SharePoint 2010 IQ1

Q. How does Ribbon works ?

Ans. A file called CMDUI.XML stays at the web front end which contains the Out-of-Box site wide Ribbon implementation i.e. all the Ribbon UI for the entire site. In addition to this you have a CustomAction for each ribbon component. These CustomActions have CommandUIExtentions block which has CommandUIDefinitions and CommandUIHandlers which make up the activity of the ribbon component. So, when the ribbon is loaded the CommandUIDefinition merges with Out-of-Box definition in the CMDUI.XML

Q. How will you use WebParts or other solutions Created in SharePoint 2007 in SharePoint
2010 ?


Ans. In SharePoint 2010 the 12 hive is now replaced by 14 hive, So we will rewrite and recompile any code that refers to files and resources in “12″ hive. In addition to we must recompile custom code written for Windows SharePoint Services 3.0 and Office SharePoint Server 2007 that does not run on IIS.

Q. What is the advantage in using Windows PowerShell over stsadm in SharePoint 2010 ?

Ans. Unlike stsadm, which accept and return text, Windows PowerShell is built on the Microsoft .NET Framework and accepts and returns .NET Framework objects.Windows PowerShell also gives you access to the file system on the computer and enables you to access other data stores,
such as the registry and the digital signature certificate stores etc..

Q. What is REST ? How is it used in SharePoint 2010 ?

Ans. REST (Representational State transfer) is a protocol (powered by ADO.NET services) which is used for getting data out of sharepoint via Url. It is mostly used to access data from sharepoint even when you are not in the sharepoint context.

Q. What datatype is retured by REST ?

Ans. REST does not return an object of type SharePoint Site\List. Instead, it returns an XML output.

SharePoint 2010 IQ For Developers

Q. What has Changed in SharePoint 2010 Object model?

Ans. Microsoft has replaced the "12 hive" structure that we had in SharePoint 2007 with "14 Hive" structure in 2010.

It has apparently added three new folders to its hive.

The Folders are :

* UserCode – files used to support sandboxed solutions
* WebClients – used for the client Object Model
* WebServices – New .svc files

Q. How would you deploy WebPart Using Windows PowerShell?

Ans. At the Windows PowerShell command prompt (PS C:\>), type the below
command :
Install -SPWebPartPack -LiteralPath "FullPathofCabFile" -Name "Nameof WebPart"

Q. How would you re-deploy the old custom solutions in SharePoint 2010.What Changes are needed to the old Solution files.

Ans. SharePoint 2010 object model contains many changes and enhancements, but our custom code will still compile and, will run as expected. You should however, rewrite and recompile any code that refers to files and resources in "12 hive". For Details See : SharePoint Object Model – Backward Compatibility

Q. How would you add a link in the Ribbon?

Ans. You can add any link or Custom Action under any of the existing tabs of the ribbon or can create a new a new tab and place your links under it.

Q. What does CMDUI.XML contain?

Ans. The definitions for the out-of-the-box ribbon elements are split across several
files in the SharePoint root, with TEMPLATE\GLOBAL\XML\CMDUI.XML being the
main one.

Q. What are the Disadvantages of Using LINQ in your Code?

Ans. LINQ translates the LINQ queries into Collaborative Application Markup
Language (CAML) queries thus adding an extra step for retrieving the items.

Q. What is different with SharePoint 2010 workflows ?

Ans. Some of the additions in workflow model are :

1. SharePoint 2010 workflows are build upon the the workflow engine provide .Net Framework 3.5.

2. In addition to the SharePoint lists we can now create workflows for SharePoint sites as well.

3. SharePoint Designer 2010 also has a new graphical workflow designer for designing workflows and deploying them directly to SharePoint.

4. Another Improvement in SharePoint Designer 2010 is that it now allows you to edit the out-of-the-box workflows that come with SharePoint.

SharePoint 2010 Object Model Backward Compatibility

SharePoint 2010 Object Model Backward Compatibility

Some Important things about SharePoint 2010 Object model and its backward compatibility.

Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010 contain object model upgrades that are designed to be compatible with existing solutions developed for Windows SharePoint Services 3.0 and Microsoft Office SharePoint Server 2007. Some namespaces, classes, and methods are now obsolete, but they are still available and will continue to work as expected in your custom code.

You can synchronize your customizations and applications with the upgraded versions of Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010 after you have redeployed them.

The object model contains many changes and enhancements, but your custom code will still compile and, with one potential exception, it will run as expected. If in case, any of your customizations rely on list queries that can generate result sets in excess of 5,000 items or that scan all rows of lists that consist of more than 5,000 items, you must change the query size threshold.(See Later in the Post)..

Note: You must Re-compile or re-write your code in below conditions:

* You should rewrite and recompile any code that refers to files and resources in "12" hive.For example, if you have redeployed all of your files into the "14" folder and emptied your "12" folder, any references to files
under the "12" folder will not work. You will need to rewrite your code to refer the files in "14 Hive" instead of "12 Hive" to make it work.

* You must recompile custom code written for Windows SharePoint Services 3.0 and Office SharePoint Server 2007 that does not run on IIS (such as console applications and services).

* You should recompile custom code written for Office SharePoint Server 2007 if your solution includes a feature receiver that implements the FeatureInstalled, FeatureUninstalling, FeatureActivated, or Feature Deactivating methods and you are deploying by using either the Stsadm command-line tool or the timer service.

Lets Look at some of the custom solutions that you would be moving to SharePoint 2010.

Moving Using Solution Packages (.wsp Files)

You can simply deploy them as we did in SharePoint 2007. You dont need to recompile them(unless, your code has references to 12 hive). If however, you want to start upgrading your applications so that they use the most current classes and methods, you should recompile your code. The compiler warnings will tell you which elements of the object model are obsolete, andwhich newer alternatives you should use.

Moving Using Windows Installer Files

If you deploy your custom solutions by using Windows Installer (.msi) packages, be sure to change them so that your custom files are deployed to their correct locations in the "14" folder. This is especially true if you are
deploying files to locations other than the TEMPLATE\FEATURES folder.

Moving Site templates

Site templates are deprecated. If you need to redeploy a site template to either SharePoint Foundation 2010 or SharePoint Server 2010, follow these steps:

1. Create a site from the site template.

2. Install SharePoint Foundation 2010 or SharePoint Server 2010 on your existing server farm or on a new server farm. If you install the upgrades on a new server farm, attach the content database that contains the site that you created to the new farm.

3. On the new installation, choose Save Site as Template from the Site Settings page. This creates a solution package with a .wsp file name extension.

CSS Changes

When you upgrade to either SharePoint Foundation 2010 or SharePoint Server 2010, you are able to choose either backward compatibility mode or the upgraded user interface. You can however, switch between backward compatibility mode and the new interface at the site-collection level or site level.

Since, the UI has changed significantly in both SharePoint Foundation 2010 and SharePoint Server 2010, any customizations(made to SharePoint 2007 CSS) that rely on specific CSS classes and UI elements will work only in backward compatibility mode.

A property SPWeb.UIVersion is also available for developers, to programmatically get or set the UI version (3 for backward compatibility mode and 4 for the new interface).

Themes:

Themes no longer exist in SharePoint Foundation 2010 and SharePoint Server 2010, so any customizations and design work that you have done with themes will not be imported into the new interface.

Custom Actions and Toolbar Additions:

Most custom actions, including those targeted at links and edit control block (ECB) menus, continue to work as expected in the upgraded interface. Because the toolbar is replaced by the ribbon, most custom actions that add buttons to a toolbar will be placed in the Custom Commands tab of the ribbon.
Note : Any Custom Action Element that uses the ControlAssembly attribute,the ControlClass attribute, or the ControlSrc attribute, however, will not appear in the new interface.

Site definition :
 
Migrate sites to a supported, predefined site definition, then apply custom features by using solution deployment. You can also continue to use a custom site definition. You do not have to create a new site definition based on SharePoint Server 2010.

Event handler : Rewrite and redeploy as a feature.

JavaScript : In some cases, you might have to adjust the scripts to work with the new page model. Verify that it works on an upgraded site, and in both Visual Upgrade modes.

Conclusion:

Because the changes to the API in the upgrades are backward compatible, you should not have to make any changes to your custom code before you redeploy it in either SharePoint Foundation 2010 or SharePoint Server 2010. All deprecated elements of the API continue to be available to you, so that you have time to review the newer elements of the API before incorporating them into your customizations.

Monday, October 25, 2010

SharePoint 2010 Workflows

SharePoint 2010 Workflows

A quick view on whats new with SharePoint 2010 Workflows :

1. SharePoint 2010 workflows are build upon the workflow engine provided .Net
Framework 3.5.

2. List and Site workflows - In addition to the SharePoint lists we can now create
workflows for SharePoint sites as well. These are called as "Site Workflows".

3. SharePoint Designer 2010 Changes - MS has provided a new graphical workflow
designer for designing workflows. These workflows can be deployed in SharePoint
Server directly from the designer.

4. Editing Out-of-Box workflows - Another Improvement in SharePoint Designer
2010 workflows is that it now allows you to edit the out-of-the-box workflows that
come with SharePoint.

5. Re-usable Workflow - In addition to above, with Designer 2010 you can also
create reusable declarative workflows. That means unlike SharePoint 2007 designer
workflows, you don't have to bind a workflow to a specific list. You can resuse them
by binding it to more than one list or multiple lists.

6. User profile in Workflow - User Profile data can now be bound to properties in
workflow. This will make it possible to get information about the SharePoint user
profile in the workflow itself.

7. Moving SharePoint Designer Workflows - The resuable designer workflows can
now be moved to another SharePoint server or to Visual Studio 2010 with a
workflow .wsp file. "Save as Template" command can be used to create the WSP
file for the workflow.

8.Changes in List Events - SharePoint 2010 adds four new workflow Event
Receivers for list based workflows. The four workflow event receivers available are
Starting, Started, Postponed and Completed. These are similar to other SharePoint
list\library event receivers and they execute code on the server in response to the
event.

9. Workflow Templates - To make development easier, Visual Studio 2010 includes
event receiver project types to make using the workflows and events fairly simple.

Now to Start developing workflows what do you need.

1. SharePoint designer - If you need to customize the Out-of-box workflow or wants
to create a "not so complex" reusable workflow. You can however, deploy your
designer workflow in any sharepoint enviornment using a wsp file. See Move
Designer workflow using wsp

2. Microsoft Visio - If you want to design a workflow which has complex workflow
chart, you can design it in Viso and later it can be pulled in to SharePoint designer.
Also, note that you can only create Sequential workflows in viso.

3. Creating Worflow in VS - Visual Studio 2010 provides templates to create
workflows and creates events for the workflow.

Lets look at some of the Videos available for creating workflows using all above
methods.

Create a User Group using Client Object Model

//get the connection

ClientContext ctx = new ClientContext(“http://SPSite”);

//create the group

GroupCreationInformation grp = new GroupCreationInformation();

grp .Title = “Your New Group”;

grp .Description = “This is a custom group created using the client object model”;

//add it to the list of site groups

Group newgrp = ctx.Web.SiteGroups.Add(grp);

//Get a role.

RoleDefinition rd = ctx.Web.RoleDefinitions.GetByName(“Permission level Name”); // – > To
Create a Custom Role definition or Permission level see my post Here

//create the role definition binding collection

RoleDefinitionBindingCollection rdb = new RoleDefinitionBindingCollection(ctx);

//add the role definition to the collection

rdb.Add(rd);

//create a RoleAssigment with the group and role definition

ctx.Web.RoleAssignments.Add(grp, rdb);

//execute the query to add everything

ctx.ExecuteQuery();

Create Custom Permission level using Client Object model

Create Custom Permission level using Client Object model –

ClientContext ctx = new ClientContext(“SPSiteurl”);

//create a new base permission

BasePermissions perms = new BasePermissions();

var _basePerm = | SPBasePermissions.AddListItems| SPBasePermissions.EditListItems;

perms.Set((PermissionKind)Enum.Parse(typeof(PermissionKind), _basePerm));

//create the construct for a new role definition

RoleDefinitionCreationInformation rdInfo = new RoleDefinitionCreationInformation();

//set the perms

rdInfo.BasePermissions = perms;

//set a descriptionrdInfo.Description = “Custom Role definition created with the client object
model”;

//set the name

rdInfo.Name = “My custom Permission level”;

//add the definition to the web collection

RoleDefinition rd = ctx.Web.RoleDefinitions.Add(rdInfo);

//execute to create

ctx.ExecuteQuery();

Now Assign a user this custom role definition –

/get the group

RoleDefinition rd = ctx.Web.RoleDefinitions.GetByName(“My custom Permission level”);

//get the user object

Principal usr = ctx.Web.EnsureUser(“domain\isha”);

//create the role definition binding collection

RoleDefinitionBindingCollection rdb = new RoleDefinitionBindingCollection(ctx);

//add the role definition to the collection

rdb.Add(rd);

//create a RoleAssigment with the user and role definition

ctx.Web.RoleAssignments.Add(usr, rdb);

Creating DashBoards Using SharePoint 2010

Creating DashBoards Using SharePoint 2010.

To create a dashboards in SharePoint 2010, you would use the newly integrated part of the SharePoint Server 2010 Enterprise called PerformancePoint. PerformancePoint Services is a performance management service that you can use to monitor and analyze your business or you can say that, PerformancePoint Services is Microsoft’s dashboard delivery tool, which now is part of the SharePoint Server 2010 Enterprise platform. PerformancePoint Services enables you to create rich, context-driven dashboards that aggregate data and content to provide a complete view of how your business is performing at all levels.

What will PerformancePoint give me?

It provides you with flexible and easy-to-use tools for building Key Performance Indicators (KPIs), Scorecards, Analytic Charts and Grids, Reports, Filters and Dashboards.Each of these components are unique to PerformancePoint Services and provide functionality that interacts with a server component that handles the hard parts like data connectivity and security.

What is PerformancePoint Services as a service application -

As you know that In SharePoint Server 2010 services are no longer contained within a Shared Service Provider (SSP) instead you can create a service application for each service and can share them with various existing web applications. To understand better, PerformancePoint Services will be one of the Service that will stay in the application server with a database something like “PerformancePoint Services Service database” in the Sql server box.

What is Secure Store Service: – This service application stores the password for the
PerformancePoint Services unattended account.

What are the Features of PerformancePoint Services

* With PerformancePoint Services, the dashboards and dashboard items are stored and secured within SharePoint lists and libraries, providing you with a single security and repository framework. The new architecture also takes advantage of SharePoint Server scalability, collaboration, backup and recovery, and disaster recovery capabilities.

* The Decomposition Tree is a new visualization report type available in PerformancePoint Services. You can use it to quickly and visually break down higher-level data values from a multi-dimensional data set to understand the driving forces behind those values. The Decomposition Tree is available in scorecards and analytic reports and ultimately in dashboards.

* You can access more detailed business information with improved scorecards. Scorecards have been enhanced to make it easy for you to drill down and quickly access more detailed information. PerformancePoint scorecards also offer more flexible layout options, dynamic hierarchies, and calculated KPI features.

* Better Time Intelligence filtering capabilities that you can use to create and use dynamic time filters that are always up to date. Other improved filters improve the ability for dashboard users to quickly focus in on information that is most relevant.

* Ability to include and link PerformancePoint Services Web Parts together with other PerformancePoint Services Web parts on the same page.

* Easier to author and publish dashboard items by using Dashboard Designer.

* The KPI Details report is a new report type that displays contextually relevant information about KPIs, metrics, rows, columns, and cells within a scorecard. The KPI Details report works as a Web part that links to a scorecard or individual KPI to show relevant metadata to the end user in SharePoint Server.

* Create analytics reports to better understand underlying business forces behind the results. Analytic reports have been enhanced to support value filtering, new chart types, and server-based conditional formatting.

What is this Dashboard Designer ?

PerformancePoint Dashboard Designer is the design tool you will use to build key performance indicators (KPIs), indicators, scorecards, reports, filters, data sources, and dashboards. It also enables you to deploy your finished dashboards to SharePoint.

Prerequisites for creating dashboards

1. Activate the SharePoint Server Publishing Infrastructure feature. PerformancePoint Services uses this feature to perform dashboard publishing.

2. Activate PerformancePoint Services Site Collection Features feature. This feature adds PerformancePoint content types and a Business Intelligence Center site template.

3. Activate the SharePoint Server Enterprise Site Collection Features feature. This feature  enables Excel Services, Visio Services, and Access Services, included in the SharePoint Server Enterprise License.

4. Create a new Business Intelligence Center site by clicking Site Actions ➪ New Site, and then choose Business Intelligence template.

5. Create an Unattended Service Account.

In PerformancePoint Services, you create the unattended account directly in the PerformancePoint Services application settings. In this case, the password is stored in Secure Store Service and the actual username is stored in the PerformancePoint Services database.

An unattended account can be created using the following steps:
1. Browse to the Central Administration Site.
2. From the Application Management category, choose Manage service applications.
3. From the list of existing service applications, click PerformancePoint Service Application.
4. Click the PerformancePoint Service Application Settings link.
5. Specify the unattended service account for PerformancePoint and click OK.


To get started Open the Dashboard Designer. To do this follow the Steps below

1. In Internet Explorer, navigate to the Business Intelligence Center site that you must have created.
2. Click the Create Dashboards link, and then click Start using PerformancePoint Service link.
3. From the PerformancePoint Services page, click the big button that says Run Dashboard Designer. This will download and install the PerformancePoint Dashboard Designer to your workstation.  Once the executable fi le is downloaded and installed on your computer, the PerformancePoint Dashboard Designer appears. Once the Dashboard Designer is installed, you have an empty workspace. A workspace is a primary container for all of the elements that you can use to build your dashboard, and it keeps its content synched  with the site from which it was launched.

Creating Your Dashboard

Before we get started with building a dashboad lets just create a Dashboard Datasource first.

To create a Dashboard Datasource follow the below steps :

1. Right – click the Data Connections folder in the Workspace Browser, and then select New ➪
Data Source.
2. From the Select a Data Source Template menu, choose the Analysis Services template to create a datasource that connects to Microsoft SQL Server Analysis Services, and click OK. Next Configure the Connection Settings.
3. Watch for Cache Lifetime setting. The value of this textbox (in minutes) indicates the interval
of refreshing the dashboard information from the backend datasource.
4. Click Test Data Source to make sure that your connection settings are correct.
5. Switch to the Properties tab and change the Name of your datasource.

6. Save the new datasource by right – clicking it in the Workspace Browser, and then selecting
Save.

Creating KPI

Now that we have our connection ready lets create our key performance indicator (KPI). In order to create a new KPI to track what ever you wanna track for your company, you need to follow these steps:

1. Right – click the PerformancePoint Content folder and select New ➪ KPI.
2. In the Select a KPI Template dialog, select Blank KPI, and then click OK.
3. And once you have your KPI created, you can define your actual and Target values. Also,
select the data source and the measure.
4. Click OK to close the dialog.
5. Select the Target row, and click the Set Scoring Pattern and Indicator button in the Thresholds area.
6. Next, In the Edit Binding Settings dialog, select the fi rst option (Band by normalized value of Actual/Target) from the Banding method drop – down, and then click Next.
7. In the Select an Indicator step, select an indicator to use for the target that clearly shows
whether the goal is met. You can choose from a collection of indicator templates available in
PerformancePoint Dashboard Designer. Once you are done, click Next.
8. In the last step of the wizard, leave the value intact and click Finish.
9. Save the KPI by right – clicking it in the Workspace Browser, and then selecting Save.

Create Users and Add them to a Group using Client Object Model

Create Users and Add them to a Group using Client Object Model

//get the connection

ClientContext ctx = new ClientContext(“http://SPSite”);

//get the group

Group grp = ctx.Web.SiteGroups.GetById(GroupId); -> get group id ( See Post Get all users and
groups client object model sharepoint 2010

//create the user object
UserCreationInformation usr = new UserCreationInformation();

usr.LoginName = “Domain\isha”;

usr.Email = “ikapoo@Oursite.com”;

usr.Title = “Programmer”;

//add it to the group

grp.Users.Add(usr);

//execute the query to add the user

ctx.ExecuteQuery();

Powershell script for getting all the webparts in a SharePoint Page

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)

[System.Reflection.Assembly]::LoadWithPartialName(“System.Xml”)

$webApp=[Microsoft.SharePoint.Administration.SPWebApplication]::Lookup(“http://servernam
e”)

foreach($site in $webApp.Sites)

{

$web=$site.RootWeb

$file=$web.GetFile(“MyWebPartPage.aspx”)

if($file.Exists)

{

$wpManager=$web.GetLimitedWebPartManager(“Default.aspx”,[System.Web.UI.WebControls
.WebParts.PersonalizationScope]::Shared)

foreach($webPart in $wpManager.WebParts)

{

if($webPart.GetType().Name -eq “myContentEditorWebPart”) -> Getting my ContentEditor
WebPart.

{

$wp=[MicroSoft.SharePoint.WebPartPages.ContentEditorWebPart]$webPart
}
}
}
}

Programmatically adding documents to a document set using SharePoint 2010

Programmatically adding documents to a document set using SharePoint 2010.

In continuation with the previous post about how to create a document sets programmatically,
here i will post a little code snippet for adding a document to this document set that we just
created in our previous post.
For this example i am adding a file to our custom document set which already exists on
SharePoint server. You can however, use the file upload control to browse and add a file to your
docuemntset.

void addDocumentToDocuemntSet()
{

// Get the existing file
SPFile spfile = web.GetFile(“http://SPSite:8080/Lists/DemoLib/abc.txt”);

byte[] documentBytes = new byte[spfile.TotalLength];

if (spfile.Exists)
{
FileStream fs = new FileInfo(spfile.url).OpenRead()

fs.Read(documentBytes, 0, (int)fi.Length);

//add the default document to your document set template

newDocumentSetTemplate.DefaultDocuments.Add(spfile.Name,
web.ContentTypes["Document"].Id, documentBytes);

}

Programmatically Creating Document sets in sharepoint 2010

Programmatically Creating Document sets in sharepoint 2010.

You can create a document set using sharePoint object model, SharePoint Client OM and also
using SharePoint 2010 web services.

This example shows how to create document sets using SharePoint object model.

public static void CreateDocumentSetContentType(string libraryUrl)
{

using (SPSite site = new SPSite(libraryUrl))
{
using (SPWeb web = site.OpenWeb())
{

//create the new document set contenttype
SPContentType newDocumentSet = web.ContentTypes.Add (new
SPContentType(web.ContentTypes["Document Set"],web.ContentTypes,
“MydocumentSet”));

//get a an instance of DocumentSetTemplate for the new document set
DocumentSetTemplate newDocumentSetTemplate =
DocumentSetTemplate.GetDocumentSetTemplate(newDocumentSet );

//add allowable content types
newDocumentSetTemplate.AllowedContentTypes.Add
(web.ContentTypes["Document"].Id);

//add a shareable property
newDocumentSetTemplate.SharedFields.Add(newDocumentSetContentType.Fields["Module"]);

newDocumentSetTemplate.Update(true);
newDocumentSet .Update();
web.Update();
}
}
}

Programmatically get all users and groups using client object model

 Programmatically get all users and groups using client object model.

The code below shows you how to query users and groups using client object model. The client
OM includes the GroupCollection,Group,UserCollection,and User objects to make working with
users and groups easier.The client OM also has access to built – in groups such as the owners,
members, and visitors groups. You can
access these off your context object using the
AssociatedOwnerGroup,AssociatedMemberGroup,and AssociatedVisitorGroup properties,
which return a Group object.

function GetUsersGroups()
{

ClientContext context = new Microsoft.SharePoint.Client.ClientContext(“http://SPSite”);

GroupCollection groupCollection = context.Web.SiteGroups;
context.Load(groupCollection,
groups = > groups.Include(
group = > group.Users));

context.ExecuteQuery();

foreach (Group group in groupCollection)
{
UserCollection userCollection = group.Users;

foreach (User user in userCollection)
{
MessageBox.Show(“User Name: ” + user.Title + ” Email: ” +
user.Email + ” Login: ” + user.LoginName);
}
}
//Iterate the owners group
Group ownerGroup = context.Web.AssociatedOwnerGroup;
context.Load(ownerGroup);
context.Load(ownerGroup.Users);
context.ExecuteQuery();
foreach (User ownerUser in ownerGroup.Users)
{
MessageBox.Show(“User Name: ” + ownerUser.Title + ” Email: ” +
ownerUser.Email + ” Login: ” + ownerUser.LoginName);
}
context.Dispose();
}

Programmatically get permissions for all the users using client object model

Programmatically get permissions for all the users using client object model.

Firstly, to better understand about SPRoleDefinition and SPRoleAssignment read below.

SPRoleDefinition represents the levels such as “Full Control”, “Contribute”, while a Role
Assignment contains a collection of Role Definitions.
Any object that inherits from SPPrincipal can be assigned a SPRoleAssignment. For e.g. an
SPPrincipal such as a logged in user(SPUser type) called “isha”, can have a role assignment that
points you to two SPRoleDefinitions, “Full Control” and “Design”, thereby giving you a union
of SPBasePermissions between Full Control and Design.

Here is a simple code snippet to get SPRoleDefinitions for all the users in a site.

private static void GetUserRoles()
{
using (SPSite site = new SPSite(SPsiteUrl))
{

SPWeb web = site.OpenWeb();
Console.WriteLine(“\n\n Roles Assignments:”);

foreach (SPRoleAssignment roleA in web.RoleAssignments)
{
Console.WriteLine(“The following Role definition bindings exist for ” +
roleA.Member.Name);
foreach (SPRoleDefinition roledef in roleA.RoleDefinitionBindings)
{
Console.WriteLine(roledef.Name);
}
}
Console.ReadLine();
}
}

Search scopes for your search service application in SharePoint 2010

SearchServiceApplicationProxy;

// Service Application Info object to retrieve the application id for the search service.
SearchServiceApplicationInfo searchApplictionInfo =
searchApplicationProxy.GetSearchServiceApplicationInfo();

// Retrieve the search application instance for the specified id.
SearchServiceApplication searchApplication =
Microsoft.Office.Server.Search.Administration.SearchService.Service.SearchApplications.GetV
alue (searchApplictionInfo.SearchServiceApplicationId);

//get the current scopes defined in the search server
Scopes scopes = new Scopes(searchApplication);

Programmatically get permissions for list and listitems using client object model

Programmatically get permissions for list and listitems using client object model.

In this Post we have two code snippets, one for retrieving the Permissions on a specific list and
other for getting the Permissions on a specific Item using Client Object model.

Get Permissions for a List –

//get the Conext
ClientContext ctx = new ClientContext(“SPSiteUrl”);

//get the list
List myList = ctx.Web.Lists.GetByTitle(“My List”);

IEnumerable roles = null;
roles = ctx.LoadQuery(
myList.RoleAssignments.Include(

roleAsg => roleAsg.Member,

roleAsg => roleAsg.RoleDefinitionBindings.Include(

roleDef => roleDef.Name, // for each role def, include roleDef’s Name

roleDef => roleDef.Description)));

ctx.ExecuteQuery();

Retrieving permissions for a Specific item - The Code is similar to the above code but i am
using SecurableObject to hold the ListItem. Just to make things easy.

SecurableObject curObj = null;

ListItem curItem = ctx.Web.Lists.GetByTitle(“My List”).GetItemById(ItemId); -> Use ItemId of
the Item.

//plug it into our query object
curObj = curItem as SecurableObject;

IEnumerable roles = null;

roles = ctx.LoadQuery(

curObj.RoleAssignments.Include(

roleAsg => roleAsg.Member,

roleAsg => roleAsg.RoleDefinitionBindings.Include(

roleDef => roleDef.Name, // for each role def, include roleDef’s Name

roleDef => roleDef.Description)));

ctx.ExecuteQuery();

SharePoint_Permissions_Matrix

http://blogs.msdn.com/b/markarend/archive/2008/02/14/sharepoint-2007-permissions-matrix.aspx




Print current Page Sharepoint



To create the button, add a Content Editor Web part, select the source editor and put the follow code:

<script>
function printWindow(){
bV = parseInt(navigator.appVersion)
if (bV >= 4) window.print()
}
</script>
<img src="/imagens/print_ico.jpg" alt="Print This Page">
<a href="javascript:printWindow()">Print This Page</a>

SharePoint List Templates

When we are creating List using elemnts.xml and feature.xml, need to know what Template ID code to use.
here is a list can help you.

Template ID Description
100 Generic list
101 Document library
102 Survey
103 Links list
104 Announcements list
105 Contacts list
106 Events list
107 Tasks list
108 Discussion board
109 Picture library
110 Data Sources list
111 Site Template Gallery
113 Web Part Gallery
114 List Template Gallery
115 XML Form Library (InfoPath)
120 Custom grid for list
200 Meeting Series list
201 Meeting Agenda list
204 Meeting Decisions list
207 Meeting Objectives list
210 Meeting text box
211 “Things to Bring” Meeting list
212 Meeting Workspace Pages list
300 Portal Sites list
1100 Issue Tracking list
2002 Personal document library
2003 Private document library

What Is Sharepoint?

 Sharepoint is a website wherein team members can see documents and folders created by them on windows platform and are accessible over the web.

Features of Sharepoint
  • Collaboration – Collaboration means working together.  Sharepoint helps you to share information about project to team members through organise way.
  • Document Management – Document management helps you to manage documents in a structured way and allows you to share documents to authenticate users through the use of versioning, metadata, workflows, and search.
  • Portal – Portal provides interface through which you can able to access information and share information over the web.
Example of Document Management with Sharepoint:
Let say you have Business Requirement documents, which needs to be shared among group of team members, than sharepoint is smart choice.
  • Sharepoint allows to edit document, save document and even versioning of document.
  • Documents are accessible to authenticate users only.
  • You can also able to view who had previously edited this document including all required details such as date and time of editing document, what is been edited, etc.
  • It is much more than just document sharing, it also provide workflow. Example: Leave letter submitted by employee needs to be  approved by team leader and manager can used workflow, where in employee would get notification whenever any of them get approved the leave, by this way employee is happy as he get latest status of his leave approval, also manager doesn't needs to remember all the task, as he can able to view that leave request in its pending task.

Friday, August 13, 2010

How to access SharePoint User Profile from C# code

Step 1: Refer the following dlls in the code:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;



Step 2: Create the instance of SPSite object:

using (SPSite ospSite=new SPSite("http://servername:portname")
{}

where http://servername:portname is your sharepoint application url.
Here we have used using to create the instance of SPSite since 'using' automatically disposes the object when the block gets finished.

Withing 'using' block , add the following codes:


Step 3: Create the instance of servercontext object:

ServerContext ospServerContext = ServerContext.GetContext(ospSite);


Step 4: Create the instance of userporfile object propertycollection object:

UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(UniqueId);
Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

here uniqueid is the id by which each profile is recognized individually. Eacn user profile has a uniqueId many ny 5-2-1 id if it is an AD account or GUID.


Step 5: Check whether the USerprofile object is null or not

if (ospUserProfile != null && propColl != null)
{}

Step 6: Iterate thorugh all the proerties in property collection:

foreach (Property prop in propColl)
{}

In the for loop you can get the property name and value like this:

To get property name: prop.Name
To get property value: ospUserProfile[prop.Name].Value

To set a value to a proerty : ospUserProfile[prop.Name].Value ="SOME VALUE";

To save the user profile after updation: ospUserProfile.Commit();

This will get the userporfile of a user and update the profile.


The whole code is as follows:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using System.IO;
using System.Data;
using Microsoft.Office.Server.UserProfiles;

namespace Program1
{

public static void Main(string args[])
{
using (SPSite ospSite = new SPSite(webApp))
{
try
{
ServerContext ospServerContext = ServerContext.GetContext(ospSite);
UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(uniqueId);
Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

if (ospUserProfile != null && propColl != null)
{
foreach (Property prop in propColl)
{
Console.WriteLine("property Name : " + prop.Name);
Console.WriteLine("proerpty Value : " + ospUserProfile[prop.Name].Value);

//If updation is required
ospUserProfile[prop.Name].Value="SOME VALUE";

}
ospUserProfile.Commit();
}
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
}
}
}

How to set Item Level Permission in to Sharepoint List

SPList.RoleAssignments Property :
Gets the collection of role assignments for the list.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPRoleAssignment.RoleDefinitionBindings Property : Gets the collection of role definition bindings for the role assignment.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPPrincipal Class :
Represents a user or group that can be assigned permissions in Windows SharePoint Services to control security.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

I have written a function that will take the following parameters:

1. string Site url
2. string Library name
3. string Old user name (format : <domainname>\<username>
4. string new user name (format : <domainname>\<username>

My whole intension of function is to revoke permission of the item from old user and assign it to new user. You may or may not require the new user parameter if you are only revoking access.

public static void SetItemPermission(string SitePath, string LibName, string OldUser, string NewUser)
{

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite WebApp = new SPSite(SitePath))
{
using (SPWeb Site = WebApp.OpenWeb())
{
SPList list = Site.Lists[LibName];
SPQuery newSPQuery = new SPQuery();
newSPQuery.Query = "<where><contains><fieldref name="\">" +
"<value type="\">" + OldUser + "</value>" + "</contains></where>";
try{
SPListItemCollection listItemCol = list.GetItems(newSPQuery);
if (listItemCol.Count > 0)
{
SPUser user = null, _newUser = null;
SPRoleAssignment role = null;
foreach (SPListItem item in listItemCol)
{
user = Site.Users[OldUser];
SPPrincipal principal = (SPPrincipal)user;
item.RoleAssignments.Remove(principal);
role = new SPRoleAssignment(NewUser, "", "", "");
role.RoleDefinitionBindings.Add(Site.RoleDefinitions["Contribute"]);
item.RoleAssignments.Add(role);
}
item.SystemUpdate(false);
}
}}catch(Exception ex){}
}
}
});


}
#endregion

How to check whether SPList exists in Sharepoint?

Sometimes we require to check whether SPList exists or not. There is no direct method to check for it. Instead we have to use try-catch block to catch the exception and to determine the list existence:

The code is:


using (SPSite ospSite = new SPSite("http://<servername>:<portname>"))
{
using (SPWeb ospWeb = ospSite.OpenWeb())
{
try
{
SPList ospList = ospWeb.Lists["ListName"];
if (ospList != null)
return true;
}
catch(Exception ex)
{
return false;
}
}
}


This code block creates an instance of SPList object. If ospList object is not null that is list is there so it returns true.
If list does not exists, an exception will be raised and false will be returned from catch block

How to get distinct value from CAML query

Many times, we face a challenge to get unique rows froma CAML query. The main problem is that CAML does not have any feature to get the distinct rows in one go.

Way Around:

We all know that CAML query returns SPListItemCollection and we can convert the outcome to data table also.
We can convert the resultant datatable to dataview and again convert the dataview to datatable by using ToTable and arguments :
Distinct = true
and column name

So..
suppose we have SPWeb object as 'web' so

DataTable DT= web.GetSiteData(qry);
DataView v = new DataView(tbl);
return v.ToTable(true, "Type");


This code snippets returns the distinct rows by comparing column name "Type".

How to use RunWithElevatedPrivileges in Sharepoint

The SPSecurity class provides a static method named RunWithElevatedPrivileges that enables code to execute as system code running under the identity of SHAREPOINT\system. This allows code to run in an escalated security context to perform actions as the system.

This method should be used with care and should not expose direct access to system resources, but rather should be used when you need to perform actions on behalf of the system. The method is simple. You can either create a delegate to a public void method or simply write code within an inline delegate.

The signature looks like the following:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Code runs as the "SharePoint\system" user
});


Note that :
Code running with the escalated privilege should use a new SPSite object for code running as the system and use the SPContext.Current property to access the actual calling user’s identity.

To modify WSS content under the System credentials, you need to create a new SPSite site collection that generates a new security context for objects referenced from the site, as in the following example. You cannot switch the security context of the SPSite once it has been created, but must instead create a new SPSite reference to switch user contexts. The following code uses the system credentials to add a list item using the profile data of the current Web user:

SPSecurity.RunWithElevatedPrivileges(
delegate() {
using (SPSite site = new SPSite(web.Site.ID)) {
using (SPWeb web2 = site.OpenWeb()) {
SPList theList = web2.Lists["visitors"];
SPListItem record = theList.Items.Add();
record["User"] = SPContext.Current.Web.CurrentUser;
record.Update();
}
}
);

How to add a SPGroup to a Site Collection- Sharepoint

Groups cannot directly be added to a site-they must be added to the site collection.
If you try to add a group to the site’s Groups collection, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

This situation occurs because the SPGroup is always created at the Site Collection level and assigned to the site. The following code is valid and adds the LitwareSecurityGroup to the site collection groups.

// Adds a new group to the site collection groups:
site.SiteGroups.Add("LitwareSecurityGroup", site.CurrentUser,site.CurrentUser, "A group to manage Litware Security");

However, this still does not associate the group with our site, nor would it be useful within the site without any permissions. To add the group to the site, create a new SPRoleAssignment by associating an SPRoleDefinition with the SPGroup, and then add that role assignment to the site, as in the following code sample:


SPGroup secGroup = site.SiteGroups["LitwareSecurityGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);

How to get list of SPGroups in Sharepoint Site Collection

Sharepoint Gropus (or SPGroups) are never created in the context of the site-they are always created in the context of the site collection and assigned to a site.

We can get list of groups of a site by suing site.Groups


SPSite siteCollection = new SPSite("http://localhost/litware/sales/");
SPWeb site = siteCollection.OpenWeb();

foreach(SPGroup group in site.Groups){
Console.WriteLine(group.Name);
}

How to check whether a List is a Document Library?

Many times, we face a situation where we iterate through list collection. Now if we need to check whether a list is a SPDocumentLibrary or not, we can check it in very simple manner:

Suppose we need to display list of document libraries present in a site in a dropdown control named 'lstTargetLibrary', we will iterate through list collection and check for List type:


SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;

lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}

How to Upload a File to a SharePoint Site from a Local Folder

This code sample will show how to upload a file from your local pc to Sharepoint site using object mode:

1. Create a project and import namespaces :

using System.IO;
using Microsoft.SharePoint;


2. The UploadFile funtion code:

public void UploadFile(string srcUrl, string destUrl)
{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}

SPWeb site = new SPSite(destUrl).OpenWeb();

FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}


The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A System.IO.FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

To upload a file from a local folder on the same server that is running Windows SharePoint Services, you can use a System.IO.FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call an UploadFile method, which in turn calls the previously described EnsureParentFolder method.

How to delete a List from Sharepoint ?

This small code snippets will demonstrate how to delete a SPList from a sharepoint site.

To delete a list, you must specify the GUID of the list as the parameter for the Delete method. Use the ID property of the SPList class to find the GUID.

SPWeb mySite = SPContext.Current.Web;
SPListCollection lists = mySite.Lists;

SPList list = lists[ListName];
System.Guid listGuid = list.ID;

lists.Delete(listGuid);

Difference between Update and SystemUpdate in Sharepoint

We all know that whenever we add a list item or do some modification, we update the list. Here we have two options:

1. List.Update() and 2. List.SystemUpdate()

The main difference betwwen two is that,

List.Update() creates automatically new version of list item as Update method is called.


List.SystemUpdate() avoids SharePoint 2007 to change modified date and modifier fields. Argument false tells that no new versions are expected.

SystemUpdate takes an boolean argument that set whether new version need to be created or not.

Example using SystemUpdate() :

SPList list = web.Lists["myList"];
SPListItem item = list.Items[0];
item["myField"] = "my value";

item.SystemUpdate(false);
list.Update();

Monday, June 14, 2010

Handling AccessDenied Exception to implement our logic


The SPUtility.HandleAccessDenied method provides the functionality to redirect users to the standard "Access Denied Page" pragmatically, thus asking them to re-logon. One of the scenarios of such usage is the public sites, where access to the standard SharePoint specific pages still exists and you want to block those pages
However, you can handle access denied exception via SPSecurity.CatchAccessDeniedException = true
Access deined exception is handled by sharepoint platform and user will be redirected to _layouts/AccessDenied.aspx page if user doesnt have permission to perform that task. This might casue usability problem in some cases. You can handle access denied exception in your code by setting CatchAccessDeniedException value to true.
Following code snippet shows how to handle access denied exception:

bool catchException = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
//updating list item
SPList list = SPcontext.Current.Web.List["TestList"];
SPListItem item = list.Items[0];
item["title"] = "Some value";
//If user doesnt have permission, exception will be thrown
//If value of CatchAccessDeniedException is true, then user will be
//redirected to AccessDenied.aspx page
item.Update();
}
cach(Exception ex)
{
//Your custom error message can be shown here
}
finally
{
//reset the flag to original value
SPSecurity.CatchAccessDeniedException = catchException;
}