SharePoint Web Services Wrapper

Recently I noticed that a common reason for developers to seek help on the MSDN forum is related to difficulties understanding and/or utilizing the SharePoint Web Services. You can’t blame the developers. It’s much more convenient to work with an Object Oriented API, rather than exchanging XML messages with a Web Service. For example, take a look at the Lists.asmx -> GetListItems. Of course it’s no rocket science, but it will sure save time if you could avoid dealing with the XML directly.


I spent some time researching if there is some kind of a library out there which provides ‘managed’ access to those Web Services. I.e. – work with .NET objects, rather than construct and parse XML elements. The closest thing I have found is this and it’s totally outdated and incomplete. At least it’s some reassurance to me that I am not missing the big picture and indeed, there might be people who would appreciate such framework.

So, I decided to start a project which will try to implement such .NET Object Oriented API around the SharePoint Web Services. Of course, for those corner weird cases (as well for the advanced developers), the underlying XML will still be accessible. Here is a good description of all the SharePoint services. My goal is to cover them all, eventually. I will start with the most commonly used ones.

It is hosted on CodePlex – http://spwebserviceswrapper.codeplex.com/
The project is not published yet, as there is no single line of code written yet. I will be doing this in my spare time. Once I shape it to my liking, it will become open source and everyone is welcome to contribute.

Got comments? Suggestions/Objections? There is a similar library already implemented? Please do let me know.

Hristo

SharePoint bug udating title of uploaded xml

Another interesting case…

Programmatically upload an xml file (extension should be .xml) to SharePoint document library. As soon as you upload it, try to change the Title field of the item.


So here is the code:

// We upload the file to SharePointSPFile file = Web.Files.Add(itemUrl, buff, true);Web.Update();

string newTitle = "Sample Title";SPListItem destItem = file.Item;destItem.File.CheckOut();// Try to change the titledestItem["Title"] = newTitle;destItem.UpdateOverwriteVersion();destItem.File.CheckIn(string.Empty,SPCheckinType.MinorCheckIn);

For any non-xml extension files it works, but for xml files the Title doesn’t change – it remains the same as the original name of the uploaded file. If you try doing this with another field of the item, it would work.

I came up with the following workaround:

SPFile file = Web.Files.Add(itemUrl, buff, true);Web.Update();

string newTitle = "Sample Title";SPListItem destItem = file.Item;destItem.File.CheckOut();destItem["Title"] = newTitle;destItem.UpdateOverwriteVersion();

// Work-around startdestItem["Title"] = newTitle;destItem.Update();// Workaround end

destItem.File.CheckIn(string.Empty, SPCheckinType.MinorCheckIn);

Anyone has clue what’s going on? Original MSDN forum thread is here.

Extending SharePoint Web Part

Hello!

SharePoint provides a lot of different out-of-the-box Web Parts. But sometimes we wish a particular web part behaved in a little different way, or have some small extra functionality. Or we may want to implement a heavily modified Web Part, based on already existing one.

Today, I will show you how to extend the functionality of an already existing web part.


We will take for example the SharePoint RSS Viewer. It loads an RSS feed and visualizes it in a web part on a SharePoint site. One of its visible properties in the UI is the Feed URL. It’s a static string and doesn’t allow any kind of dynamic parameters. Example:

Or

Those placeholders in my example are fictional, but you should get the idea of a dynamic value passed as a parameter to the service.

Our goal is to override the default behavior of the Feed URL field. We want to get to a point where we actually control how the Feed URL is being interpreted. We may want to replace placeholders with actual values, or do any other kind of adjustment of the URL, based on current and dynamic conditions. So here is the plan: we create a new web part, inherit the RSS Viewer web part and extend the Feed URL property.

Let’s start. Here is how the RSS View part settings look like in edit mode:

See the RSS Feed URL field? That’s what we are interested in.

Ok, start Visual Studio 2008 with the VSeWSS plugin installed. From the menu, start a new SharePoint -> Web Part project.

Give it a full trust

Change your namespace to something you prefer (for example, I will change it to HristoYankov). Rename the folder ‘WebPart1′ to ‘RSSAggregatorWebPartDynamicParam’. It will rename all classes and files for you. In the Solution Explorer, expand Properties and open AssemblyInfo.cs. Add this to the bottom:
[assembly: AllowPartiallyTrustedCallers]

and this to the top:
using System.Security;

Your Solution Explorer should look similar to:

Right click on your project, click on Properties, go to the Debug tab and set the SharePoint site URL you will be deploying to.

Open the RSSAggregatorWebPartDynamicParam.webpart file and set Title and Description to whatever you like.

Now, after your project is setup, starts the interesting part. Let’s inherit the RSS View control! What you need to do is…

Add this file as a reference – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\microsoft.sharepoint.portal.dll. This is where the RSS View class is defined.

Open your RSSAggregatorWebPartDynamicParam.cs file and change your class from this:
public class RSSAggregatorWebPartDynamicParam : System.Web.UI.WebControls.WebParts.WebPart

to that:
public class RSSAggregatorWebPartDynamicParam : RSSAggregatorWebPart

And add this statement:
using Microsoft.SharePoint.Portal.WebControls;

Basically, we no longer inherit the basic WebPart class. Instead, we now inherit the whole functionality of the RSS Viewer web part and all of its user interface!

You can also delete this function, as we are not going to do any changes there.
protected override void CreateChildControls()

So far so good. Now let’s override the Feed URL property! Add this to your class:

[DefaultValue(""),Resources("RSSWebpart_Property_FeedUrl_Text","RSSWebpart_ToolPart_Group","RSSWebpart_Property_FeedUrl_Description"),Personalizable(PersonalizationScope.Shared),WebBrowsable(true)]public new string FeedUrl{get{return base.FeedUrl;}set{base.FeedUrl = value;}}

And add this statement:
using System.ComponentModel;

Three things to note here:
1. The FeedUrl property is the one which handles the URL which points to the RSS feed.
2. Note the attribute on top of the property. If you don’t add it, it won’t be visible in the UI
3. Note the ‘new’ keyword. This way we hide the underlying base FeedUrl property.

Ok, now we have control over the Feed URL. What we should do, is change the way FeedUrl is being returned. Change your get to look like:

get{return OverrideURL(base.FeedUrl);}

And create this function:

private string OverrideURL(string url){// TODO: Process the URLreturn url;}

So, in OverrideURL we can change any way we like the URL that is set in the User Interface and then return it modified. At this point, it is up to you how to utilize this capability.

For the purpose of the example, let’s just look for the string #current_date# in the URL and replace it with the current date.

private string OverrideURL(string url){return url.Replace("#current_date#", DateTime.Now.ToShortDateString();}

At the end, your code should look like:

using System;using System.Runtime.InteropServices;using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint.WebPartPages;using Microsoft.SharePoint.Portal.WebControls;using System.ComponentModel;

namespace HristoYankov{[Guid("03badfa9-53e4-401a-bc60-28db88b202ac")]public class RSSAggregatorWebPartDynamicParam : RSSAggregatorWebPart{   public RSSAggregatorWebPartDynamicParam()   {   }

   [DefaultValue(""), Resources("RSSWebpart_Property_FeedUrl_Text", "RSSWebpart_ToolPart_Group", "RSSWebpart_Property_FeedUrl_Description"), Personalizable(PersonalizationScope.Shared), WebBrowsable(true)]   public new string FeedUrl   {       get       {           return OverrideURL(base.FeedUrl);       }       set       {           base.FeedUrl = value;       }   }

   private string OverrideURL(string url)   {       return url.Replace("#current_date#", DateTime.Now.ToShortDateString());   }}}

Now, right click your project and do ‘Deploy’. It should add a RSSAggregatorWebPartDynamicParam assembly to your GAC. When you go to your SharePoint site and do ‘Edit Page’ -> ‘Add Web Part’

you should be able to see your newly created web part listed in the pop up. Add it to the page. Put it in Edit Settings mode and set the Feed Url to something like:
http://servername/service/Param1=#current_date#

It will be replaced by:
http://servername/service/Param1=06/06/2009 (for example)

NOTE: I just noticed this – as soon as you set the URL which contains the ‘placeholder’, the web part which is still in edit mode starts showing it with a replaced value (the date). I believe that the underlying value is still http://servername/service/Param1=#current_date#. So perhaps, in the method OverrideURL we should be taking into consideration if the web part is in edit mode. And if it is – just return the original parameter that was passed. Something like:

private string OverrideURL(string url){if (this.NotInEditMode){// Not in edit mode, perform changesreturn url.Replace("#current_date#", DateTime.Now.ToShortDateString());}else{// We are in edit mode, return URL as isreturn url;}}

I will be checking this later. As usual, you can get the full source code here.

But basically that’s it. With minimum amount of code and effort, we have extended the functionality of an already existing web part, to something that serves our concrete needs.

Hope this was helpful!

SharePoint Solution Hello World Tutorial

Hi,

In this post, I will explain to you how to create your first SharePoint 2007 ASP.NET application. We will cover what tools you would need and what are the steps to creating a SharePoint Hello World app! I will keep the article short and clear on the necessary steps to be followed.


First, let’s start with the tools. You will need Visual Studio 2008 SP1 (preferably) this freely available plugin for it Visual Studio 2008 extensions for Windows SharePoint Services 3.0. It is a toolset for developing custom SharePoint applications: Visual Studio project templates for Web Parts, site definitions, and list definitions; and a stand-alone utility program, the SharePoint Solution Generator.

We assume that you have setup and you do have available a SharePoint site, on which we will be deploying our solution.

So, start your Visual Studio 2008. From the menu choose to start a new Project.

Visual Studio will show this window. Select GAC and proceed.

Your Solution Explorer would look like this, initially:

We need to create a couple of folders. Recreate the folder structure described in the screenshot below:

Right click on HelloSharePointWorld and select add new item. Select text file, but name it “Hello.aspx”

Put the following content in your newly created ASPX page.

<%@ Page Language="c#"Inherits="Hello, SharePointHelloWorld, Version=1.0.0.0,Culture=neutral, PublicKeyToken=3cf44204a7ad1f1e"MasterPageFile="~/_layouts/application.master"%>

<asp:Content ID="Content1"ContentPlaceHolderID="PlaceHolderMain"runat="server"><asp:Label ID="lblLabel1" runat="server" Text="Hello World!"></asp:Label></asp:Content>

Note the PublicKeyToken value. It will be changed later. Now, create a new class in the App_Code folder. Name it Hello.aspx.cs. Your directory structure should look like:

The content of your Hello.aspx.cs should read:

using System;using Microsoft.SharePoint.WebControls;

public partial class Hello : LayoutsPageBase{ protected void Page_Load(object sender, EventArgs e) { }}

Right click on your project, select Properties from the menu. Go to the Debug tab and set the hostname and port number of the SharePoint site where you want your project to be deployed.

Then save.

Now, right click on your project in Solution Explorer and rebuild it. Then right click on it and Deploy.

Now, open Windows Explorer and navigate to C:\WINDOWS\assembly. You should see an assembly called SharePointHelloWorld there. Right click it and select Properties.

Copy the Public Key Token (highlighted, note that it would be different for you) and click Cancel button. Now go back to your ASPX page in the project and replace the incorrect Public Key Token with the one you just copied.

Redeploy your application. Start Internet Explorer and navigate to http://%5Bserver name]:[port]/_layouts/HelloSharePointWorld/Hello.aspx

You should see something similar to:

Congratulations, you have created your first SharePoint solution. If you start the Central Admin for SharePoint and go to Operations -> Solution Management you should see a solution named sharepointhelloworld.wsp.

Let’s add one more modification. Open the Hello.aspx.cs file and change it to:

using System;using Microsoft.SharePoint.WebControls;using System.Web.UI.WebControls;

public partial class Hello : LayoutsPageBase{ protected Label lblLabel1;

 protected void Page_Load(object sender, EventArgs e) {     lblLabel1.Text = "Hello world! Time is: " +     DateTime.Now.ToString(); }}

By that, we utilize the code behind to output data on the screen. Rebuild, redeploy and refresh the page.

This is a good starting point for further learning by experimenting and example.

Of course, the full code for this project can be found here.

SharePoint 2010 overview

SharePoint is a collection of products and software tools by Microsoft that mainly provides collaboration functions, process management, searching and document management. Currently, the most popular version is SharePoint 2007. At this very moment Microsoft is working very hard on releasing the next version of the product – SharePoint 2010. This article will try to cover areas such as: what new features will be there, what changes from developer’s standpoint, what are the requirements, release date and others.

Naming
The product is no longer code-named “14″. The official name is Microsoft SharePoint Server 2010. The ‘Offfice’ part of the name finally drops out. The Office brand will no longer include Server side components (such as SharePoint). It now clearly refers to the client applications, such as Word, Excel and etc.

On a separate note, Exchange 2010 will be shipped separately of Office (beta is out already).

New Features

  • Groove (document collaboration application, acquired by Microsoft) is now being renamed and transformed into Microsoft Office SharePoint Workspace 2010.
  • SharePoint 2010 is not going to support Internet Explorer 6 (awesome). However, it will be supporting Firefox 3.x on Windows and perhaps even Firefox 3.x and Safari on non-Windows platforms.
  • Master Data Management (MDM) will be integrated with Office 14.
  • SharePoint 2010 will be able to interact with other CMS systems through CMIS.
  • You will be able to map SharePoint lists directly to database tables, which will provide great performance and scalability, especially on large lists.
  • There will be Silverlight support and maybe AJAX!
  • SharePoint Designer will support saving workflows to re-use for provisioning.
  • BDC might support Updating and Inserting data
  • Faceted Search
  • FAST Search for SharePoint. A new version of FAST Search for SharePoint at a lower cost.
  • “Web edit”“Microsoft has made it much easier for users to customize their own sites in SharePoint 2010. A new feature called Web edit allows site owners to edit their sites almost as if they were typical Office documents, making it easier for them to carry out common Web editing tasks like uploading and changing images or editing text.”
  • Other user-focused upgrades include the ability to use Office themes in SharePoint, for example by customizing a team site with the color palette of a SharePoint slide deck.
  • Read Visio documents in SharePoint
  • Improved administrative capabilities with a dashboard that uses the ribbon interface
  • Set of tools to monitor server farm health and data performance
  • Standardized UI across all Office products, browsers, mobile devices
  • Open API support


The free (and light) WSS version of the product will still be available, although there is no much information regarding it. Microsoft announced that it will get a lot of new features and will be a “great release”.


Developer tools
So, having said all that, what changes from the developer perspective? Is our life going to become easier, or even harder?

Microsoft announced “deep support for industry standards” and the main development tool will be Visual Studio 2010. It will ship with comprehensive support for development in all SharePoint areas – Web parts, features, solutions, content types, etc.

Deploy and debug from VS
You should be able to build, deploy and debug SharePoint applications directly from Visual Studio! If this is true, it will save us a lot of time!

Also, there will be a new Server Explorer window within VS, which we will use to explore SharePoint objects such as: Sites, Lists, Documents and other.

The Feature Designer embedded in Visual Studio 2010 will provide a detailed look at all the components of a Feature.

Package Explorer will provide you a WYSIWYG view to your package. You should be able to re-arrange items within the package by drag&drop!

There is extended support and integration of the Team System, if you are into this kind of a Source Control.

Requirements
It is a good idea to start getting prepared for this release of SharePoint, as it has very specific system requirements.

  • SharePoint 2010 will be 64-bit only
  • SharePoint Server 2010 will require 64-bit Windows Server 2008 or 64-bit Windows Server 2008 R2.
  • SharePoint Server 2010 will require 64-bit SQL Server 2008 or 64-bit SQL Server 2005.
  • As mentioned, IE 6 won’t be supported.

Out of the article:
So, what can you do today to get into the best shape for SharePoint Server 2010?
1. Start by ensuring new hardware is 64-bit. Deploying 64-bit is our current best practice recommendation for SharePoint 2007.
2. Deploy Service Pack 2 and take a good look at the SharePoint 2010 Upgrade Checker that’s shipped as part of the update. The Upgrade Checker will scan your SharePoint Server 2007 deployment for many issues that could affect a future upgrade to SharePoint 2010.
3. Get to know Windows Server 2008 with SharePoint 2007, this post is a great starting point.
4. Consider your desktop browser strategy if you have large population of Internet Explorer 6 users.
5. Continue to follow the Best Practices guidance for SharePoint Server 2007.
6. Keep an eye on this blog for updates and more details in the coming months.

And here are two interesting Q&As:

Q: Why are you only supporting the 64-bit versions of SQL Server 2005 or 2008 for SharePoint Server 2010?
A: This decision was based on our current test data for SharePoint Server 2010 and real world experience from customers running SharePoint Server 2007 with 32-bit SQL Server. SharePoint performance and scalability can benefit significantly from 64-bit SQL Server and the throughput increases are significant enough for us to make the difficult decision to only support SharePoint Server 2010 on 64-bit SQL Server 2005 or 2008. It has been our strong recommendation for some time that SharePoint Server 2007 customers take advantage of 64-bit SQL Server due to the inherent performance and scale benefits it can provide.

Q: Where can I find more information on the advantages of 64-bit hardware and guidance on how to migrate SharePoint from 32-bit to 64-bit.
A: These two TechNet articles are a good starting point;

Release date
According to Chris Capossela (senior vice president of Microsoft’s Information Worker Product Management Group) SharePoint 2010 will enter a technical preview in the third quarter of 2009 and will release to manufacturing in the first half of 2010.

Beta
Microsoft announced that it is now testing the software in an invitation-only technical preview, with a public beta to follow later this year. It focuses on a number of its enterprise customers and target specific enterprise deployment scenarios.

So, there is still some waiting to be done. But waste no time, instead, start preparing your 64-bit environments!

SharePoint regional settings double value bug

Here is an interesting one…

I had to set the regional settings of my SharePoint site to Hungarian, so the DateTime fields get localized properly. This has been discussed previously here.

However, I started experiencing problems with the double values. Explanation by example:
(myField is of type SPFieldNumber)


double myDouble = 123.45;
myField.DefaultValue = myDouble.ToString();

Basically, I am trying to assign the value of a type double variable as the default value of my SharePoint field (which I am about to render).

At this point, when I check (using Quick Watch in Visual Studio) the value of myField.DefaultValue it shows 123,45 (which is ok, for the localization I am using). However, myField.DefaultValueTyped shows 12345. Looks like SharePoint is ignoring the fact that the site is localized and does not consider ‘,’ to be in the role of a ‘.’

The solution I came up with is:
double myDouble = 123.45;
myField.DefaultValue = myDouble.ToString(CultureInfo.InvariantCulture);

Perhaps it is not the best, but at least the output now is:
myField.DefaultValue = “123,45″
myField.DefaultValueTyped = 123.45

Which is what is expected! Let me know if you know of a better way!

stsadm command line error

There is a common problem with stsadm being executed from the command line. For example, you run:
stsadm -o installfeature -name [featurename]

And you get “Command line error.” in the console. It is because you have copy/pasted the command from your browser or somewhere else. There is a problem with the encoding.

Solution: Type the command in the console window, don’t paste it.

Hope this helps.

Check if user belongs to K2 role

In your SharePoint (or other) / K2 solution, you may find yourself in a situation where you want to check if the current user belongs to a given K2 role. Perhaps, you want to allow only users who belong to particular K2 role to view a page, or you want to show a different page depending on the K2 role the user belongs to.


Surprisingly, K2 API does not provide a convenience method to do that. You have to implement it yourself. Even further, K2 Roles may contain ActiveDirectory groups and you will have to check if the current user belongs to them! In this article, we will discuss how all this is being done.

In the project where you will be implementing this method, make sure you have references to those libraries (which should be in the GAC):

  • SourceCode.HostClientAPI
  • SourceCode.Security.UserRoleManager.Management

First, let’s think about the signature of our method. It needs to return a boolean and receive a K2 role name as parameter:
public static bool CurrentUserBelongsToK2Role(string roleName)

That should do it. Now let’s start implementing the method. We need to get the name of the current user.
string loginName = WindowsIdentity.GetCurrent().Name;

(By the way, WindowsIdentity is in System.Security.Principal)

What we have so far is:
public static bool CurrentUserBelongsToK2Role(string roleName)
{
string loginName = WindowsIdentity.GetCurrent().Name;

// TODO: Implement further

return false;
}

Not much. We need to get an instance of K2′s UserRoleManager class. We will create a separate method which returns us an instance of this object:
public static UserRoleManager GetUserRoleManager()
{
UserRoleManager userRoleManager = new UserRoleManager();
userRoleManager.CreateConnection();
userRoleManager.Connection.Open(GetSCConnectionStringBuilder().ToString());

return userRoleManager;
}

And implement a second method, to get us a GetSCConnectionStringBuilder object.
public static SCConnectionStringBuilder GetSCConnectionStringBuilder()
{
SCConnectionStringBuilder connectionString = new SCConnectionStringBuilder();
connectionString.Authenticate = true;
connectionString.Host = ConfigurationSettings.AppSettings["K2Server"];
connectionString.Integrated = true;
connectionString.IsPrimaryLogin = true;
connectionString.Port = uint.Parse(ConfigurationSettings.AppSettings["K2ServerPort"]);

return connectionString;
}

Basically, this method will read K2Server and K2ServerPort keys from your config and use them for connection to K2. You are free to implement it any way you like. Now, when we have those two helper methods, we can finally do:
UserRoleManager userRoleManager = GetUserRoleManager();

Using the Role Manager, we will try to get an object representation of the K2 role we are checking against:
Role role = userRoleManager.GetRole(roleName);
if (role == null)
{
throw new Exception(“Role ” + roleName + ” not found!”);
}

So this piece of code will throw an exception in case the role we are trying to check does not exist. If it exists, our Role object will not be null. Now we need to enumerate the RoleItems within the role. Basically, it will give us all the users (or AD groups) included in this K2 role:
foreach (RoleItem roleItem in role.Include)
{
string currentRoleName = roleItem.Name;
}

Again, let’s see what we have so far:
public static bool CurrentUserBelongsToK2Role(string roleName)
{
string loginName = WindowsIdentity.GetCurrent().Name;

UserRoleManager userRoleManager = GetUserRoleManager();

Role role = userRoleManager.GetRole(roleName);
if (role == null)
{
throw new Exception(“Role ” + roleName + ” not found!”);
}

foreach (RoleItem roleItem in role.Include)
{
string currentRoleName = roleItem.Name;

// TODO: Implement here
}

return false;
}

So far so good, at least we are now able to enumerate all items within a K2 role! Let’s keep going and finish the implementation as marked in bold above.

The currentRoleName object could be returned to us in the format of K2:DOMAIN\Name. We need to normalize it to DOMAIN\Name (i.e. remove the ‘K2:’ part).
if (currentRoleName.IndexOf(‘:’) > -1)
{
currentRoleName = roleItem.Name.Split(‘:’)[1];
}

Now… the roleItem object we have (in the foreach statement) is of base type RoleItem. There are two classes which inherit from it – UserItem and GroupItem. This means, the current roleItem could be any of the two, which will help us understand if we are dealing with a single user or an ActiveDirectory group added to the K2 role. Let’s detect this:
if (roleItem is UserItem)
{
// TODO: Implement
}
else if (roleItem is GroupItem)
{
// TODO: Implement
}

Now we know when we are dealing with user and when with AD group. We just need to implement both cases. Implementing the UserItem case is as easy as comparing the currentRoleName to the loginName:
if (currentRoleName.ToLower() == loginName.ToLower())
{
// Found a USER match
userRoleManager.Connection.Close();
return true;
}

Implementing the GroupItem case is a little bit trickier. First, we need to implement a method which will return us a string array of the AD groups the current user belongs to, so we can later compare against them. Here is the code you will need:
private static string[] GetCurrentUserADGroups()
{
List groups = new List();

// Get the Groups of the current user
foreach (IdentityReference group in WindowsIdentity.GetCurrent().Groups)
{
// Ad the group to the list
NTAccount ntAcctGroup = group.Translate(typeof(NTAccount)) as NTAccount;
groups.Add(ntAcctGroup.Value.ToLower());
}

return groups.ToArray();
}

With the help of this method, we can get back to the implementation of the GroupItem case now:
else if (roleItem is GroupItem)
{
string[] loginNameADGroups = GetCurrentUserADGroups();
}

Then, we simply check if the loginNameADGroups contain the currentRoleName string (which in this case is an AD group).
if (loginNameADGroups.Contains(currentRoleName.ToLower()))
{
userRoleManager.Connection.Close();
return true;
}

And at the end of our CurrentUserBelongsToK2Role method we just have to add:
// No match found
userRoleManager.Connection.Close();
return false;

And that’s all! So, let’s see now how the whole thing looks:
public static bool CurrentUserBelongsToK2Role(string roleName)
{
string loginName = WindowsIdentity.GetCurrent().Name;

UserRoleManager userRoleManager = GetUserRoleManager();

Role role = userRoleManager.GetRole(roleName);
if (role == null)
{
throw new Exception(“Role ” + roleName + ” not found!”);
}

foreach (RoleItem roleItem in role.Include)
{
string currentRoleName = roleItem.Name;

// Is it K2:DOMAIN\Name ?
if (currentRoleName.IndexOf(‘:’) > -1)
{
// Get DOMAIN\Name
currentRoleName = roleItem.Name.Split(‘:’)[1];
}

if (roleItem is UserItem)
{
if (currentRoleName.ToLower() == loginName.ToLower())
{
// Found a USER match
userRoleManager.Connection.Close();
return true;
}
}
else if (roleItem is GroupItem)
{
string[] loginNameADGroups = GetCurrentUserADGroups();

if (loginNameADGroups.Contains(currentRoleName.ToLower()))
{
userRoleManager.Connection.Close();
return true;
}
}
}

// No match found
userRoleManager.Connection.Close();
return false;
}

Of course, you can find the whole project attached here.

How to create a K2 SmartObject

How does K2[blackpearl] integrate with other systems? One standard way to do this is through Web Services. And how does K2[blackpearl] integrate with Web Services? It is done through SmartObjects. So we have: K2 SmartObject Web Service Other System


“A K2 SmartObject can encapsulate data that does not currently reside in an existing system, such as data about an employee’s extracurricular activities, his or her family, or hobbies and interests. By using a SmartObject for employee information, all data about an employee is accessed in the same place, and updates are applied to the data at its source. It is important to remember that SmartObjects do not store or cache data. Once created, a SmartObject can be used and reused in a variety of ways; within K2 Designer for Visio, integrated for use in an InfoPath form, a workflow deployed via K2 Studio, in a report, in SharePoint, etc.”

SmartObject is all that and also it is the link between K2 and Web Services. So let’s see step by step how do we consume a Web Service method.

1. Create Web Service
First, let’s create a simple web service which we will be consuming later. For the purposes of the demonstration, it will be as simple as returning you the sum of two values.

I will use Visual Studio 2008 to create a new ‘ASP.NET Web Service Application’ project.

Let’s create the simple method ‘Sum’. See screenshot below:

Of course, you should test it first:

For the curious, it returned 3 ;)

Ok, now we need to publish it somewhere in the network and make sure we can access it! Right click the solution, Publish.

‘Publish’ it somewhere on your local hard drive and make sure you map it in IIS to a virtual directory. You can do that by going into IIS, choose existing site (or create a new one), right click on it -> New Virtual Directory, browse to the path where you Published the service and keep clicking Next.

Let’s assume you published your service to http://localhost:86/SampleService/SampleService.asmx, which in the local network (if you have one) maps to http://192.168.0.1:86/SampleService/SampleService.asmx.

We are done with the service, it’s in the network, it works, it is ready to be registered as a service instance.

2. From K2 Workspace add it to Dynamic Web Service
Ok, now we have to add it to the ‘Dynamic Web Services’ list. Open your K2 Workspace. Go to Management -> Management Console -> Expand the servername -> SmartObjects -> Services -> Dynamic Web Service.

Click on the Add button and populate the URL field.

Click Next. In the next screen set names to something that makes sense to you and click Save. Let’s call it ‘Sample Service’.

You have now registered a service instance. Let’s verify that by going to the K2 server and opening C:\Program Files\K2 blackpearl\ServiceBroker (or C:\Program Files (x86)\K2 blackpearl\ServiceBroker) and run BrokerManagement.exe. On the first screen, click on ‘Configure Services’.
Under services -> DynamicWebService -> serviceinstances there should be an instance with a name ‘SampleService‘.

3. Create SmartObject
We are good to create a SmartObject around it now. Start a new instance of Visual Studio and create a new K2 SmartObject project.

The first thing you do is switch to Advanced mode.

Then Remove All methods that were created for you. We will start from scratch.

Then click on +Add and run the wizard that shows up in Advanced mode (it’s a checkbox on the first page).

Name the method Sum, make it Read type.

In the next screen, Configure Method Parameters, we will add the two parameters that we have to pass to the method – intA and intB. Make them ‘Number’s.

At the end, it should look like this:

Click Next. On the next screen you have to select the Service Method we will be executing. This is easy. First click Add, to start adding a service method call to the SmartObject. A new popup will show. There is a field ‘Service Object Method’ and next to it there is a ‘…’ button. Click on the button. It will open the Context browser. Browse through ServiceObjects Server -> Sample Service -> Sum -> Read.

Click Add in the Context Browser. You will see:

We need to map some fields now. See the ‘a’ and ‘b’ input properties? They are the web service method input parameters. We have to ‘bind’ them to the intA and intB fields we created for the SmartObject.

Click on the first one (‘a’), click ‘Assign’ button and a small pop up will appear. Set ‘Map to’ to ‘SmartObject Method Parameter’ and from the second dropdown select ‘intA’.

Then click ok and do the same thing for ‘b’, but select ‘intB’ instead. For ‘ReturnValue’ – click on it, Assign, set ‘Map To’ to SmartObject Property (i.e. you are storing the result in a property of the SmartObject). Then click Create.

You should end up with:

Click OK and finish the wizard.

Make sure you name your SmartObject properly.

4. Deploy
Right click the solution and do Rebuild. It should compile with no errors. Let’s deploy the SmartObject to our K2 Server. Right click the project -> Deploy. Follow the wizard (Next, Finish) and your SmartObject should be deployed.

5. Test
Let’s test your SmartObject. Log into the K2 server and go back to C:\Program Files (x86)\K2 blackpearl\ServiceBroker. Run the file SmartObject Service Tester.exe.

Expand the SmartObjects section, find your SampleServiceSmartObject, expand it until you see the Sum method.

Right click on it, Execute method. Populate the input fields and click ‘Sum’ button. Promptly, you should see the result displayed.

We just invoked the SmartObject, which talked to the WebService, retrieved result for us and was visualized in the test utility. Everything works perfectly, your SmartObject is ready to be consumed from a workflow!

6. Consume in Workflow
Create a new K2 Process Project in Visual Studio. I will reuse the K2 solution we already have and just add the new project to it.

From the Toolbox, drag and drop a new SmartObject event. On the second page, Wizard will prompt you for SmartObject Method. Browse to our Sum method in the SampleServiceSmartObject.

Click Add. It should look like this:

On the next screen, you have to provide values for the SmartObject input properties. This could be K2 DataFields from your process, or actual hardcoded sample values. For the purpose of the demo, we will just bind them to ’2′ and ’54′. Select the property, click Assign button, set value, click ok. It should look like this:

On the next screen, we have to bind the return result to something. Let’s bind it to a DataField in the process which we will create. Click on the ReturnValue, click ‘Assign’, in the popup click on the ‘…’ button which will open the Context Browser. In this browser, either select already existing DataField, or create a new one on the fly (right click -> create). Make sure the field is Integer (for this demo). Select it, click ‘Add’, then ‘Ok’ in the pop up.

It should look like:

Click finish. You just finished adding a SmartObject event to your workflow. After this event is executed, you will have the value of ‘a’ + ‘b’ in the SumValue data field. I.e. you are consuming the SmartObject (and hence the Web Service).

Now you just need to finish the rest of the workflow ;)

7. Change the URL of the service
What if the address of your Web Service changes? Simple, go to the K2 server and open the C:\Program Files (x86)\K2 blackpearl\ServiceBroker folder. Run the BrokerManagement.exe app. On the first screen, click on ‘Configure Services’.

Find your service instance again:

Right click on it -> Configure Service. It will open a pop up. There you can change the URL field and click Save.

And that’s it, your service instance is now pointing to the right URL.

Basically that’s all. Now you know how to consume web services from your K2 Workflows, utilizing SmartObjects!

Hope this helps!

SharePoint bug tracking

So you have this SharePoint project you are working on… And as with any project, you need a bug tracker in order to communicate properly with the QAs and BAs in the company. What do you use? OnTime? Mantis? Bugzilla?

Why not SharePoint itself? It’s already (presumably) set up for you, users are familiar with it and you are only couple of steps away from setting up your own Issue Tracker.


To get it up and running, here is what you should do, step by step:
1. Open your SharePoint web site as admin

2. Click on ‘View All Site Content’ (usually top left) or open http://server:port/_layouts/viewlsts.aspx

3. Click on ‘Create’ to create a new list (shortcut: http://server:port/_layouts/create.aspx)

4. From the ‘Tracking’ column select ‘Issue Tracking’

5. Type in the name and description of the list where issues will be tracked

You may want to select ‘Yes’ on ‘Send e-mail when ownership is assigned’, to send emails to the users assigned to issues.

6. Click ‘Create’ button and your bug tracker is created. You should see a list with the name you have given on step 5. This is the tracker, open it. Click ‘New Item’ to see the default fields and their values you get.

7. Time to customize according to your needs. Go to the List Settings of your issue tracking list.

8. Scroll down to the Columns section. You will want to modify the highlighted columns – Issue Status, Priority and Category, for starter.

9. Click on any of them, let’s say ‘Issue Status’. Scroll down to the ‘Additional Column Settings’

You can now change the possible statuses your issues may have. For example, you may want to add ‘Acknowledged’, ‘Postponed’, ‘Invalid’, ‘Cannot fix’, etc… You may also change the default value or make the field required (a smart choice). When you are happy with your changes, click Ok.

10. Do the same for Category and Priority.

11. You can extend your tracker further, by adding extra columns. Let’s say, Product (as you may be working on different products at the same time) or Version (as your product may have many production versions). To do this, go to the Settings of the list again (as in step 7). Scroll down to columns and click Create Column.

12. Type in the name of your column and select its type. In this case, I will name it ‘Product Version’ and make it a dropdown list.

13. Make the column required (if you want to), specify the available choices and select the type of the control (dropdown, radio buttons or check boxes).

Then click Ok and you are all set.

14. Let’s test your bug tracker. Go to the list and create a new item

15. Fill all the fields you want to and click Ok. You have now logged a new Issue.

16. To customize your tracker further, you may want to create new Views, which sort and arrange the items in categories, assignees and what not

17. You may need to add users (give permissions) to the site or the list.

Now you have your own tracker, embedded in your SharePoint environment. Hope this was helpful!

SharePoint Development tools list

SharePoint development is not always as straight-forward as we all want it to be. However, there are a lot of tools which can make our job easier. Here is a list of some of our favorite tools for SharePoint development:


SharePoint Manager 2007
“The SharePoint Manager 2007 is a SharePoint object model explorer. It enables you to browse every site on the local farm and view every property. It also enables you to change the properties (at your own risk). This is a very powerfull tool for developers that like to know what the SharePoint holds of secrets. “

STSDEV: Simple Tools for SharePoint 2007 Development
STSDEV is a proof-of-concept utility application which demonstrates how to generate Visual Studio project files and solution files to facilitate the development and deployment of templates and components for the SharePoint 2007 platform including Windows SharePoint Services 3.0 (WSS) and Microsoft Office SharePoint Server 2007 (MOSS).”

WSPBuilder
“A SharePoint Solution Package (WSP) creation tool for WSS 3.0 & MOSS 2007″

Windows SharePoint Services 3.0 Tools: Visual Studio 2008 Extensions, Version 1.2
“Tools for developing custom SharePoint applications: Visual Studio project templates for Web Parts, site definitions, and list definitions; and a stand-alone utility program, the SharePoint Solution Generator.

U2U CAML Query Builder
“CAML (Collaborative Application Markup Language) is an XML-based query language that helps you querying, building and customizing Web sites based on Windows SharePoint Services. The XML elements define various aspects of a WSS site. The tool will help you build, test and execute your CAML Queries. “

I don’t think anybody wants to write CAML Queries ‘by hand’

SharePoint Timer Scheduler
“Sharepoint Timer Scheduler gives you a way of running your Timer Job from a list in the Root Web of your Sharepoint site. Excellent way of giving Site Administrators access to Timer Jobs so they can be run immediately or rescheduled. No need to code custom SPJobDefinition classes.”

Basically, this is a ‘tool’ which allows you to reschedule timer jobs without the need to redeploy a solution! Great!

Pako Simeonov’s Tool
Pako Simeonov wrote a great tool which fixes errors of the kind ‘Feature {Guid} for list template is not installed in this farm. The operation could not be completed’

What are your favorite tools?

SharePoint DateTime Format and Regional Settings

Now, how exactly do you control the DateTime string representation and formatting in a SharePoint application?

Normally, in an ASP.NET Web Application, it depends on the Regional Settings (Control Panel -> Regional and Language Options) of the user running the application pool of the site. Unless you override the Culture options in the code.


So when I tried to ‘localize’ the DateTime representation for my SharePoint site, by changing the app pool user’s Regional settings, at first I was surprised it didn’t do the job. DateTime was still shown in the default en-US format.

This means SharePoint overrided the Regional settings of its application pool user. It took me a couple of minutes before I realized that for SharePoint applications, the DateTime formatting is controlled by opening the site -> Site Actions -> Site Settings -> Site Administration (column) -> Regional Settings

There, you have the option to fine tune the regional settings for the site, which will also affect the DateTime formatting.

After setting it to the one you desire, you save the settings and next time you open the site, DateTime will be formatted according to the locale you have selected.

Hope this helps!

Follow

Get every new post delivered to your Inbox.