Dec 27, 2012

SharePoint Server Object Model Sample @Dotnet-Schools

SharePoint Server Object Model Sample @Dotnet-Schools






Creating a subsite
1
SPWeb mySite = SPContext.Current.Web;
2
SPWebCollection mySiteCollection = mySite.Webs;

3
uint lcid = mySite.Language;
4
string templateName = "WIKI#0";

5
mySiteCollection.Add("Nani Site", "Nani", "Site Created using object model", lcid, templateName, false, false);
6
mySite.Dispose();
Creating a list
1
SPSite mySiteCollection = SPContext.Current.Site;
2
SPWeb mySite = mySiteCollection.OpenWeb();

3
SPListCollection myListCollection = mySite.Lists;
4
myListCollection.Add("Niru6", "created using object model",SPListTemplateType.Contacts);
Show all top level sites in farm
01
SPWebServiceCollection myservices = new SPWebServiceCollection(SPFarm.Local);
02
foreach (SPWebService myservice in myservices)

03
{
04
SPWebApplicationCollection myWebAppCollection = myservice.WebApplications;

05
foreach (SPWebApplication mywebApp in myWebAppCollection)
06
{

07
SPSiteCollection mySiteCollection = mywebApp.Sites;
08
SPSite mySite = mySiteCollection[0];

09
Label1.Text += mySite.RootWeb.Url + "";
10
}

11
}
Return the collection of site collections in a SharePoint Web application
1
SPWebApplication myWebApp = SPContext.Current.Site.WebApplication;
2
SPSiteCollection mySiteCollection = myWebApp.Sites;

3
foreach (SPSite mySite in mySiteCollection)
4
{my

5
Label1.Text += mySite.RootWeb.Title + "";
6
mySite.Dispose();

7
}
To return the collection of The all the Webs or sites within a site collection, including the top-level site and all subsites
01
SPWebApplication myWebApp = SPContext.Current.Site.WebApplication;
02
SPSiteCollection mySiteCollection = myWebApp.Sites;

03
foreach (SPSite mySite in mySiteCollection)
04
{

05
SPWebCollection myWebCollection = mySite.AllWebs;
06
foreach (SPWeb myWeb in myWebCollection)

07
{
08
Label1.Text += mySite.Url + " " + myWeb.Title + "";

09
myWeb.Dispose();
10
}

11
mySite.Dispose();
12
}
To return the all the subsites and lists of the current site
01
SPSite mySite = SPContext.Current.Site;
02
SPWebCollection myWebCollection = mySite.AllWebs;

03
foreach (SPWeb myWeb in myWebCollection)
04
{

05
SPListCollection myListCollection = myWeb.Lists;
06
foreach (SPList myList in myListCollection)

07
{
08
Label1.Text += myWeb.Title +" " + myList.Title + "";

09
}
10
myWeb.Dispose();

11

12
}
Show all roles in a site
1
SPSite mySite = SPContext.Current.Site;
2
SPWeb myWeb = mySite.RootWeb;

3
SPRoleDefinitionCollection myRoleCollection = myWeb.RoleDefinitions;
4
foreach (SPRoleDefinition myRole in myRoleCollection)

5
{
6
Label1.Text += myRole.Name + "";

7
}
Show all alerts in a site
1
SPWeb mySite = SPContext.Current.Web;
2
SPAlertCollection myAlertCollection = mySite.Alerts;

3
foreach (SPAlert myAlert in myAlertCollection)
4
{

5
Label1.Text += myAlert.Title + "";
6
}
Show all lists in a site
1
SPWeb mySite = SPContext.Current.Web;
2
SPListCollection myListCollection = mySite.Lists;

3
foreach (SPList myList in myListCollection)
4
{

5
Label1.Text += myList.Title + "";
6
}
Show all list templates in a site
1
SPSite mySite = SPContext.Current.Site;
2
SPWeb myWeb = mySite.RootWeb;

3
SPListTemplateCollection myTemplateCollection = myWeb.ListTemplates;
4
foreach (SPListTemplate myTemplate in myTemplateCollection)

5
{
6
Label1.Text += myTemplate.Name + " " + myTemplate.Type + "";

7
}
Show all fields in a list
1
SPSite mySite = SPContext.Current.Site;
2
SPWeb myWeb = mySite.RootWeb;

3
SPList myList = myWeb.Lists["Niru3"];
4
SPFieldCollection myFieldCollection = myList.Fields;

5
foreach (SPField myField in myFieldCollection)
6
{

7
Label1.Text += myField.Title + "";
8
}
Show all items in a list column
01
SPSite mySite = SPContext.Current.Site;
02
SPWeb myWeb = mySite.RootWeb;

03
SPList myList = myWeb.Lists["Niru3"];
04
SPListItemCollection myItemCollection = myList.Items;

05

06
foreach (SPListItem myItem in myItemCollection)

07
{
08


09
Label1.Text += myItem["Last Name"].ToString() + "";
10


11
}
Delete all items from a list
When using a for Loop, if you wish to remove an item from the collection you are iterating through it can be done very easily. When using foreach you will get an exception stating that the item cannot be removed
Refer :
Link
1
SPSite mySite = SPContext.Current.Site;
2
SPWeb myWeb = mySite.RootWeb;

3
SPList myList = myWeb.Lists["Niru3"];
4
for (int i = myList.Items.Count - 1; i >= 0; i--)

5
{
6
myList.Items.Delete(i);

7
}
Show all groups in a site
1
SPSite mySite = SPContext.Current.Site;
2
SPWeb myWeb = mySite.RootWeb;

3
SPGroupCollection myGroupCollection = myWeb.Groups;
4
foreach (SPGroup myGroup in myGroupCollection)

5
{
6
Label1.Text += myGroup.Name + "";

7

8
}
Delete a item in a list based on condition
01
SPSite mySite = SPContext.Current.Site;
02
SPWeb myWeb = mySite.RootWeb;

03
SPList myList = myWeb.Lists["Niru3"];
04
for (int i = myList.Items.Count - 1; i >= 0; i--)

05
{
06
if (myList.Items[i]["Last Name"].ToString() == "Nani")

07
{
08
myList.Items.Delete(i);

09
}
10


11
}
Show all users in a group
01
SPSite mySite = SPContext.Current.Site;
02
SPWeb myWeb = mySite.RootWeb;

03
SPGroupCollection myGroupCollection = myWeb.Groups;
04
SPGroup myGroup = myGroupCollection["Viewers"];

05
SPUserCollection myUserCollection = myGroup.Users;
06
foreach (SPUser myUser in myUserCollection)

07
{
08
Label1.Text += myUser.Name + "

09
";
10
}
Show all users from all groups from user collection
01
SPSite mySite = SPContext.Current.Site;
02
SPWeb myWeb = mySite.RootWeb;

03
SPGroupCollection myGroupCollection = myWeb.Groups;
04
foreach (SPGroup myGroup in myGroupCollection)

05
{
06
SPUserCollection myUserCollection = myGroup.Users;

07
foreach (SPUser myUser in myUserCollection)
08
{

09
Label1.Text += myGroup.Name + "" + myUser.Name + "";
10
}

11

12
}
Show only blog sites
01
SPSite mySite = SPContext.Current.Site;
02
SPWebCollection myWebCollection = mySite.AllWebs;

03
foreach (SPWeb myWeb in myWebCollection)
04
{

05
if (myWeb.WebTemplate == "BLOG")
06
{

07
Label1.Text += myWeb.Title + "" ;
08
}

09
myWeb.Dispose();
10


11
}
Show services and status in sharepoint server farm
1
SPFarm myFarm = SPFarm.Local;
2
SPServiceCollection myServiceCollection = myFarm.Services;

3
foreach (SPService myService in myServiceCollection)
4
{

5
Label1.Text += myService.Name + " " + myService.Status + "
6
";

7
}
To get the timer jobs history for a particular service in the SharePoint 2010 farm
01
SPFarm myFarm = SPFarm.Local;
02
SPServiceCollection myServiceCollection = myFarm.Services;

03
foreach (SPService myService in myServiceCollection)
04
{

05
if (myService.DisplayName == "My Sample Service")
06
{

07
foreach (SPJobHistory entry in myService.JobHistoryEntries)
08
{

09
Label1.Text += "Job Definition Title - " + entry.JobDefinitionTitle + " : Status - " + entry.Status + " : Start Time - " + entry.StartTime + "
10
";

11
}
12


13
}
14
}
Get content database for all site collections
01
SPWebServiceCollection myWebServiceCollection = new SPWebServiceCollection(SPFarm.Local);
02
foreach (SPWebService myWebService in myWebServiceCollection)

03
{
04
SPWebApplicationCollection myWebApplicationCollection = myWebService.WebApplications;

05
foreach (SPWebApplication myWebApplication in myWebApplicationCollection)
06
{

07
SPContentDatabaseCollection myContentDatabaseCollection = myWebApplication.ContentDatabases;
08
foreach (SPContentDatabase myContentDatabase in myContentDatabaseCollection)

09
{
10
Label1.Text += myContentDatabase.Name + "

11
";
12
}

13
}
14


15
}
Add fields to list and add it to default view
1
SPWeb mySite = SPContext.Current.Web;
2
SPList myList = mySite.Lists.TryGetList("Niru2");

3
SPFieldCollection myFieldCollection = myList.Fields;
4
string strNewFieldName = myFieldCollection.Add("Native Place", SPFieldType.Text, false);

5
SPField oField = myFieldCollection.GetField(strNewFieldName);
6
SPView oView = myList.DefaultView;

7
SPViewFieldCollection colViewFields = oView.ViewFields;
8
colViewFields.Add(oField);

9
oView.Update();
Creating a new view in a list
01
SPWeb mySite = SPContext.Current.Web;
02
SPList myList = mySite.Lists.TryGetList("List_Name");

03

04
SPViewCollection myViewCollection = myList.Views;

05
string strViewName = "View_Name";
06
System.Collections.Specialized.StringCollection collViewFields = new System.Collections.Specialized.StringCollection();

07
collViewFields.Add("Field1_Name");
08
collViewFields.Add("Field2_Name");

09
collViewFields.Add("Field3_Name");
10
string strQuery = "" +

11
"1000";
12


13
myViewCollection.Add(strViewName, collViewFields, strQuery, 100, true, false,
14
Microsoft.SharePoint.SPViewCollection.SPViewType.Grid, false);
Source : MSDN
Creating a new content type and add it to a list, Adding the existing site columns to existing content type
- Check for duplicate content type, field, and list names.
- Create a new site content type.
- Add the content type to the site collection
- Create a site field to link to
- Link the content type to the field
- Commit changes to the database
- Create a list
- Apply the new content type to the list
o Add the new content type
o Remove the default content type
o Commit changes to the list
- Refer : Link
Delete recycle bin items
01
SPSite site = new SPSite(<>);
02
SPWeb web = site.RootWeb;

03
SPRecycleBinQuery q = new SPRecycleBinQuery();
04


05
q.RowLimit = Int32.Parse(<>);
06
q.OrderBy = SPRecycleBinOrderBy.Default;

07
SPRecycleBinItemCollection itemColl = web.GetRecycleBinItems(q);
08
foreach (SPRecycleBinItem item in itemColl)

09
{
10
Guid[] id = new Guid[1];

11
id[0] = item.ID;
12
itemColl.Delete(id);

13
}
Source: MSDN
• creating folder, uploading file to folder, deleting folder searching the folder in a doc lib
Refer to MSDN
Use about AllowUnsafeUpdates  :Refer this link
About Disposing objects :link
My Notes :
* (SPSite -> AllWebs)The AllWebs property of the SPSite class returns all the Web sites within a site collection, including the top-level site and all subsites.
* (SPWeb ->webs) To return a list of all the first-tier subsites beneath a specific Web site, use the Webs property of the SPWeb class.
* (SPWeb) openweb – return the site that is associated with the url that is used in SPSite constructor
* To return the collection of site collections in a SharePoint Web application, use the Sites property of the Microsoft.SharePoint.Administration.SPWebApplication class. Use properties of the Microsoft.SharePoint.SPContext class to return the current Web application.
* (SPWeb ->RootWeb)To return the top-level Web site of the current site collection, use the RootWeb property.
* close method — Closes the website at the end of a request and releases resources.
* Dispose method — Releases all resources used by the current instance of the website.
*  To Get the web site where the feature is activated.
SPWeb parentWeb = properties.Feature.Parent as SPWeb;
* when we use Rootweb and SPContext ie No explicit  dispose required.

Disclaimer:
The sample code provided is on “AS IS” basis with no warranties, and confers no rights.

SharePoint Object Model Code Samples

SharePoint provides a solid framework for the .Net developers to write code against and extend sharepoint functionality. As sharepoint is done on ASP.NET 2.0 and have a power code base of .Net Class libraries, a lot of developers can now make use of them and create excellent applications utilizing sharepoint features and libraries.

SPSiteDataQuery Class

Imagine a scenario in which you want to run a single query against every list in the current site collection that has been created from the Announcements list type and return all list items that were created today. The following code sample demonstrates how to do this by creating an SPSiteDataQuery object, initializing it with the necessary CAML statements, and then passing it to the current SPWeb object’s GetSiteData method.

SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";

string queryText = @" ";


query.Query = queryText;

DataTable table = site.GetSiteData(query);

foreach (DataRow row in table.Rows) {
Console.WriteLine(row["Title"].ToString());
}

Using SPQuery to query specific items in the list
To get back specific results within a list, you can use the SPQuery object. When you use an SPQuery object, you will create CAML statements to select specific data within the target list. To select announcements that have expired, you may want to use a query built with CAML statements, as shown in the following example:
SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@" ";

SPList list = site.Lists["News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}
You must specify the fields you want returned in the query by using the ViewFields property. Also note that you must specify the fields in terms of the field Name, and not DisplayName. If you attempt to access fields without specifying them in ViewFields, you will experience an exception of type ArgumentException

Enumerating through the Fields excluding Hidden and read only fields
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}

Checking if the List Exists and Adding a new list if it does not Exists
using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("http://spdevserver"3000")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}

if (list == null) {
Guid listID = web.Lists.Add(listName, "News",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}

Check if list is of the type Document Library or Not?
public bool CkechIfListisDocLib(SPList list) {
if (list is SPDocumentLibrary)
return true;
else
return false;
}

Running a Code with Elevated Permissions
If you want to run a portion of the code with elevated permissions

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// do something
});

Download a file from Document Library and Save it locally
private static void DownloadFile()
{
//site url
SPSite site = new SPSite("http://spdevser:3000/");
//web url
SPWeb web = site.OpenWeb(@"/sites");
//list name
SPList list = web.Lists["Form Templates"];
//downloading first items
File.WriteAllBytes(@"c:\test.doc", list.Items[0].File.OpenBinary());file

}

Add an Item to the List
private static void AddItem()
{

SPSite site = new SPSite("http://spdevserver:3000/"); //site url

SPWeb web = site.OpenWeb(@"/Dev/template"); //weburl

SPList list = web.Lists["COI"]; //list

SPListItem item = list.Items.Add(); //item to be added

item["Title"] = "Welcome"; //update the title field

list.Update(); //update list

}

Update a file to the Document Library

SPSite site = new SPSite("http://spdevserver:3000/");
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;

FileStream fs = File.Open(@"C:\Sample.doc",FileMode.OpenOrCreate,FileAccess.Read);

SPFolder myfolder = web.Folders["Documents"];

myfolder.Files.Add("Sample.doc", fs);
myfolder.Update();

SPQuery Samples


Basic Query - Query to get all the Items from a list where Category field is equal to "Sp2007"

// Get SiteColl
SPSite curSite = new SPSite("http://myPortal");

//Get Web Application
SPWeb curWeb = curSite.OpenWeb();

// Create a SPQuery Object
SPQuery curQry = new SPQuery();

//Write the query (suggested using U2U Query Bulider Tool)
curQry.Query = " SP2007 ";

// Set the Row Limit
curQry.RowLimit = 100;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection curItems = myList.GetItems(curQry);

// Go through the resulting items
foreach (SPListItem curItem in curItems)
{
string ResultItemTitle = curItem["Title"].ToString();
}

Query on DateTime Field - Query to Find Items in the List with Today's date.

// Create a SPQuery Object
SPQuery DateFieldQuery = new SPQuery();


//Write the query
DateFieldQuery.Query = “+ DateTime.Now.ToString("yyyy-MM-ddTHH:\\:mm \\:ssZ") + ”;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection ResultItems = myList.GetItems(DateFieldQuery);

Query Using Yes\No Columns -
Query to Retrieve all the Items from a list where a Yes\NO type Field, named "AreYouCool?" is "Yes".


// Create a SPQuery Object
SPQuery CheckBoxQuery = new SPQuery();


//Write the query
CheckBoxQuery .Query = “1 ”;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection ResultItems = myList.GetItems(CheckBoxQuery);

SharePoint Web services Samples


//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 = " " +
"" + ID + "" + Title+ "";
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 = "" + ListID+ "" + Title + "";

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 = "" + ID +"";

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)

Below is the code to get the values of a choice field in a sharepoint list . You can save these values into a datatable and can bind the datatable with a Drop-down control.

//get choice field values from sharepoint list
protected void GetDrpDownValuesFromList()
{
SPWebservice.Lists FMService = new SPWebservice.Lists();
FMService.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode ndLists = FMService.GetList("MyList"); //add list name
XmlDocument doc = new XmlDocument();
doc.LoadXml(ndLists.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 FieldsInList = doc.SelectNodes("//sp:Field", mg);

foreach (XmlNode Field in FieldsInList)
{
if (Field.HasChildNodes)
{
if (Field.Attributes["Name"].Value == "choiceFieldName")
{
foreach (XmlNode node in Field.ChildNodes)
{
if (node.HasChildNodes)
{
foreach (XmlNode Newnode in node.ChildNodes)
{
if(Newnode.HasChildNodes)
{
_addToDataTable(Newnode.InnerText); // Add node value to datatable
}}}}}}}

Get User Profile

Here's the code to retrieve the UserProfile from User Profiles Service Application in Sharepoint 2010 by passing the account name

SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite("SiteUrl"))
                        {
                            SPServiceContext context = SPServiceContext.GetContext(site);
                            UserProfileManager allProfiles = new UserProfileManager(context);
                            string loginName = @"DomainName\AccountName";
                            //Ex: TestDoamin\abc
                            //You can also use UserExists method to check
                            if (allProfiles.ResolveProfile(loginName).Length == 1)
                            {
                                UserProfile up = allProfiles.GetUserProfile(loginName);
                           
                             }
                        }
                    });


Adding Item Level Security to a List Item

Item Level Security for the User:

 public override void ItemAdded(SPItemEventProperties properties)
{
            SPUser usr = null;
            using (SPWeb web = properties.Web)
            {
                usr = web.SiteUsers.GetByID(web.CurrentUser.ID);

            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList lst = web.Lists[properties.ListId];
                        SPListItem li = lst.GetItemById(properties.ListItemId);

                        SPRoleDefinition rd = web.RoleDefinitions.GetByType(SPRoleType.Reader);

                        SPRoleAssignment ra = new SPRoleAssignment((SPPrincipal)usr);

                        ra.RoleDefinitionBindings.Add(rd);
                        if (!li.HasUniqueRoleAssignments)
                        {
                            li.BreakRoleInheritance(false);
                        }
                        for (int i = 0; i <= li.RoleAssignments.Count - 1; i++)
                        {
                            li.RoleAssignments.Remove(i);
                        }
                        li.RoleAssignments.Add(ra);
                        li.Update();

                    }
                }
            });
}

Item Level Security for a Group:

  public override void ItemAdded(SPItemEventProperties properties)
{
   SPGroup grp = null;
            string groupname = "ListUsers";

            SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite site = new SPSite(properties.SiteId))
                            {
                                using (SPWeb web = site.OpenWeb())
                                {
                                    web.AllowUnsafeUpdates = true;
                                    SPGroupCollection groupCollection = web.Groups;
                                    if (string.IsNullOrEmpty(groupname) || (groupCollection == null) || (groupCollection.Count == 0))
                                    {
                                        throw new ArgumentNullException("Security Group Not Found");
                                    }
                                    else
                                    {
                                        grp = groupCollection[groupname];
                                        SPList lst = web.Lists[properties.ListId];
                                        SPListItem li = lst.GetItemById(properties.ListItemId);

                                        SPRoleDefinition rd = web.RoleDefinitions.GetByType(SPRoleType.Reader);

                                        SPRoleAssignment ra = new SPRoleAssignment((SPPrincipal)grp);

                                        ra.RoleDefinitionBindings.Add(rd);
                                        if (!li.HasUniqueRoleAssignments)
                                        {
                                            li.BreakRoleInheritance(false);
                                        }
                                        for (int i = 0; i <= li.RoleAssignments.Count - 1; i++)
                                        {
                                            li.RoleAssignments.Remove(i);
                                        }
                                        li.RoleAssignments.Add(ra);
                                        li.Update();
                                        web.AllowUnsafeUpdates = false;
                                    }
                                }
                            }
                        });
}

SPContext Object


When building custom web parts for Windows SharePoint Services V3. You can use the SPContext object to get for instance the site or web from the current context.You can also get the listitem and the webfeatures.

In WSS V2 you would use SPControl.GetContextSite() or SPControl.GetContextWeb() but that's a lot less flexible and it's slower as well.
A couple of different uses of SPContext are shown below:

*************************************************************************
SPList currentList = SPContext.Current.List;
SPWeb currentSite = SPContext.Current.Web;
SPSite currentSiteCollection = SPContext.Current.Site;
SPWebApplication currentWebApplication = SPContext.Current.Site.WebApplication;

*************************************************************************

SPListItem item = (SPListItem)SPContext.Current.Item;

*************************************************************************

SPWeb site = SPContext.Current.Site.OpenWeb(guid);
SPUser user = SPContext.Current.Web.CurrentUser;

*************************************************************************

SPSiteDataQuery siteQuery = new SPSiteDataQuery();
DataTable queryResults = SPContext.Current.Web.GetSiteData(siteQuery);
queryResults.TableName = "queryTable";
queryResults.WriteXml("C:\\queryTable.xml");

The last example makes use of the SPSiteDataQuery object.  In WSS V3 there are two different query objects. Besides SPSiteDataQuery object there is also the SPQuery object.
The difference between the two is that SPQuery can only be used for queries within a single folder in a single list. SPSiteDataQuery can be used for cross lists and even cross site queries.




Basic Query - Query to get all the Items from a list where Category field is equal to "Sp2007"

// Get SiteColl
SPSite curSite = new SPSite("http://myPortal");

//Get Web Application
SPWeb curWeb = curSite.OpenWeb();

// Create a SPQuery Object
SPQuery curQry = new SPQuery();

//Write the query (suggested using U2U Query Bulider Tool)
curQry.Query = " SP2007 ";

// Set the Row Limit
curQry.RowLimit = 100;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection curItems = myList.GetItems(curQry);

// Go through the resulting items
foreach (SPListItem curItem in curItems)
{
string ResultItemTitle = curItem["Title"].ToString();
}

Query on DateTime Field - Query to Find Items in the List with Today's date.

// Create a SPQuery Object
SPQuery DateFieldQuery = new SPQuery();


//Write the query
DateFieldQuery.Query = “+ DateTime.Now.ToString("yyyy-MM-ddTHH:\\:mm \\:ssZ") + ”;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection ResultItems = myList.GetItems(DateFieldQuery);

Query Using Yes\No Columns -
Query to Retrieve all the Items from a list where a Yes\NO type Field, named "AreYouCool?" is "Yes".


// Create a SPQuery Object
SPQuery CheckBoxQuery = new SPQuery();


//Write the query
CheckBoxQuery .Query = “1 ”;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection ResultItems = myList.GetItems(CheckBoxQuery);

No comments:

Post a Comment

Search for