Mittwoch, 28. November 2012

Sharepiont item level rights and a fluent Interface

Fluent Interfaces are a common thing nowdays, and evereyone who ever used Linq knows about them. Other products use them as well. But have you ever tried to write on on your own? Lately I did, and I found that there are different ways to do it depending on the situation where you are starting from.

My sceanrio was, that I wanted to implement a solution for running to set item permissions on a sharepoint list item. You need elevated privileges to do that if you are not an admin. Usually, in the ItemAdded event reciever you do it like so:

var item = properties.ListItem;
var web = properties.web;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
   using (SPSite oSite = new SPSite(web.Site.Url))
   {
     using (SPWeb oWeb = oSite.OpenWeb())
     {
       SPList oList = oWeb.Lists.GetList(item.ParentList.ID, false);
       SPListItem oItem = oList.Items.GetItemById(item.ID);

       oItem.BreakInheritedRights();
      
       SetRights(oWeb, oItem);
       
       oItem.Update();
     }
   }
});

You get the item and the web from the event properties. But in the delegate you must get a new instance of the web, the list and the item because the outside references are running in the low privileges context. The Method BreakInheritedRights is an extender that calls BreakRoleInhreitance on the item and removes all current RoleAssignments. The not shown method SetRights sets the actual rights to the item. I needed to do this for several lists and the above code was to obscure and hard to understand. So I decided to implement it something like that:

var item = properties.ListItem;
var web = properties.web;

SecurityHelper.RunWithElevatedPrivileges()
        .OnSite(web.Site.Url)
        .OnListItem(item.ParentList.ID, item.ID)
        .Execute(setItemPermissions);

This seemed to be more readable to me. So I was in  the lucky situation that this functionality was enterly new. So I have choosen the easiest way to do it: by creating a set of classes to build up your langauage. So I came up with the following set of classes:

public class SecurityHelper
{
  public static SecurityHelper RunWithElevatedPrivileges() { ... }
  public RunWithElevatedPrivilegesSiteContext OnSite(string url) { ... }
}


public class RunWithElevatedPrivilegesSiteContext
{
  public void Execute(Action<SPWeb> actionToRunElevated) { ... }
  public RunWithElevatedPrivilegesListItemContext OnListItem(Guid listId, int itemId) { ... }
}

public class RunWithElevatedPrivilegesListItemContext
{
  public void Execute(Action<SPWeb, SPListItem> executeOnListItem) { ... }
}

The static RunWithElevatedPrivileges method is the entry point. It allows us by calling the OnSite-Method to create a site context to execute elevated code, modeled throug the class RunWithElevatedPrivilegesSiteContext which gets passed in the site url. Using its Execute-Method we can run elevated code that only needs the web. If you want a list item to be in context, you have to call the OnListItem-Method to get a RunWithElevatedPrivilegesListItemContext instance. This allows you to pass in a callback expecting web and list item. This will be obtained by the Execute-Method in the following way:

public void Execute(Action<SPWeb, SPListItem> executeOnListItem)
{
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {
    using (SPSite site = new SPSite(_siteUrl))
    {
      using (SPWeb web = site.OpenWeb())
      {
        SPList list = web.Lists.GetList(_listId, false);
        SPListItem item = list.Items.GetItemById(_itemId);

        executeOnListItem(web, item);
      }
    }
  });
}

If things get more complex, you shoud prefer to define interfaces that define your language an implement them on your classes or you can use extensions methods like in LINQ.

Have a fluid coding!



Donnerstag, 20. September 2012

BASTA Follow-Up

Für alle die meine Sessions auf der Basta verfolgt haben und besonders für alle die sie nicht verfolgen konnten, hier die jeweiligen Folien und Beispiele.

TFS Express Slides

NoSQL vs. SQL Slides and Examples

Auch die versprochenen kleinen agile Tools die im TFS Express fehlen gibt es zum Download. Dazu einige bekannt Einschränkungen:

  • Funktioniert nur mit der englischen Scrum-Template Version.
  • Alle Operationen laufen synchron - eventuelle Wartezeiten (insb. beim starten) können vorkommen.
  • Die Software wird "as-is" geliefert - Nutzung auf eigene Gefahr.
Wer Fragen dazu hat, kann sich melden.

Viel Spaß damit!

HTTP 503 Error in TFS

The night before my TFS Express talk at the BASTA conference I faced an ugly error with my TFS Express installation. The installation ran fine, I could start management console, access the database but trying to access the website at localhost:8080/tfs yielded the 503 error.

As a result of a quick Google query I found out that there is plenty of discussion on the web about this topic, for example at StackOverflow or on MSDN. Some post state that they never found a solution for this, other show a long list of possible things to try - nothing worked for me.

By luck I found the solution to my problem. I used RavenDb on my machine before, which is running on port 8080 as well. Due to a different problem in Raven I had in mind that it does some urlacl-stuff by reserving an urlacl for the URL http://+:8080. This is used to assign rights for accesing this URL for the logged on user. If you face a 503 error when trying to use RavenDb with IIS deployment you should run the following command line:


netsh http delete urlacl http://+:8080/


It seems that running raven from the console does a urlacl reservation, which in turn makes TFS to stop working. The solution to the problem was similar to the solution mentioned on the RavenDb website. Run the above command line and TFS works fine - I assume RavenDb will no longer work properly.

This is neither a RavenDb mistake nor a TFS mistake - you should just configure these servers to run on different ports if they run concurrently.

Anyway this is one possible solutions out of a thousand and perhaps it might save someone some valuable time. Happy serving...




Sonntag, 16. September 2012

Creating a child task for a backlog item with TFS API

Because TFS Express lacks the agile planning tools of the full version, I was writing a small tool that makes creating tasks as children of a backlog item more enjoyable. It took me a while to figure it out, so I share my result.

First you need a reference to the team project collection:

var tfs = new TfsTeamProjectCollection(new Uri("https://your.tfspreview.com"));
tfs.EnsureAuthenticated();

var workItemStore = tfs.GetService<WorkItemStore>();

The the new task work item must be created. To instanciate a work item you must pass its type. You get this from the Project class.

var project = workItemStore.Projects["NameOfYourTeamProject"];
var taskType = project.WorkItemTypes["Task"];
var task = new WorkItem(taskType);
task.Title = "A new task"; 
task.State = "To Do";      
task.Save();

Next, we need to create a parent / child link. We need a WorkItemLinkTypeEnd instance that we can get from the WorkItemLinkType that we can get from the work item store like this:

var linkType = workItemStore.WorkItemLinkTypes["System.LinkTypes.Hierarchy"];
var taskLink = new WorkItemLink(linkType.ReverseEnd, task.Id);

The taskLink instance is a parent / child work item link whose reverse end (where it points to aka the child) points to the id of the task work item we created formerly. To connect the close end to the parent, the backlog item, we have to load it and put the link into its Links collection:

var backlogItem = workItemStore.GetWorkItem(backlogItemId);´
backlogItem.Links.Add(taskLink);
backlogItem.Save();

Thats it - the new task appears as a child of the backlog item (for example in the taskboard). Hope this may save someone some time :-)

Dienstag, 21. August 2012

Portable code between Silverlight, WPF and more

I had some talks about multi-targeting between WPF and Silverlight. The usual approach to achive this was to have one projects for each platform and use file linking to avoid duplicated code. This was working quite well but was a bit of a hassle as well.

With .NET 4.5 Micorsoft gave developers a new tool to solve the problem: portable libraries! There is a new project template called Portable Class Library. If you select it, a dialog box appears asking you which platforms should be targeted:


The selected settings can later be changed using the project properties. The class library can be directly referenced in a Silverlight project as well as in WPF, which was not possible before: an assembly targeted to the .NET Framework could not be referenced from Silverlight.

Some drawbacks...

As every nice feature, this has its drawbacks as well. Of course in the PCL project you can only use a subset of all supported plattforms. On MSDN is a list of supported features. A PCL project can not reference platform specific assemblies - it is limited to other PCL assemblies.
A major thing I miss in contrast to the old school multiple DLL with shared files approach is, that you can no longer use compiler directives to use platform specific code. Neither can you effectivly determine on what platform your code is running. On the one hand that is the idea of PCL, on the other hand it seems like a limitiation to me.

And a conclusion...

I think it all comes down to careful plannig and using the right tool for the right case. I think you can not discard the mulit-assembly approach completely if you want to get most out of mulit targetign. But PCL are a handy way to have real common code - the one that does not need to know the platform it is running on - in a common location. As suggested on MSDN, platform specific code can then be implemented in platform specific assemblies that inherit from your PCL base classes. This yields to a mixed mode between the old and the new approach.