How to use SharePoint 2010 Client Object Model to Managed Client OM

After I have written nice posts on complete details on Client Object Model and ECMAScript introduction planned to write introduction posts on Managed Client OM and Silverlight Client OM. So, in this post, we will discuss on Managed Client Object Model.
So, Managed Client Object Model is simple .NET code written based on CLR. So, you can use C#.net or VB.net to write code and execute whatever you want against SharePoint server.So, you can use any c# project to write code and run it. But, are there any prerequisites to write code? Do we need to follow some rules or process?
First, to write client side code, we need SharePoint libraries which has all the methods and classes to communicate with the SharePoint server. For this reason Microsoft SharePoint 2010 provides us the client side dll's to write Managed code. Below are the details.
DLL's needed: Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll. Find these files in the 14/ISAPI folder. Usually, the location would be at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI".

How to create a project to start working and communicate to SharePoint 2010 server? Follow the steps below.

  1. Open Visual Studio 2010.
  2. File -> New -> Project -> Visual C# -> Choose Console Application from the list of C# project types. [Make sure you have selected .NET Framework 3.5 on the top of window as shown in below.]

  3. Give some name to the project. I have given some valid name as "SP2010_HelloWorld".
  4. Now next step is getting the SharePoint Client Dll's reference to our project. So, for this get the SharePoint dll's to the client machine [Where we created project] and paste the DLL's in some safe location. I copied them to C:\SP2010_ClientDLL\.
  5. Now, go to Visual Studio 2010 project right click on project -> select References and browse to location where client dll's copied and select both dll's and hit ok.
  6. Finally, our references folder should looks like below.

  7. Now we are ready with all prerequisites and part left is writing code. I will show you simple code on how to write the code for getting web site title and description.
  8. Before start coding, we need add reference to the namespace in page by declaring using keyword as shown below.
using Microsoft.SharePoint.Client; 







9.  This is the code to get data from a SharePoint server, in this example we are retrieving Title and Description of a web site.




static void Main(string[] args)   
{
LoadSiteData();
}

private static void LoadSiteData()
{
string webUrl = "http://nb16";
ClientContext context = new ClientContext(webUrl);
Web web = context.Web;
//Loads all web properties.
context.Load(web);
//Execute the query and load the object into the response given in load() method.
context.ExecuteQuery();
Console.WriteLine(web.Title);
Console.ReadLine();
}







NOTE: Remember, you need to change the webUrl to actual SharePoint site url in the above example.



10.  Now run the code and see the output. You will see the title and description of the SharePoint web site.


That's it!!! Very simple and easier way. SharePoint 2010 client side development is very easy now. Lets rock it....

How to use the Silverlight Client Object Model in SharePoint 2010

As part of the introduction series, I want to present the advantage of the client object model introduced in SharePoint 2010. There are great advantages with this model as it don't require SharePoint needs to be installed on the client machine. We just need to refer the client dlls which Microsoft SharePoint provides and based on them we will write code to communicate with SharePoint server. In this article we will go through Silverlight Client Object Model. If you want to know the other client object model types go here. ECMAScript and Managed client object models.
To communicate with the SharePoint server in Silverlight context we need to give two client SharePoint DLL references to the silver light project.

DLL's Needed: Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They can be found at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".
OK, we understand the concept and we will create a project and implement code for better understanding on how it works.

  1. Open Visual Studio 2010.
  2. File -> New -> Project -> Visual C# -> Silverlight -> Select Silverlight Application project template as shown below.

  3. Give some name to the project. In my example, I have given some meaningful name like "SP2010Silverlight_HelloWorld" and create the project.
  4. Now, you see the below screen.

  5. What this meaning is "Do you want to create an ASP.NET web site and host the XAP file generated to the web site". For our example, it's really not needed. But, there is no problem by using that.
  6. Now next step is getting the SharePoint Silverlight Client Dll's reference to our project. So, for this get the SharePoint dll's to the client machine [Where we created project] and paste the DLL's in some safe location. I copied them to C:\SP2010_ClientDLL\.
  7. Now, go to Visual Studio 2010 project right click on project -> select References and browse to location where client dll's copied and select both dll's and hit ok as shown in below figure.

  8. After you added all references the references folder should look like this.
  9. Now we are ready with all prerequisites and part left is with writing code. I will show you simple code on how to write the code for getting web site title and description using Silverlight Client OM.
  10. Before start coding, we need to add reference to the namespace in page by declaring using keyword as shown below.
using Microsoft.SharePoint.Client; 





11. This is the code to get data from a SharePoint server, in this example we are retrieving Title and Description of a web site.



XAML code: MainPage.XAML




<?XML:NAMESPACE PREFIX = [default] http://schemas.microsoft.com/winfx/2006/xaml/presentation NS = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" /><usercontrol xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:datainput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" x:class="SilverLight_ClientOM_LoadSiteData.MainPage" mc:ignorable="d" d:designwidth="400" d:designheight="197">   
<grid x:name="LayoutRoot" background="White">
<BUTTON name=btnLoadSite content="Load Site" width="75" verticalalignment="Top" margin="25,12,0,0" horizontalalignment="Left" height="23" click="btnLoadSite_Click"></BUTTON>
<canvas name="canvasLabels" visibility="Collapsed">
<DATAINPUT:LABEL content="Site: " name="label1" width="73" verticalalignment="Top" margin="41,55,0,0" horizontalalignment="Left" height="22"></DATAINPUT:LABEL>
<DATAINPUT:LABEL name="label2" width="233" verticalalignment="Top" margin="120,55,0,0" horizontalalignment="Left" height="22"></DATAINPUT:LABEL>
<DATAINPUT:LABEL content="Url:" name="label3" width="73" verticalalignment="Top" margin="41,84,0,0" horizontalalignment="Left" height="24"></DATAINPUT:LABEL>
<DATAINPUT:LABEL name="label4" width="233" verticalalignment="Top" margin="120,84,0,0" horizontalalignment="Left" height="24"></DATAINPUT:LABEL>
<DATAINPUT:LABEL content="Description" name="label5" width="73" verticalalignment="Top" margin="41,116,0,0" horizontalalignment="Left" height="26"></DATAINPUT:LABEL>
<DATAINPUT:LABEL name="label6" width="233" verticalalignment="Top" margin="120,116,0,0" horizontalalignment="Left" height="26">
</DATAINPUT:LABEL></canvas>
</grid>
</usercontrol>







MainPage.Xaml.cs file code:




using System;   
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;

namespace SP2010Silverlight_HelloWorld{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();

private void btnLoadSite_Click(object sender, RoutedEventArgs e)
{
context = ClientContext.Current;
web = context.Web;
context.Load(web, w => w.Title, w => w.Description, w => w.ServerRelativeUrl);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}

private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = LoadSiteData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}

private void LoadSiteData()
{
canvasLabels.Visibility = System.Windows.Visibility.Visible;
label2.Content = web.Title;
label4.Content = web.ServerRelativeUrl;
label6.Content = web.Description;
}
}
}







Place all the code above given in the both files of your project.

Note: Remember to change the web url given in the code "http://nb16" to actual SharePoint server url.


Till now, what we have done is, writing and complete code for loading the site data. But, we need to understand the above code.


In the above code, there is a callback function used. Which is asynchronous and loads data. But, you may confuse at the line delegate UpdateUIMethod(). I copied the below text from MSDN to better understand about the delegate and why it's needed.


"Because query execution is asynchronous when you use the SharePoint Foundation Silverlight object model, you must pass delegates for callback methods as parameters in the ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) method, similarly to query execution in the ECMAScript object model. However, to run code that makes changes in the user interface (UI) through the Silverlight object model, you must delegate this work to the Dispatcher object of the thread that created the UI by calling BeginInvoke()". So, we should use the delegate to make changes on the UI.


Deploy and Test


We have two ways to deploy the XAP file in SharePoint environment.


One is, We can use SharePoint default location [\Templates\Layouts\ClientBin] and deploy the file there. Refer this location from the Silverlight web part.


Second is, We can use a SharePoint document library and deploy the file there. Refer this document library location file path while adding the silverlight web part. In this post, we will use the default location to deploy and test.




  1. To deploy and test the code in SharePoint 2010 we need to use the SharePoint Silverlight web part [New web part added in this version].


  2. The silverlight web part default location is "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin". So, all the XAP files should be deployed to this location to use them in the silverlight web part.


  3. To make this process easier, we need to do below.


  4. Right click on Silverlight project -> propertiese -> Build -> change the output path to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin" as shown below.




  5. Build the solution and see the XAP generated in the ClientBin location.


  6. Now, navigate to SharePoint site where you want to see the silverlight data, Edit page.


  7. Add silverlight web part to the page.


  8. It will prompt you for the XAP file location: Type the url: "/_layouts/ClientBin/SP2010Silverlight_HelloWorld.xap".


  9. Now click on OK and you can see the silverlight web part on the page.




Ooh!!! This is it!!! We are done with development, deployment and testing. Hope this won't create any confusion. If you have any issues please let me know. I am always here to help you out...

Copy files from one sitecollection to other in sharepoint 2010

Copying files from one site collection to other can be done using Content deployment feature of SharePoint 2010. You can do this either manually or on a predetermined schedule.
Some Important things to Note :
1. Content deployment is a one-way process - Content is copied from a source site collection to a destination site collection.The content deployment feature does not support round-trip synchronization from source to destination and back again.
2. Creating new content or changing existing content on the destination site collection can cause content deployment jobs to fail.
3. You cannot deploy(copy) a site to the same content database as the source site - This is because all the GUIDs that are used to define sites, Web pages, lists, and items are transferred with the site when it is deployed to the destination. For this reason, you cannot deploy a site to the same content database as the source site.
4. The destination site collection must exist before you can deploy content to it, and it must be an empty site collection.You must not specify a template for the site collection. If a template is used to create the site collection, the content deployment job will fail.
5. Before you start any process, you must first configure the destination server for receiving incoming requests or to accept content deployment jobs. This can be done using Content deployment Settings Page.
6. Lastly, Content deployment paths and jobs are created and managed on the Manage Content Deployment Paths and Jobs page in Central Administration.
Now lets talk about the main components
Content deployment paths and jobs - There are two main components of content deployment.
1. The first is a content deployment path, which is a relationship between a source site collection and a destination site collection.
2. The second part is a content deployment job, which is associated with a path and is a collection of settings that are related to the schedule and scope that are followed in deploying that content.
In short, A job is associated with a path, and it defines the specific content that is to be deployed from the source to the destination and the schedule on which the deployment should occur. After you have created the content deployment path, you can specify jobs to run on that path.
The Overall Steps that you need to follow are :
1. Create a source site.
2. Create a new Web application.
3. Create a destination site collection.
4. Enable incoming content deployment jobs.
5. Create a content deployment path.
6. Create a content deployment job.
7. Deploy the source site.
8. Update the source site.
9. Deploy changes.
10. Check the destination site for changes.

Programmatically access user profile + client object model SharePoint 2010

Here is a Code snippet for retrieving user profile picture using Client Object model – ECMAScript . I am passing the userId from the front end to a javascript method called “getUserProfile()” to retrieve the user profile info. The method onQuerySucceeded will get you the user Profile info.
function getUserProfile(userID)
{
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var userInfoList = web.get_siteUserInfoList();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Eq><FieldRef Name=\’ID\’/>’ +’<Value Type=\’Number\’>’ + userID + ‘</Value></Eq>’ +
‘</Where></Query><RowLimit>1</RowLimit></View>’);
this.collListItem = userInfoList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args)
{
var item = collListItem.itemAt(0);
var profile = item.get_item(‘Notes’);
var pictureUrl = item.get_item(‘Picture’).get_url();
var userImage = document.getElementById(‘myImageContainer’); -> Image object
userImage.src = pictureUrl;
var profileDiv = document.getElementById(‘userProfileContainer’);
profileDiv.innerHTML = profile;
}

Get Item level Permissions using Client Object model SHarePoint 2010

Here is a little code snippet to get the info about the users who have permission for a specific item in a list
Retrieving permissions for a Specific item -
private void GetItemPermission()
{
SecurableObject curObj = null;
ListItem curItem = ctx.Web.Lists.GetByTitle(“My List”).GetItemById(ItemId); -> Use ItemId of the Item.
//plug it into our query objectcurObj = 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();
}

Check User Permission in Sharepoint Designer 2010 workflow

In SharePoint 2010 Designer workflow the User-Impersonation type step has some additional conditions available for checking list and item level permissions for a specified
Lets look at two major conditions that you would need to implement impersonation -
1. Check list item permissions - The condition simply says the below :
If permissions for these users are at least these permissions on item in this list.
The usage : If permissions for WFApprovers Members are at least Read on item in Current Items
For the above condition to evaluate as true, the users must have at least the permissions that the Read Permission levels provide. This step can very well be used to check that the WFApprovers should have read access to the items.
2. Check list item permission levels - The condition simply says the below :
If permission levels for these users are at least these permission levels on item in this list.
The usage : If permission levels for ikapoor Members are at least Read on item in Current Items.
Please note that : The users can be a single user, multiple users, but you cannot use a group in this condition.
Important Things to remember Notes : Impersonation steps can only be added to the root of a workflow and cannot be nested in another step.

WebPart Life cycle

1. protected override void OnInit(EventArgs e)
2. protected override void OnLoad(EventArgs e)
3. protected override void CreateChildControls()
4. protected override void LoadViewState(object savedState) //Only at Postback
5. protected override void OnPreRender(EventArgs e)
6. protected override void Render(System.Web.UI.HtmlTextWriter writer)
7. protected override void OnUnload(EventArgs e)
8. public override void Dispose()

Add/Update/Get List Item by SharePoint Web services

//Add a New List Item
protected void CreateListItem(string ID, string Title)
{
SpWebservice.Lists SPService = new SpWebservice.Lists();
SPService.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode ndListView = SPService.GetListAndView("MyList", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;
XmlDocument doc = new XmlDocument();
System.Xml.XmlElement batch = doc.CreateElement("Batch");
batch.SetAttribute("OnError", "Continue");
batch.SetAttribute("ListVersion", "1");
batch.SetAttribute("ViewName", strViewID);
batch.InnerXml = "<method> <id="1" cmd="New">" +
"<field name="Id">" + ID + "</field><field name="Title">" + Title+ "</field>";
try
{
SPService.UpdateListItems(strListID, batch);
}
catch { }
}
//Update list Item
protected void UpdateListItem(string ListID,string Title)
{
SpWebservice.Lists SPService = new SpWebservice.Lists();
SPService.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode ndListView = SPService.GetListAndView("MyList", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;
XmlDocument doc = new XmlDocument();
System.Xml.XmlElement batch = doc.CreateElement("Batch");
batch.SetAttribute("OnError", "Continue");
batch.SetAttribute("ListVersion", "1");
batch.SetAttribute("ViewName", strViewID);
batch.InnerXml = "<method id="1" cmd="Update"><field name="ID">" + ListID+ "</field><field name="Title">" + Title + "</field></method>";
try
{
SPService.UpdateListItems(strListID, batch);
}
catch { }
}
//Get List Items
protected void GetListItems(string ID)
{
SpWebservice.Lists SPService = new SpWebservice.Lists();
SPService.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode ndListView = SPService.GetListAndView("MyList", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
ndViewFields.InnerXml = "";
ndQuery.InnerXml = "<Where><Eq><FieldRef Name=ID/><Value Type='Number'>" + ID +"</Value></Eq></Where>";
try
{
XmlNode ndListItems =
SPService.GetListItems(strListID, null, ndQuery, ndViewFields, null, null, null);
XmlDocument doc = new XmlDocument();
doc.LoadXml(ndListItems.OuterXml);
XmlNamespaceManager mg = new XmlNamespaceManager(doc.NameTable);
mg.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
mg.AddNamespace("z", "#RowsetSchema");
mg.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
mg.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois");
mg.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
mg.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory");
XmlNodeList NodeList = doc.SelectNodes("//sp:listitems/rs:data", mg);
foreach (XmlNode ListItem in NodeList)
{
foreach (XmlNode node in ListItem.ChildNodes)
{
string ID = string.Empty;
string Title = string.Empty;
XmlAttribute id = node.Attributes["ows_ID"];
if (id != null)
{
ID = id.Value;
}
XmlAttribute _Title= node.Attributes["ows_Title"];
if (_Title!= null)
{
Title= _Title.Value;
}
_AddToDataTable(ID, Title);
}
}
catch { }
}
// Get list Fields (using GetList method)
Please see my Post Get choice field values Using GetList() method of SharePoint Web services to get values in a choice field column in a list.

Complete details about Client Object Model in SharePoint 2010

This is the introduction to the Client Object model introduced in the SharePoint 2010. This is going to be a huge help and useful part in SharePoint 2010 for developers and makes lot of customization to the existing SharePoint system.
In eariler versions, I mean till SharePoint 2007 the code runs using the SharePoint object model to run against the server which is running SharePoint. Other than the SharePoint server object model, other way is, simply reference the web service and use that to get and manipulate data. Then what is the need of SharePoint 2010 Client object model[Cleint OM] concept?

What is Client Object Model?

Client Object Model is introduced in SharePoint 2010 which helps to developers to make things easier to develop the client side applications for SharePoint 2010. Client Object Model can run on the client machines (Where SharePoint is not installed) and communicate with the SharePoint server remotely. This is the great advantage for the SharePoint devs as they don't have to install SharePoint for development any more.

What are the different Client OM supporting in the SharePoint 2010 API? [Client API]

  1. .NET Managed Client - Implemented in .NET CLR. I mean we use this in Web, Windows and Console applications.
  2. Silverlight Client - You can use the SharePoint objects in Silver light coding. Wow, this is going to be a huge advantage to the Silverlight applications which can be integrated into SharePoint. Before we don't have access to SharePoint objects inside Silverlight context.
  3. ECMAScript Client - Through javascript too, we can get context and do manipulations to SharePoint objects. Do you think it's possible? Yes, its a brilliant way of thinking from Microsoft SharePoint team and this will help in great scenarios. Will explain later in this article.

Why Client Object Model comes into the picture? Are there any specialties of them?

The main started point to think by SharePoint team are as follows.

  1. Is it really necessary to have SharePoint installed on server for SharePoint development? - Yes, in SharePoint 2007 you have to install SharePoint on the server to write code and test it.
  2. What is the advantage of writing more web services to serve what the clients are looking for? - This is completely not a feasible solution to give or expose web services for each and every single requirement to get and manipulate data. It has plenty of limitations and if Microsoft exposes 500 web services and you didn't find what you really need and they are just waste. Instead write whatever you want and use them.
  3. The great thinking and beautiful solution to the people who don't allow server side coding in the SharePoint sites is ECMAscript client OM. You can create a simple javascript file and deploy into the server to get what you needed. As we know, most of the clients don't allow server side coding but they want something to be developed. In SharePoint 2007 it's very difficult to get this job done. But now in SP 2010 very easy.
So, these things take into high priority and makes them to come up with a great solution in the form of Client Object Model. The great advantage of it is completely looks [Syntax] like the SharePoint Object Model. So, nothing new for developers and no confusion. Infact very simple to manage and write code.

SharePoint object model syntax:

Server side syntax
Client side syntax

SPContext
ClientContext

SPSite
Site

SPWeb
Web

SPList
List

Now, I believe you have understood the Client OM concept. Now, we will discuss a little bit about technical implementation.
SharePoint 2010 provides the client support files to refer the SharePoint objects and communicate with the SharePoint server. Below are the details.

For Managed Client
DLL's needed : Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll. Find these files in the 14/ISAPI folder. Usually, the location would be at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI".

Silverlight
Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They find at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".

ECMAScript
SP.js file - The file fund at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS".

What we need to do is, add the relted file to the project references if it is Managed client or Silverlight and start using the SharePoint objects in the code. If it is ECMAScript then we just need to declare the line ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js"); on the top of js file to use the SP object.
**Initialize is some javascript function.**
My next posts will be the examples of each client OM implementation and how to get, manipulate data for better understanding.

How to remove a user from a sharepoint group by programe

You can remove a user by its LoginName of by its internal UserId from a specified group.

Here is an example of both

Remove by UserId -

Method 1 –

web.AllowUnsafeUpdates = true;

SPGroupCollection collGroups = web.SiteGroups;

SPUserCollection usercoll = siteobj.RootWeb.SiteUsers;

int ID = oWeb.Users[UserName].ID;

usercoll.RemoveByID(ID);

web.Update();

web.AllowUnsafeUpdates = false;

Method 2 –

web.AllowUnsafeUpdates = true;

SPGroupCollection collGroups = web.SiteGroups;

SPUserCollection usercoll = siteobj.RootWeb.SiteUsers;

String LoginID = web.CurrentUser.LoginName;

usercoll.Remove(LoginID);

web.Update();

web.AllowUnsafeUpdates = false;

How to Check whether a user belongs to one given SPGroup or not in SharePoint

Today, in our current project, we got one requirement: Get the groups via current logon user.

As you know, i first search the MSDN. I got two objects: SPGroup, SPUser. How should use them.

I create a virtual web part to test them, below is the code, you could use these code to check whether a user belongs to one given SPGroup or not in SharePoint.You will find this is very useful when you work on any user and group manage in sharepoint 2007 and sharepoint 2010

private bool GetGroupofUser()
{
bool flag = false;
using (SPSite siteCollection = SPContext.Current.Site)
{
using (SPWeb site = siteCollection.OpenWeb())
{
string groupName = "TestGroup";
//Get the current logged in user
SPUser currentUser = site.CurrentUser;

//Get all the user groups in the site/web
SPGroupCollection userGroups = currentUser.Groups;
//Loops through the grops and check if the user is part of given group or not.
foreach (SPGroup group in userGroups)
{
//Checking the group
if (group.Name.Contains(groupName))
flag = true;
break;
}
}
}
return flag;
}

Create List Print Ribbon in SharePoint 2010

This solution named ListPrintingUtility designed to add support for printing lists. The idea behind this solution is to add a command button to the Ribbon above a list that will allow the user to print the current view of the list. Below screenshot shows what the Print List button looks like on the Ribbon and also shows the utility printing window that opens when the button is clicked.

The Print List button shown on the Ribbon is added using a CustomAction element. When adding to the Ribbon, the CAML is more complex than what is required for simply adding to the Site Actions menu. Nonetheless, the CAML is supported by the sandbox, so it’s a valid approach for creating the required interface.

Bolow codes shows the CAML used to create the button. This CustomAction element extends the Ribbon with a custom Print List command.

   1: <Elements xmlns="http://schemas.microsoft.com/sharepoint/">



   2:  



   3:   <CustomAction



   4:       Id="Ribbon.List.Items.Print"



   5:       Location="CommandUI.Ribbon"



   6:       RegistrationType="ContentType"



   7:       RegistrationId="0x01"



   8:       Sequence="11"



   9:       Title="Print">



  10:     <CommandUIExtension>



  11:       <CommandUIDefinitions>



  12:         <CommandUIDefinition Location="Ribbon.ListItem.Actions.Controls._children">



  13:           <Button



  14:             Id="Ribbon.List.Items.Action.PrintListButton"



  15:             Sequence="01"



  16:             Alt="Print"



  17:             Command="PrintList"



  18:             Image16by16="/_layouts/images/mewa_frozenb.gif"



  19:             Image32by32="/_layouts/images/mewa_frozenb.gif"



  20:             LabelText="Print List"



  21:             ToolTipTitle="Print List"



  22:             ToolTipDescription="Opens current view in a printer-friendly page."



  23:             TemplateAlias="o1"/>



  24:         </CommandUIDefinition>



  25:       </CommandUIDefinitions>



  26:       <CommandUIHandlers>



  27:         <CommandUIHandler



  28:           Command="PrintList"



  29:           CommandAction="javascript:



  30:             var queryString = '?ListId={ListId}&amp;ViewId=' + ctx.view;



  31:             var targetUrl = '{SiteUrl}/PrintingPages/List.aspx' + queryString; 



  32:             var windowOptions = 'scollbars=1,height=600,width=800';



  33:             window.open(targetUrl, 'printwindow', windowOptions);"/>



  34:       </CommandUIHandlers>



  35:     </CommandUIExtension>



  36:   </CustomAction>



  37:  



  38: </Elements>




The CommandAction attribute specifies the code to run when the button is clicked. In this case, some JavaScript runs that opens a new window containing the page List.aspx. QueryString parameters are passed to the page detailing the list and view to display. The idea is simply to display the current view in a new page without any chrome. This design effectively creates a print view for the list. The challenge with the List.aspx page is that it must be designed to run in the sandbox. In the past, most developers would simply deploy the page as an application page to the LAYOUTS directory directly in the SharePoint root directory. But the sandbox doesn’t support these types of pages. Therefore, we need a different approach. For this solution, the List.aspx page is deployed as a site page. Site pages are pages that are deployed to the content database instead of the system directory. These types of pages are supported in the sandbox and can be deployed to the content database by using a SharePoint project item created from the Module SharePoint project item type. Below screenshot shows the ListPrintingUtility project opened in Visual Studio 2010. You can see that a SharePoint project item named RibbonExtensions was created from the Empty Element SharePoint project item type. This project item contains the element manifest with the CustomAction that adds the Print List button to the Ribbon. A second SharePoint project item, PrintingPages, was created from the Module SharePoint project item type. The PrintingPages item is used to deploy the site page List.aspx along with its associated files, including List.js, ListStyles.css, and ListStylesPrinting.css.





The site page List.aspx renders a print view of a list. When a user clicks the Print List button, the List.aspx page is requested with a QueryString containing the ListId and the ViewId. The List.aspx page must provide code to get the list items for rendering. However, there is a problem: site pages don’t support server-side code. Therefore, you can’t write any code in the page that uses the server-side SharePoint object model. This is where the client object model comes into play. The client object model is a JavaScript library that allows you to write code on the client that is very similar to server-side code. For this solution, the necessary print view is created using clientside code, which is supported in site pages. Below codes shows the complete code in List.js for rendering the print view using the client object model.





   1: var list;



   2: var printView;



   3:  



   4: function initPage() {



   5:   $get("listTitle").innerHTML = 'getting list data...'; 



   6:   ExecuteOrDelayUntilScriptLoaded(getListData, "sp.js");  



   7: }



   8:  



   9: function getListData() {



  10:   // get QueryString parameters



  11:   var queryString = window.location.search.substring(1);



  12:   var args = queryString.split('&');



  13:   var listId = args[0].split('=')[1];



  14:   var viewId = args[1].split('=')[1];



  15:   // use client object model to get list items



  16:   var context = new SP.ClientContext.get_current();



  17:   var site = context.get_web();



  18:   context.load(site);



  19:   var lists = site.get_lists();



  20:   context.load(lists);



  21:   list = lists.getById(listId);



  22:   context.load(list);



  23:   var views = list.get_views();



  24:   context.load(views);



  25:   var view = views.getById(viewId);



  26:   context.load(view);



  27:   printView = view.renderAsHtml();



  28:   context.executeQueryAsync(success, failure);



  29: }



  30:  



  31: function success() {



  32:   $get("listTitle").innerHTML = list.get_title();



  33:   $get("listTable").innerHTML = printView.get_value();



  34: }



  35:  



  36: function failure() {



  37:   $get("listTitle").innerHTML = "error running Client OM query";



  38:   $get("listTable").innerHTML = "";



  39: }






The print list solution is a good example of the thinking involved in designing sandboxed solutions. Supported CAML elements were used to create the button. A site page was used to create the user interface experience, and supported client-side code was used to implement the functionality. A key point is that this project contains no server-side code.