Monday, March 22, 2010

Code Snippets

Get list Items: /// Gets a collection of list items that match the query from the specified list, regardless of the permissions of the current user /// The server-relative path to the list /// The CAML query that has to be run against the list /// An SPListItemCollection object that represents the resulting list items public static SPListItemCollection GetSecuredListItems(string ListServerRelativePath, string CamlQuery) { if (string.IsNullOrEmpty(ListServerRelativePath)) throw new ArgumentNullException("The server-relative path to the list is required for this function"); SPListItemCollection results = null; string listAbsoluteURL = SPContext.Current.Site.MakeFullUrl(ListServerRelativePath); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(listAbsoluteURL)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList(ListServerRelativePath); SPQuery query = new SPQuery(); query.Query = CamlQuery; results = list.GetItems(query); } } }); return results; } Update List Item: /// Updates a single item for a single field on a list, even if the current user doesn't have the access /// The server-relative path to the list /// The internal ID of the item to be updated /// The display name of the field to be updated /// The new value that has to be applied for the field /// The SPListItem object that contains the list item that was updated public static SPListItem UpdateSecuredListItem(string ListServerRelativePath, string ID, string FieldName, string Value) { if (string.IsNullOrEmpty(ListServerRelativePath)) throw new ArgumentNullException("The server-relative path to the list is required for this function"); int id; if (!int.TryParse(ID, out id)) throw new ArgumentException("The ID specified is not valid (ID = " + ID + ")."); SPListItem result = null; string listAbsoluteURL = SPContext.Current.Site.MakeFullUrl(ListServerRelativePath); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(listAbsoluteURL)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList list = web.GetList(ListServerRelativePath); SPField field = list.Fields[FieldName]; if (field == null) throw new ArgumentException("The FieldName specified (" + FieldName + ") is not valid for the List (" + list.Title + ")."); result = list.GetItemById(id); if (result != null) result[FieldName] = Value; else throw new ArgumentException("There is no listitem with the specified ID (ID = " + ID + ")."); result.Update(); web.AllowUnsafeUpdates = false; } } }); return result; } Delete List Permissions namespace DeleteListPermissions { class Program { static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("\n\n Invocation: DeleteListPermissions "); return; } //Get SPWeb object SPSite Site = new SPSite(args[0]); //e.g., "http://myserver/mysite" SPWeb Web = Site.OpenWeb(); //Get SPListItem SPList List = Web.Lists[args[1]]; //e.g., "Announcements" Console.WriteLine("\n\nList " + args[1] + " found-- Starting Permission Deletion"); //Check for permission inheritance, and break if necessary if (!List.HasUniqueRoleAssignments) { List.BreakRoleInheritance(false); //pass true to copy role assignments from parent, false to start from scratch } List.Update(); Console.WriteLine("Done...."); } } }

Wednesday, March 17, 2010

STSADM Commands

Retract Solution: stsadm -o retractsolution -n YourWSP.wsp Remove Solution: stsadm -o deletesolution -n YourWSP.wsp Add Solution: stsadm -o addsolution -f YourWSP.wsp Deploy Solution: stsadm -o deploysolution -n YourWSP.wsp -allowgacdeployment -immediate at the End do: stsadm -o execadmsvcjobs iisreset pause

Monday, March 15, 2010

TimerJob, Feature Receiver, Feature and Batch Files to Install Timer Job

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace PubFormLibraryTimer {
public class FormLibraryTimerJob : SPJobDefinition
{
private const string Event_Source = "FormLibraryTimerJob";

 public FormLibraryTimerJob () : base() { }
  public FormLibraryTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType) : base (jobName, service, server, targetType) { }
public FormLibraryTimerJob(string jobName, SPWebApplication webApplication) : base (jobName, webApplication, null, SPJobLockType.ContentDatabase)
{ this.Title = jobName; }
public override void Execute(Guid targetInstanceId)
{
            DateTime fromTime = DateTime.Now.AddMinutes(-5);
DateTime toTime = DateTime.Now;
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];
SPList formsLibraryList = contentDb.Sites[0].RootWeb.Lists["YourFormLibrary"];
            SPQuery oQuery = new SPQuery();
            oQuery.Query = "" + toTime + "" + "" + fromTime + "";
SPListItemCollection collListItems = formsLibraryList.GetItems(oQuery);
this.LogEventMessage(collListItems.Count);
}

  private void LogEventMessage(int count)
{
if (!EventLog.SourceExists(Event_Source))
{ EventLog.CreateEventSource(Event_Source, "Application"); }
EventLog.WriteEntry(Event_Source, "Your Form Library Modified Forms Count In Last 5 mins - " + count.ToString(), EventLogEntryType.Information);
}
}
}






Feature Receiver:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace YourFormLibraryTimer
{

public class FormsLibraryTimerJobFeatureReceiver : SPFeatureReceiver
{
private const string LOGGER_JOB_NAME = "FormLibraryTimerJob"; public override void FeatureInstalled (SPFeatureReceiverProperties properties) { } public override void FeatureUninstalling (SPFeatureReceiverProperties properties) { } public override void FeatureActivated (SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) { if (job.Name == LOGGER_JOB_NAME) job.Delete(); } FormLibraryTimerJob loggerJob = new FormLibraryTimerJob(LOGGER_JOB_NAME, site.WebApplication); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.BeginSecond = 0; schedule.EndSecond = 59; schedule.Interval = 5; loggerJob.Schedule = schedule; loggerJob.Update(); } public override void FeatureDeactivating (SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) { if (job.Name == LOGGER_JOB_NAME) job.Delete(); } } } } Feature: ?xml version="1.0" encoding="utf-8" ? Feature Id="{DD1D417C-746B-4793-BA4E-A95F156E1E30}" Title="Form Library Timer Job" Description="Installs Form Library Timer Job" Version="1.0.0.0" Scope="Site" ReceiverAssembly="YourFormLibraryTimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=68d32dec24dfb1a9"ReceiverClass="YourFormLibraryTimer.FormsLibraryTimerJobFeatureReceiver" xmlns="http://schemas.microsoft.com/sharepoint/" / Installing Timer Job in Batch Files: @SET TEMPLATEDIR="c:\program files\common files\microsoft shared\web server extensions\12\Template" @SET STSADM="c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm" @SET GACUTIL="C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\gacutil.exe" Echo Installing PubFormLibraryTimer.dll in GAC %GACUTIL% -if bin\debug\YourFormLibraryTimer.dll Echo Copying files to TEMPLATE directory xcopy /e /y TEMPLATE\* %TEMPLATEDIR% %STSADM% -o installfeature -filename FormLibraryTimerJob\feature.xml -force %STSADM% -o activatefeature -filename FormLibraryTimerJob\feature.xml -force -url http://localhost:91IISRESET

Thursday, March 4, 2010

Adding Columns to a List Programatically

Add Columns / Fields Programmatically to a SharePoint List You can think of a SharePoint List somewhat similar to a table present within a Database. As tables consist of different columns, a SharePoint List also comprises of different columns / fields and these fields can indeed have different attributes associated to it (like "Required field check", "Max Length", "Display Formats", etc). We can use SharePoint API to create these fields and associate the corresponding attributes programmatically within an existing List. Provided below is a code snippet in C#.Net describing the same. using (SPSite oSPsite = new SPSite("http://Web-URL")) { oSPsite.AllowUnsafeUpdates = true; using (SPWeb oSPWeb = oSPsite.OpenWeb()) { oSPWeb.AllowUnsafeUpdates = true; /* get the SPList object by list name*/ SPList lst = oSPWeb.Lists["EmpList"]; /* create a Numeric field for EmpID */ SPFieldNumber fldEmpID = (SPFieldNumber)lst.Fields.CreateNewField( SPFieldType.Number.ToString(), "EmpID"); fldEmpID.Required = true; fldEmpID.DisplayFormat = SPNumberFormatTypes.NoDecimal; /* create a Text field for Name */ SPFieldText fldName = (SPFieldText)lst.Fields.CreateNewField( SPFieldType.Text.ToString(), "Name"); fldName.Required = true; fldName.MaxLength = 50; /* create a Date field for Dob*/ SPFieldDateTime fldDob = (SPFieldDateTime)lst.Fields.CreateNewField( SPFieldType.DateTime.ToString(), "Dob"); fldDob.DisplayFormat = SPDateTimeFieldFormatType.DateOnly; /* create a Currency field for Salary */ SPFieldCurrency fldSal = (SPFieldCurrency)lst.Fields.CreateNewField( SPFieldType.Currency.ToString(), "Salary"); fldSal.Currency = SPCurrencyFieldFormats.UnitedStates; fldSal.DisplayFormat = SPNumberFormatTypes.TwoDecimals; /* add the new fields to the list */ lst.Fields.Add(fldEmpID); lst.Fields.Add(fldName); lst.Fields.Add(fldDob); lst.Fields.Add(fldSal); /* finally update list */ lst.Update(); oSPWeb.AllowUnsafeUpdates = false; } oSPsite.AllowUnsafeUpdates = false; } Adding Hyperlink Column to a SharePoint List Example 1: Set the url field of a link Use the SPFieldUrlValue class to create an object that holds the url to link to, and the title to display: SPList list = web.Lists["Links"]; SPListItem newLink = list.Items.Add(); SPFieldUrlValue value = new SPFieldUrlValue(); value.Description = "Click Me"; value.Url = "http://www.microsoft.com/sharepoint"; newLink["URLColumn"] = value; //URLColumn that we have added on the list newLink.Update(); Example 2: Get the url field of a link Use the SPFieldUrlValue class to create an object that gets the url and description: SPList list = web.Lists["Links"]; SPListItem existingLink = list.Items[0]; SPFieldUrlValue value = new SPFieldUrlValue(existingLink["URL"].ToString()); string linkTitle = value.Description; string linkURL = value.Url; Example 3: Add Choice Column to a List or Document Library programatically Considering lstCustomList is your list object and you have set AllowUnsafeUpdate() to true for the web object. We are adding two choices in the choice column. First we will add choice column itself to the list and then we will add the choices in that column and update the field. The main point to taken in to consideration is that it is SPFieldChoice not the SPField. lstCustomList.Fields.Add("ABC", SPFieldType.Choice, false); lstCustomList.Update(); SPFieldChoice objChoiceCol = (SPFieldChoice)lstCustomList.Fields["ABC"]; string[] strdata = new string[2]; strdata[0] = "Open"; strdata[1] = "Close"; objChoiceCol.Choices.Add(strdata[0]); objChoiceCol.Choices.Add(strdata[1]); objChoiceCol.Update(); lstCustomList.Update();

Wednesday, March 3, 2010

Return Items from a List

(1)The following example returns all the items for a specified Events list. It assumes the existence of a text box that can be used to type the name of an Events list. SPWeb mySite = SPContext.Current.Web; SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items; for (int i=0;i"); } (2)You can also use one of the GetItems methods of the SPList class to return a subset of items from a list. The following example returns only Title column values where the Stock column value surpasses 100. SPWeb mySite = SPContext.Current.Web; SPList list = mySite.Lists["Books"]; SPQuery query = new SPQuery(); query.Query = "100"; SPListItemCollection myItems = list.GetItems(query); foreach (SPListItem item in myItems) { Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " "); } (3)Cross-List Queries You can perform cross-list queries to query more efficiently for data across multiple Web sites. The following example uses the SPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed". SPWeb webSite = SPContext.Current.Web; SPSiteDataQuery query = new SPSiteDataQuery(); query.Lists = ""; query.Query = "" + "Completed"; System.Data.DataTable items = webSite.GetSiteData(query); foreach (System.Data.DataRow item in items) { Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " "); }