Archive for May, 2010
Full trust proxies in SharePoint 2010
Because a sandboxed solution is completely isolated to its site collection only a subset of the Microsoft.SharePoint object model can be used. Only objects that operate within the current site collection are available to you, when you are building a sandboxed solution.
Sandboxed solutions run within a special process, the Sandbox Worker Process (SPUCWorkerProcess.exe). The sandbox worker process makes sure the artifacts from the solution can be used as though they were deployed to the server itself and it will enforce the limits of a Code Access Security (CAS) policy on the contents of the solution. The following permissions will be granted to the solution by the CAS policy:
- SharePointPermission.ObjectModel
- SecurityPermission.Execution
- AspNetHostingPermission.Level = Minimal
Ofcourse you need some more functionality from time to time. Here the full trust proxy solution comes in handy.
A Proxy Class has to be deployed at Farm level and can be used by everybody within the farm.
The full trust proxy solution exists of two classes:
The first class inherits from SPProxyOperation, the second class inherits from SPProxyOperationArgs.
Both of these are located in the Micorosft.SharePoint.UserCode namespace.
The class which inherits from SPProxyOperation implements the actual operation the full trust proxy solution has to perform.
The class which inherits from SPProxyOperationArgs defines the arguments which will be passed to the operation.
Let’s make an very simple application to write a message to an eventlog. First we’ll need a full trust proxy solution to write to the event log, second a sandboxed solution (webpart) which will tell what message the full trust proxy actually has to write.
Full trust proxy solution
First define a class which inherits from the SPProxyOperationArgs:
[assembly: AllowPartiallyTrustedCallers]
namespace FullTrustProxyProject1
{
[Serializable]
public class EventLogArgs : SPProxyOperationArgs
{
public string LogMessage { get; set; }
public string LogApplication { get; set; }
public string LogLevel { get; set; }
public EventLogArgs(string logMessage, string logApplication, string logLevel)
{
this.LogMessage = logMessage;
this.LogApplication = logApplication;
this.LogLevel = logLevel;
}
}
}
As you can see this is just a class to define arguments which will be passed to the proxy operation. The class has to be Serializable and AllowPartiallyTrustedCallers has to be set, because the class is going to be used between Trust Domains.
Next the operation of the full trust proxy, the receiver of the SPProxyOperationArgs:
namespace FullTrustProxyProject1
{
public class EventLogItemCreateOperation : SPProxyOperation
{
public override object Execute(SPProxyOperationArgs args)
{
if (args != null)
{
try
{
EventLogArgs arguments = args as EventLogArgs;
string result = SPLogger.AddEventLogEntry(arguments.LogApplication, arguments.LogLevel, arguments.LogMessage);
return result;
}
catch (Exception ex)
{
return ex.ToString();
}
}
else
{
return null;
}
}
}
}
In this class the Execute method is overridden and a check is performed for the incoming args. The args are then parsed to EventLogArgs and you can access the public properties of the EventLogArgs. The Execute method returns an object.
That’s all!
Register the full trust proxy
After implementation of these two classes the proxy has to be registered at the User Code Service in SharePoint. To do this you can use PowerShell or the Object Model.
I just made a simple Windows Forms application to register, unregister and list the registered proxies:
Register:
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(“FullTrustProxyProject1, version=1.0.0.0, Culture=neutral, PublicKeyToken=db3652199d4628cd”, “FullTrustProxyProject1.EventLogItemCreateOperation”);
service.ProxyOperationTypes.Add(getEventLogItemCreationOperation);
service.Update();
label1.Text = “Updated successfully!”;
}
else
{
label1.Text = “Update failed!”;
}
Unregister:
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
SPProxyOperationType getEventLogItemCreationOperation = new SPProxyOperationType(“FullTrustProxyProject1, version=1.0.0.0, Culture=neutral, PublicKeyToken=db3652199d4628cd”, “FullTrustProxyProject1.EventLogItemCreateOperation”);
service.ProxyOperationTypes.Remove(getEventLogItemCreationOperation);
service.Update();
label3.Text = “Removed succesfully!”;
}
else
{
label3.Text = “Remove failed!”;
}
And list all registered proxies:
SPUserCodeService service = SPUserCodeService.Local;
if (service != null)
{
int count = service.ProxyOperationTypes.Count;
label2.Text = “Proxy count: ” + count.ToString() + Environment.NewLine ;
foreach (SPProxyOperationType item in service.ProxyOperationTypes)
{
label2.Text += “AssemblyName: ” + item.AssemblyName + Environment.NewLine + “TypeName: ” + item.TypeName + Environment.NewLine;
}
}
Create the sandboxed solution
After deploying and registering the full trust proxy it can be used in a sandboxed solution:
Just create a webpart as you normally do, make sure this is a sandboxed solution. Create some controls, e.g.:
![]()
At the button click event all you have to do is:
EventLogArgs args = new EventLogArgs(box.Text, app.Text, logLevels.SelectedValue);
results.Text = SPUtility.ExecuteRegisteredProxyOperation(“FullTrustProxyProject1, version=1.0.0.0, Culture=neutral, PublicKeyToken=db3652199d4628cd”, “FullTrustProxyProject1.EventLogItemCreateOperation”, args).ToString();
Keep in mind!
Keep in mind that the full trust proxy runs under another process than the sandboxed solution. So if you want to debug the full trust proxy attach the SPUCWorkerProcessProxy.exe, do you want to debug the sandboxed solution, attach the SPUCWorkerProcess.exe.
When you redeploy your full trust proxy solution you have to restart the User Code Service because that’s where the full trust proxy is registered, don’t forget! I did…
To restart go to the Central Administration, Application Management, Manage services on server and find the Microsoft SharePoint Foundation Sandboxed Code Service. Stop and start this service again. Another option is to use “net stop SPUserCodeV4″, and start it again by using “net start SPUserCodeV4″.
How to add Sharepoint dll reference to Windows Forms application project in Visual Studio 2010?
When trying to add SharePoint.dll reference to a Windows Forms application in Visual Studio 2010 make sure you set the target framework to a non client profile.
If you don’t you’ll get the error message:
The type or namespace name ‘SharePoint’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?)
Also set the platform target to x64 at the Project Properties, Build section.
SharePoint in plain English
What is SharePoint?
Found a great movie on YouTube: SharePoint in Plain English.
I do like much of the ‘.. in Plain English’ movies! On the DNA project at FrieslandCampina we even made our own: ‘DNA in Plain English’. We did draw everything by hand, scanned the drawings, made a movie and added narration to it. Also thanks to my colleague Bert Paarhuis!
Unfortunately there is a lot of business information in this movie, so I can’t show it here.
SharePoint in Plain English
Sandboxed solutions
Sandboxed solutions are deployed to the database. This means that no files within the sandboxed solution will ever touch the file system of the server. Even dlls, xml files and aspx pages will be deployed to the database.
In Central Administration ensure that the Microsoft SharePoint Foundation Sandboxed Code Service is running on every server in the Farm where sandboxed solutions will be deployed and running.
Sandboxed solutions run within a special process, the Sandbox Worker Process (SPUCWorkerProcess.exe), part of this service.
The visually difference between a sandboxed and a farm solution in Visual Studio 2010 are:
- the property Sandboxed Solution (Project properties): true for sandboxed, false for farm solution
- AssemblyInfo.cs: [assembly: AllowPartiallyTrustedCallers()] is present in a sandboxed solution, not in a farm solution.
Sandboxed solution are wsp packages, deployed from solution gallery at site collection level by site collection administrators. The packages are isolated to site collection it is deployed to.
The solution gallery also displays resources consumed today and average usage the last 14 days.
When using sandboxed solutions a farm administrator can assign resource points to a site collection. The default quota is 300 points per day and points are calculated based on 14 different metrics:
| Resource | Description | Units | Resources per point | Limit |
| AbnormalProcessTerminationCount | Abnormally terminated process | count | 1 | 1 |
| CPUExecutionTime | CPU Execution Time for site | seconds | 3600 | 60 |
| CriticalExceptionCount | Critical Exception Events | Events | 10 | 3 |
| InvocationCount | Solution Invocation Events | Events | <TBD> | <TBD> |
| PercentProcessorTime | % CPU usage by solution | % | 85 | 100 |
| ProcessCPUCycles | Solution CPU cycles | cycles | 1×10^11 | 1×10^11 |
| ProcessHandleCount | Windows handles count | items | 10000 | 10000 |
| ProcessIOBytes | Windows handles count | items | 0 | 1×10^8 |
| ProcessThreadCount | Thread count in overall process | Thread instances | 10000 | 200 |
| ProcessVirtualBytes | Memory consumed | Bytes | 0 | 1×10^9 |
| SharePointDatabaseQueryCount | Number of SharePoint database queries | Query instances | 20 | 100 |
| SharePointDatabaseQueryTime | Elapsed time to execute query | seconds | 120 | 60 |
| UnhandledExceptionCount | Number of unhandled exceptions | Unhandled exception instances | 50 | 3 |
| UnresponsiveProcessCount | Number of unresponsive processes | Unresponsive process instances | 2 | 1 |
These metrics were chosen because they impact the health and stability of the server. The use of resources that have a higher impact on the server will cost you more points.
When the sandboxed solutions in a site collection use more than the assigned amount of points in a single day the sandboxed solutions in that particular site collection are shut down by SharePoint. This means that end users won’t be able to use the functionality of any sandboxed solution in that specific site collection until the resource points are reset. The following message will be displayed to the user:

The quota is per day, so after 24 hours the site collection will be unlocked and sandboxed solutions in that site collection can be used again. These 24 hours can be adjusted because this is a timerjob default scheduled every 24 hours: Solution Daily Usage Update.
Some important notes:
- resource quota’s can be exceeded through high usage and can be an indicator of poorly written code e.g. the UnhandledExceptionCount, but this isn’t necessarily an indicator e.g. SharePointDatabaseQueryCount.
- resource quota’s can be exceeded for a period of time, because the resource usage is calculated by timerjobs, these have to run first to update the resource usage calculation.
- resource quota’s can be adjusted. You can define a new quota template (CA, App man, Specify Quota Templates, Create a new quota template and connect this template to a site collection: CA, App man, Configure quota’s and locks, select the site collection and the quota template to use) with other settings of maximum points, but this will impact the health and stability of the server.
- sandbox code will not be terminated mid-execution.
Timerjobs involved (for every web application):
- Solution Daily Usage Update (Marks the daily boundary for sandboxed solution resource quota monitoring, every day)
- Solution Resource Usage Log Processing (Aggregates resource usage data from sandboxed solution execution, every 5 minutes)
- Solution Resource Usage Update (Records resource usage data from sandboxed solution execution, and sends email to owners of site collections that are exceeding their allotted resource quota, every 15 minutes)
The Solution Gallery displays an overview of the solutions with status (activated or not) and the used resources per solution:

Unfortunately there is no drill down on this overview, so you can’t see which resource is heavily used in a particular solution.
jQuery SPServices is null or not an object
Accessing a SharePoint list with the jQuery SPServices is very cool and neat! But I just discovered an issue with it:
Sometimes you get a message: ‘SPServices’ is null or not an object.
Make sure you reference the ‘base’ jquery first, then the services js file:
<script type=”text/javascript” src=”ICTLibrary/jquery.3.2.min.js”></script>
<script type=”text/javascript” src=”ICTLibrary/jquery.SPServices-0.5.4.min.js”></script>
<script language=”javascript” type=”text/javascript”>
var userName = “”;
$(document).ready(function()
{
alert(“ready”);
userName= $().SPServices.SPGetCurrentUser({
fieldName: “Title”
});
alert(userName);
});
</script>
AND make sure you close all tags and functions properly!!
Programmatically change the value of a lookup column
Lookup values are internally referenced as a combination of ID(int) and field value(string) in the following format: 1;#FirstItem.
The class offered by SharePoint for lookup values is SPFieldLookupValue. The method SPFieldLookupValue takes 1 or 2 values:
- “1;#FirstItem” (string)
- lookupId and lookupValue. Obviously the lookupId represents the field’s ID, lookupValue represents the field’s value.
Obviously you have to know the ID and value of the new item to set to the lookup field.
To enumerate all the possible items of the lookup list:
string itemsListed = string.Empty;
SPListItemCollection sources = web.Lists["Source"].Items;
foreach (SPListItem item in sources)
{
itemsListed += item["ID"].ToString() + “;#” + item["Title"].ToString() + System.Environment.NewLine;
}
An example of the content of itemsListed:
1;#FirstItem
2;#SecondItem
3;#ThirdItem
To search for a specific item you can use a CAML query:
SPQuery query = new SPQuery();
string toSearchFor = “ThirdItem”;
query.Query = “<Where><Eq><FieldRef Name=’Title’ /><Value Type=’Text’>” + toSearchFor + “</Value></Eq></Where>”;
SPListItemCollection collection = web.Lists["Source"].GetItems(query);
If(collection.Count == 1)
{
int idOfItem = int.Parse(collection[0]["ID"].ToString());
string totalLookup = idOfItem.ToString() + “;#” + toSearchFor;
}
Developer Dashboard
The Developer Dashboard is great to see what’s going on when loading a page in SharePoint 2010.
Windows PowerShell is THE application to enable/disable the Developer Dashboard in SharePoint 2010. Here are the commands:
$service=[Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashBoardSettings;
$service.DisplayLevel = “On”;
$service.Update();
The displaylevel can be On, Off or OnDemand. When set to OnDemand an icon is added to the top right corner to toggle the On/Off state of the Developer Dashboard (enlarged):

The DisplayLevel is an enumerator used to specify behavior aspects of the Developer Dashboard, check also MSDN:
| Member | Description |
| Off | Enumeration value = 0: Dashboard feature is disabled |
| OnDemand | Enumeration value = 1: Dashboard feature is available on request |
| On | Enumeration value = 2: Dashboard feature is enabled |
When you receive the following error:
Unable to find type [Microsoft.SharePoint.Administration.SPWebService]: make sure that the assembly containing this type is loaded.
Two solutions:
- You are running Windows PowerShell in stead of SharePoint 2010 Management Shell:
use SharePoint 2010 Management Shell. - You are running Windows PowerShell in stead of SharePoint 2010 Management Shell:
make Windows PowerShell behave like the SharePoint 2010 Management Shell by running ‘add-pssnapin microsoft.sharepoint.powershell’ in Windows PowerShell.
Want to include some of your own code in the monitoring of the dashboard?
Just wrap it up in a new SPMonitoredScope:
using (SPMonitoredScope scope = new SPMonitoredScope(“MyMonitoring”))
{
//your code to monitor here
}
Web analytics
Web analytics in SharePoint 2010 has improved a lot in comparison with the Site Usage Statistics in SharePoint 2007!
View report in Central Administration
Central Administration, Monitoring, Reporting, View Web Analytics report. In the next screen select the web application you want to analyze. Make sure the Web Analytics Service Application and Proxy are started (CA, Application Management, Manage service applications) and the Web Analytics Web Service and Web Analytics Data Processing Service (CA, Application Management, Manage services on server).
Web analytics timerjobs
Web Analytics Trigger Workflows Timer Job
Health Analysis Job (Daily, Web Analytics Data Processing Service, Any Server), Runs SharePoint Health Analyzer jobs.
Health Analysis Job (Daily, Web Analytics Web Service, Any Server), Runs SharePoint Health Analyzer jobs.
Anyone knows what the separate jobs are for?
View report on a site
Site Actions, Site Settings, Site Web Analytics Reports/Site Collection Web Analytics Reports at heading Site Actions.
Reports overview
| Report | Site report | Site Collection report | Web application report | Date range | Site scope(1) | Filter | Export | Workflow(2) |
| Summary | v | v | v | v | v | x | v | v |
| Traffic: | ||||||||
| Number of Page Views | v | v | v | v | v | x | v | v |
| Number of Daily Unique Visitors | v | v | v | v | v | x | v | v |
| Number of Referrers | v | v | v | v | v | x | v | v |
| Top Pages | v | v | v | v | x | v | v | v |
| Top Visitors | v | v | v | v | x | v | v | v |
| Top Referrers | v | v | v | v | x | v | v | v |
| Top Destinations | v | v | v | v | x | v | v | v |
| Top Browsers | v | v | v | v | x | v | v | v |
| Search: | ||||||||
| Number of Queries | x | v | v | v | x | v | v | v |
| Top Queries | x | v | x | v | x | v | v | v |
| Failed Queries | x | v | x | v | x | v | v | v |
| Best Bet Usage | x | v | x | v | x | v | v | v |
| Best Bet Suggestions | x | v | x | x | x | v | v | v |
| Best Bet Suggestions Action History | x | v | x | x | x | v | v | v |
| Inventory: | ||||||||
| Storage Usage | x | v | x | v | x | x | v | v |
| Number of Sites | v | v | x | v | v | x | v | v |
| Number of Site Collections | x | x | v | v | x | x | v | x |
| Top Site Product Versions | v | v | x | x | v | v | v | v |
| Top Site Languages | v | v | x | x | v | v | v | v |
| Customized Reports | v | v | v |
(1) only Site report
(2) only Site and Site Collection report
Report samples
Top Browsers
One note at the Top Browsers report: My development environment has IE8 installed as the only browser… what about Unknown and Netscape in the listing of browsers?
Web analytics workflows
At Site and Site Collection report level workflows can be added to keep track of specific Web Analytics data changes (Web Analytics Alerts) and selected reports (Web Analytics Reports) can be scheduled to be e-mailed to reviewers. You must have the View Web Analytics Data permission to start these workflows.
The settings for the Web Analytics Alerts (watch the and/or):

Several conditions with values can be set to generate the alert you want!
The settings for the Web Analytics Reports:
Watch the reports listed, these are all the reports available at site collection level, because site collection is selected at Site Scope. Changing the scope to This Site Only the site reports (only Traffic reports) will be displayed here.
Web analytics webpart
The Web analytics webpart is an Out Of The Box (OOTB) webpart to display the results on a page. Compared to the reports this webpart is limited.
The webpart displays the most viewed content, most frequent search queries from a site, or most frequent search queries from a search center. Other settings are the Site Scope: This Site Collection, This Site and Subsites and This Site only; Period: 24 hours – 180 days; Item Limit: max 100; Exclude items with a certain title and six options to set on how to show the results in the webpart. A nice feature is the RSS feed!
Customize rating icons for SharePoint 2010
- 2 images for displaying rating:
ratings.png

ratingsrtl.png

- 2 images for hovering/selecting rating (enlarged):
ratingsempty.png
ratingsnew.png
You can find these images in the 14 hive, images folder.
Make your custom icons (16×16), I prefer (the free) Paint.NET program. Just open the original icons, save them with another name and make your own of them.
How to change these images by SharePoint Designer

How to change these images by a feature
Create an empty SharePoint 2010 project with Visual Studio 2010 and add a site collection scoped feature.
Add a SharePoint Images Mapped folder and add your images to this folder. Note: Visual Studio adds a subfolder with the name of your project to your and SharePoint’s images are not messed up, nice!
Add an event receiver to your feature to set the properties of the images.
Uncomment the FeatureActivated method and add code:
SPSite site = properties.Feature.Parent as SPSite;
SPWeb web = site.RootWeb;
//preserver original ones
web.AllProperties["ratings_imagestripurl_original"] = web.AllProperties["ratings_imagestripurl"];
web.AllProperties["ratings_newratingiconurl_original"] = web.AllProperties["ratings_newratingiconurl"];
web.AllProperties["ratings_emptyiconurl_original"] = web.AllProperties["ratings_emptyiconurl"];
//set new ones
web.AllProperties["ratings_imagestripurl"] = “_layouts/images/ITIdea.CustomRatings/RatingsFC.png”;
web.AllProperties["ratings_newratingiconurl"] = “_layouts/images/ITIdea.CustomRatings/RatingsNewFC.png”;
web.AllProperties["ratings_emptyiconurl"] = “_layouts/images/ITIdea.CustomRatings/RatingsEmptyFC.png”;
web.Update();
Uncomment the FeatureDeactivating method and add code:
SPSite site = properties.Feature.Parent as SPSite;�
SPWeb web = site.RootWeb;�
web.AllProperties["ratings_imagestripurl"] = web.AllProperties["ratings_imagestripurl_original"];�
web.AllProperties["ratings_newratingiconurl"] = web.AllProperties["ratings_newratingiconurl_original"];
web.AllProperties["ratings_emptyiconurl"] = web.AllProperties["ratings_emptyiconurl_original"];
web.AllProperties.Remove(“ratings_imagestripurl_original”);
web.AllProperties.Remove(“ratings_newratingiconurl_original”);
web.AllProperties.Remove(“ratings_emptyiconurl_original”);
web.Update();
Deploy and activate the feature and recycle the application pool.
The new custom rating icons are visible and ready to use!
When you deployed the feature, check the Site Options in SharePoint Designer and you will see the original and newly added properties:

After deactivating the feature the original images are set again (and iisreset).







