SharePoint Dragons

Nikander & Margriet on SharePoint

Monthly Archives: April 2012

Wanna deploy to a specific web application?

This is a question we regularly get questions about. Sometimes you’d really like to deploy a solution to a specific web app, but SharePoint won’t allow you to if your solution contains no resources scoped for a Web application.This article shows how to get out of this situation by adding a dummy control and tricking SharePoint to believe that the solution in fact contains web specific solutions: http://sharedpointers.blogspot.com/2011/03/deploying-solutions-to-specific-web.html

Claims in SharePoint 2010: the sequel

Or: Creating a claims provider, creating hierarchical claims, and assign permissions based on claims

This is a follow up to a previous article ( https://sharepointdragons.com/2012/01/30/claims-in-sharepoint-2010/ ) we’ve written. That article discusses how to set up a SharePoint site collection that supports claims authentication. To follow the sequel, you need to have set up such a site collection. From then on, we’ll take it one step further and discuss how to create a custom provider that issues custom claims and how to assign permissions to SharePoint objects based on such claims.

Why are we bothering you about claims, again?

After finishing our previous blog post about the topic of claims we leaned back and relaxed, enjoying our SharePoint site collection supporting claims authentication, and marveled at the sheer brilliance of our web part that displays all current claims. Then, Margriet got involved in a forum discussion at http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/415297a2-941b-411a-bfc5-e1045e0ae80e and we started realizing that the first article wasn’t enough and we had to go at least one step further.

In the aforementioned forum thread, a member of the Danish Defence IT Agency sought to implement a hierarchical claim. One that would be able to represent the following hierarchy:

  • Defence Department
    • Defence Command
      • IT Agency
        • Infrastructure
          • Server Applications
            • SharePoint

As we found out later, it’s a quite common request in military organizations to have a permission structure that is very hierarchical in nature, to have a wide variety of security clearances with a hierarchy associated to them.

Please note: For Jesper Schioett, don’t shoot us if we somehow wrongly represent your business case in this article, because seeing your profile picture at http://social.technet.microsoft.com/profile/schioett/?ws=usercard-hover we noticed that you actually can do exactly that!

One way to do that would be to create multiple claims that each represent an aspect of this hierarchy, like so:

http://claims/defence/2012/OrgLevel01 = Defence Deparment
http://claims/defence/2012/OrgLevel02 = Defence Command
http://claims/defence/2012/OrgLevel03 = IT Agency
http://claims/defence/2012/OrgLevel04 = Infrastructure
http://claims/defence/2012/OrgLevel05 = Server Applications
http://claims/defence/2012/OrgLevel06 = SharePoint

Another way would be to create a single claim and to put XML in it, like so: <l>Defence department<l>Defence Command</l></l>, which would work in scenarios where you’re programmatically iterating thru each claim (as is done in the claims web part in https://sharepointdragons.com/2012/01/30/claims-in-sharepoint-2010/), but unfortunately breaks down when you want to assign permissions to SharePoint objects based on such a claim.

Yet another way would be to use the hierarchical nature of URLs to come up with a scheme to capture the hierarchy. This is discussed in http://sharepoint.mindsharpblogs.com/NancyB/archive/2011/03/28/Custom-Claims-Providers[coln]-Hierarchical-Claims-[dash]-Part-2,-Setup-and-Claims-Augmentation.aspx However, we feel this is only a slight variation of the first approach where multiple claims are created to capture each aspect of the hierarchy. It does do a nice job of representing your actual hierarchy, so if that’s what your looking for it may still be the ideal approach for you.

At one point in the discussion, Jesper mentioned the following article: http://sharepointmetadataandclassification.typepad.com/blog/2012/03/building-a-custom-claim-provider-to-manage-security-clearances.html . It assigns multiple values to the same claim, and does an excellent job at implementing a hierarchical claim. It in fact uses another military example. While following the article, we’ve found it to be of good quality but, in our minds, it has two or three flaws (since, to our knowledge, the owner doesn’t own a machine gun we’re not afraid to point that out):

  • The code examples are screenshots. That sure was annoying.
  • Claims are added equally for everybody. We believe that even the most basic of claim provider implementations should provide some code for determining the current user.
  • The article stops too soon and doesn’t discuss what to do with these claims once set up.

Because of these shortcomings in an overall good article, we felt the need to redo parts of the article, keeping the original example intact (being fine as it is). This provides the added benefit that now the code can be copied and pasted (although we’ve put in minor changes), instead of retyped, and shows how to assign permissions to SharePoint objects based on the newly created claims.

Implementing a custom claim provider

Every SharePoint web application has a registered set of claim providers which are triggered every time authentication is performed. It doesn’t matter whether you log in using Windows authentication (NTLM or Kerberos), forms authentication (using an ASP.NET membership and role provider), or via a Security Token Service (STS, Active Directory Federation Services 2.0, or ADFS 2.0, is a good example of an STS) that issues SAML claims. In this example, we’ll create our own and add it to the existing set of claim providers. We’ve tested with both NTLM and forms authentication.

We’re not reiterating the steps listed in http://sharepointmetadataandclassification.typepad.com/blog/2012/03/building-a-custom-claim-provider-to-manage-security-clearances.html , they work and we’ll just provide our code for the implementation.

Please note: The FillClaimsForEntity method is, by far, the most interesting method to review.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.WebControls;

namespace LoisAndClark.Claims
{
    public class MyProvider : SPClaimProvider
    {
        public MyProvider(string displayName)
            : base(displayName)
        {

        }

        internal static string ProviderDisplayName
        {
            get { return “LoisAndClark My Claims Provider display name”; }
        }

        internal static string ProviderInternalName
        {
            get { return “LoisAndClark My Claims Provider internal name”; }
        }

        private static string ClearanceClaimType
        {
            get { return “http://schemas.loisandclark.eu/myclearance”; }
        }

        private static string ClearanceClaimValueType
        {
            get { return Microsoft.IdentityModel.Claims.ClaimValueTypes.String; }
        }

        protected override void FillClaimTypes(List<string> claimTypes)
        {
            if (claimTypes == null) throw new ArgumentNullException(“empty claimtypes”);

            claimTypes.Add(ClearanceClaimType);
        }

        protected override void FillClaimValueTypes(List<string> claimValueTypes)
        {
            if (claimValueTypes == null) throw new ArgumentNullException(“empty claim value type”);

            // claim value type = Microsoft.IdentityModel.Claims.ClaimValueTypes.String
            claimValueTypes.Add(ClearanceClaimValueType);
        }

        private string[] SecurityLevels = new string[] { “None”, “Confidential”, “Secret”, “Top Secret” };

        private bool DoesClaimValueAlreadyExist(List<SPClaim> claims, string claimType, string claimValue)
        {
            if (claims == null) throw new ArgumentNullException(“empty claims list”);
            if (String.IsNullOrEmpty(claimType)) throw new ArgumentNullException(“no claim type”);
            if (String.IsNullOrEmpty(claimValue)) throw new ArgumentNullException(“no claim value”);

            foreach (SPClaim claim in claims)
            {
                if (claim.ClaimType == claimType && claim.Value == claimValue) return true;
            }

            return false;
        }

        protected override void FillClaimsForEntity(Uri context, SPClaim entity, List<SPClaim> claims)
        {
            if (entity == null) throw new ArgumentNullException(“empty entity”);
            if (claims == null) throw new ArgumentNullException(“empty claims”);
            if (String.IsNullOrEmpty(entity.Value)) throw new ArgumentException(“no entityvalue”);

            // claim type = http://schemas.loisandclark.eu/myclearance
            bool top = DoesClaimValueAlreadyExist(claims, ClearanceClaimType, “Top Secret”);
            bool secret = DoesClaimValueAlreadyExist(claims, ClearanceClaimType, “Secret”);
            bool confidential = DoesClaimValueAlreadyExist(claims, ClearanceClaimType, “Confidential”);
            bool none = DoesClaimValueAlreadyExist(claims, ClearanceClaimType, “None”);

            // Entity value in Windows authentication scenario: 0#.w|loisandclark\administrator
            // Entity value in Forms authentication scenario: 0#.f|fbamembershipprovider|anton
            string currentUser = entity.Value.Substring(entity.Value.IndexOf(“|”) + 1);

            // Now, add claims based on the current user. This logic is omitted.

            // None
            claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[0], ClearanceClaimValueType));
           
            // Confidential
            claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[1], ClearanceClaimValueType));
           
            // Secret
            claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[2], ClearanceClaimValueType));
           
            // Top Secret
            claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[3], ClearanceClaimValueType));

            //if (confidential || secret || top) claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[1], ClearanceClaimValueType));
            //if (secret || top) claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[2], ClearanceClaimValueType));
            //if (top) claims.Add(CreateClaim(ClearanceClaimType, SecurityLevels[3], ClearanceClaimValueType));

        }

        protected override void FillEntityTypes(List<string> entityTypes)
        {
            entityTypes.Add(SPClaimEntityTypes.FormsRole);
        }

        protected override void FillHierarchy(Uri context, string[] entityTypes, string hierarchyNodeID, int numberOfLevels, SPProviderHierarchyTree hierarchy)
        {
            if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole)) return;
        }

        //protected override void FillHierarchy(Uri context, String[] entityTypes, String hierarchyNodeID, int numberOfLevels, SPProviderHierarchyTree hierarchy)
        //{
        //  if (String.IsNullOrEmpty(hierarchyNodeID))
        //  {
        //    hierarchy.AddChild(CreateHierarchyNodeForNodeID(MyLoginNameClaimType));
        //    hierarchy.AddChild(CreateHierarchyNodeForNodeID(MyClaimType));
        //  }
        //  else if (String.Equals(hierarchyNodeID, MyLoginNameClaimType, StringComparison.Ordinal))
        //  {
        //    hierarchy.Name = GetHierarchyNodeNameForNodeID(hierarchyNodeID);
        //  }
        //  else if (String.Equals(hierarchyNodeID, MyClaimType, StringComparison.Ordinal))
        //  {
        //    hierarchy.Name = GetHierarchyNodeNameForNodeID(hierarchyNodeID);
        //  }
        //}

        protected override void FillResolve(Uri context, string[] entityTypes, SPClaim resolveInput, List<PickerEntity> resolved)
        {
            if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole)) return;
        }

        protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List<PickerEntity> resolved)
        {
            if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole)) return;
        }

        protected override void FillSchema(SPProviderSchema schema)
        {
            schema.AddSchemaElement(new SPSchemaElement(PeopleEditorEntityDataKeys.DisplayName, “Display Name”, SPSchemaElementType.Both));
        }

        protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, SPProviderHierarchyTree searchTree)
        {
            if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole)) return;
        }

        public override string Name
        {
            get { return ProviderInternalName; }
        }

        public override bool SupportsEntityInformation
        {
            get { return true; }
        }

        public override bool SupportsHierarchy
        {
            get { return true; }
        }

        public override bool SupportsResolve
        {
            get { return true; }
        }

        public override bool SupportsSearch
        {
            get { return true; }
        }
    }
}

 

A custom claim provider needs to be registered via an event receiver based on SPClaimProviderFeatureReceiver. Step 9 of the article prescribes that you need to set the Receiver assembly and Receiver class properly. You can do that by setting:

  • The receiver assembly to $SharePoint.Project.AssemblyFullName$.
  • The receiver class to LoisAndClark.Claims.MyProviderEventReceiver.

We’ve implemented the event receiver responsible for registering our custom claim provider like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;

namespace LoisAndClark.Claims
{
    public class MyProviderEventReceiver : SPClaimProviderFeatureReceiver
    {
        private void ExecBaseFeatureActivated(SPFeatureReceiverProperties props)
        {
            base.FeatureActivated(props);
        }

        public override string ClaimProviderAssembly
        {
            get { return typeof(MyProvider).Assembly.FullName; }
        }

        public override string ClaimProviderDescription
        {
            get { return “my provider description”; }
        }

        public override string ClaimProviderDisplayName
        {
            get { return MyProvider.ProviderDisplayName; }
        }

        public override string ClaimProviderType
        {
            get { return typeof(MyProvider).FullName; }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties props)
        {
            ExecBaseFeatureActivated(props);
        }
    }
}

Once you deploy it and log in, you should see the new claims issued by our custom claim provider, as shown in the next Figure.

image

Two tips. One. Every time you’re changing your claim provider, deploy it and then perform an iisreset before changes are visible. Two. You can debug your custom claim provider by attaching to the w3wp process.

Assigning permissions to SharePoint objects

With all these brand new claims, the urge rises to do something useful with them. You can do this by assigning a claim to a SharePoint web site. We’ve done this twice, both for the claim values “None” and “Top Secret”. This is the code (again, we didn’t have to be very creative, we just borrowed and augmented (to use some claims terminology) the code from http://blog.mastykarz.nl/programmatically-granting-permissions-claims/):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //string permission = “None”;
            string permission = “Top Secret”;

            using (SPSite site = new SPSite(“http://astro:46454″))
            {
                using (SPWeb web = site.OpenWeb())
                { SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
                    if (claimMgr != null)
                    {
                        SPClaim claim = new SPClaim(
                            “http://schemas.loisandclark.eu/myclearance”,
                            permission,
                            Microsoft.IdentityModel.Claims.ClaimValueTypes.String,
                            SPOriginalIssuers.Format(SPOriginalIssuerType.ClaimProvider,
                            “LoisAndClark My Claims Provider internal name”));
                        string userName = claimMgr.EncodeClaim(claim);

                        SPUserInfo info = new SPUserInfo { LoginName = userName, Name = permission };
                        SPRoleAssignment roleAssignment = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes);
                        roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[“Read”]);
                        web.RoleAssignments.Add(roleAssignment);
                        web.Update();
                    }
                }
            }

        }
    }
}

You’ll see them again in the Groups list:

image

Or, in some ways, the user.aspx application page even shows it clearer:

image

After that, we created a custom list called MySecrets containing the items None and Top Secret:

image

If you want to see the None list item , you need to either be a site collection administrator or have the None claim. This can be seen in the next Figure:

image

To see the Top Secret list item, you’ll need to have the Top Secret claim (or be an administrator):

image

You can experiment with the custom claim provider and verify that this indeed works. Please note that in our example we’ve provided all claims for everyone. If you modify the example and only provide a None claim, you’ll see the difference. In our case, it’s poor Anton the forms user that has to suffer:

image

Conclusion

Claims are cool! But didn’t we all know this already?

Optimize with Aptimize?

A long time ago, we did a SharePoint 2001 project (yep, the first version) where we needed to support 40.000 people. Really hard to do since at that time SharePoint could not scale out and everything including the datatabase (the Exchange-based web storage system or WSS) had to be located on a single server. We used a 3rd party performance optimizer tool that really helped a lot.

We haven’t really kept track of such tools, but here’s one you can use for SharePoint 2010 today: Aptimizer ( http://www.riverbed.com/us/products/stingray/stingray_aptimizer.php ). It’s always nice to have a tool such as this as an option. Also check out http://social.technet.microsoft.com/wiki/contents/articles/7926.sharepoint-2010-tips-for-dealing-with-performance-issues-en-us.aspx it’s becoming a popular resource for checking tips about dealing performance issues. It’ll be updated if there’s any news on the 3rd party optimizer front.

The riddle of the five drop down lists with unique values

In a way, this post is a follow up of blog post https://sharepointdragons.com/2012/04/18/adding-jquery-to-a-visual-web-part-and-then-implement-parentchild-radio-buttons/. If you know your way around visual web parts or user controls, you don’t need to read it per se. If you don’t understand the contents of this post, it’s advisable to read it first.

Question: Suppose you have five drop down lists with an identical set of values (1-5 in this example), and suppose each selected value within this group of five lists needs to be unique. How do you implement that?

Answer: Well, a good way to that would be to use jQuery to handle the client-side validation, and implement a server-side version that kicks in if JavaScript is disabled or circumvented. The code below consists of a user control (.ascx) used in a visual web part and it’s code behind file.

Please note: The user control contains a CustomValidator control that doesn’t use the ControlToValidate property. This is because we’re not validating a specific control, instead we’re validating all list controls.This does mean that the Value property of the arguments parameter always contains an empty string.

Here’s the code for the user control (*.ascx):

<%@ Assembly Name=”$SharePoint.Project.AssemblyFullName$” %>
<%@ Assembly Name=”Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Register TagPrefix=”SharePoint” Namespace=”Microsoft.SharePoint.WebControls”
    Assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Register TagPrefix=”Utilities” Namespace=”Microsoft.SharePoint.Utilities” Assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Register TagPrefix=”asp” Namespace=”System.Web.UI” Assembly=”System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ %>
<%@ Import Namespace=”Microsoft.SharePoint” %>
<%@ Register TagPrefix=”WebPartPages” Namespace=”Microsoft.SharePoint.WebPartPages”
    Assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”VisualWebPart1UserControl.ascx.cs”
    Inherits=”VisualWebPartProject1.VisualWebPart1.VisualWebPart1UserControl” %>
<asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>
<SharePoint:ScriptLink ID=”ScriptLink1″ runat=”server” Name=”~sitecollection/SiteAssets/MyAssets/jquery-1.7.js” />

<script type=”text/javascript”>
    // Contains a list of priority values and the amount of occurrences.
    // E.g.: value 1 is selected 0 times, value 2 is selected 3 times.
    var _arrPrios;

    // Resets all priority values to zero occurrences.
    function Init() {
        // First is dummy entry, this makes it easier to understand the mapping between array index position and drop down list values.
        _arrPrios = [0, 0, 0, 0, 0, 0];
    }
   
    // Checks if all drop down lists contain a unique value.   
    function ValidateLists(src, args) {
        Init();
       
        // Select all priority drop down lists.
        $(“#divPrioLists select :selected”).each(function () {
            AddSelectedValue($(this).val());
        });
       
        // Skip first dummy entry (index = 0).       
        for (var i = 1; i < _arrPrios.length; i++) {
            if (_arrPrios[i] != 1) {               
                args.IsValid = false;
                return false;
            }
        }       

        args.IsValid = true;
    }

    // Count occurrences for every selected value (e.g. end user selected “1” 0 times, “2” 3 times.
    function AddSelectedValue(intValue) {
        _arrPrios[intValue] = ++_arrPrios[intValue];
    }
</script>

<asp:CustomValidator id=”CustomValidator2″ runat=”server” ErrorMessage = “All priority lists must have unique values”
ClientValidationFunction=”ValidateLists” OnServerValidate=”ValidateLists” >
</asp:CustomValidator>

<div id=”divPrioLists”>

<asp:DropDownList ID=”list1″ runat=”server”>
<asp:ListItem Text=”1″ Value=”1″ />
<asp:ListItem Text=”2″ Value=”2″ />
<asp:ListItem Text=”3″ Value=”3″ />
<asp:ListItem Text=”4″ Value=”4″ />
<asp:ListItem Text=”5″ Value=”5″ />
</asp:DropDownList>

<asp:DropDownList ID=”list2″ runat=”server”>
<asp:ListItem Text=”1″ Value=”1″ />
<asp:ListItem Text=”2″ Value=”2″ />
<asp:ListItem Text=”3″ Value=”3″ />
<asp:ListItem Text=”4″ Value=”4″ />
<asp:ListItem Text=”5″ Value=”5″ />
</asp:DropDownList>

<asp:DropDownList ID=”list3″ runat=”server”>
<asp:ListItem Text=”1″ Value=”1″ />
<asp:ListItem Text=”2″ Value=”2″ />
<asp:ListItem Text=”3″ Value=”3″ />
<asp:ListItem Text=”4″ Value=”4″ />
<asp:ListItem Text=”5″ Value=”5″ />
</asp:DropDownList>

<asp:DropDownList ID=”list4″ runat=”server”>
<asp:ListItem Text=”1″ Value=”1″ />
<asp:ListItem Text=”2″ Value=”2″ />
<asp:ListItem Text=”3″ Value=”3″ />
<asp:ListItem Text=”4″ Value=”4″ />
<asp:ListItem Text=”5″ Value=”5″ />
</asp:DropDownList>

<asp:DropDownList ID=”list5″ runat=”server”>
<asp:ListItem Text=”1″ Value=”1″ />
<asp:ListItem Text=”2″ Value=”2″ />
<asp:ListItem Text=”3″ Value=”3″ />
<asp:ListItem Text=”4″ Value=”4″ />
<asp:ListItem Text=”5″ Value=”5″ />
</asp:DropDownList>

</div>

<asp:Button ID=”btnSubmit”  runat=”server” Text=”Submit” />

Here’s the code for the code-behind file of the user control:

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

namespace VisualWebPartProject1.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {

        protected override void OnInit(EventArgs e)
        {           
            // At this point, on a postback, the page hasn’t been validated yet.
            // You could call Page.Validate() explicitly or follow the normal flow of events.           
        }

        protected override void OnLoad(EventArgs e)
        {
            // At this point, on a postback, the page hasn’t been validated yet.
            // You could call Page.Validate() explicitly or follow the normal flow of events.           
        }

        protected override void OnPreRender(EventArgs e)
        {
            // The page has been validated on a postback.
            if (Page.IsPostBack && Page.IsValid)
            {

            }
        }

        // Contains a list of priority values and the amount of occurrences.
        // E.g.: value 1 is selected 0 times, value 2 is selected 3 times.
        private int[] _arrPrios = { 0, 0, 0, 0, 0, 0 };

        /// <summary>
        /// Server-side validation is equivalent to jQuery version, but kicks in in case end user disables JavaScript,
        /// or maliscuously tries to circumvent client-side validation.
        /// </summary>
        protected void ValidateLists(object source, ServerValidateEventArgs args)
        {
            // Register all selected values for all priority lists
            AddSelectedValue(list1, list2, list3, list4, list5);

            // Skip first dummy entry (index = 0).       
            for (int i = 1; i < _arrPrios.Length; i++)
            {
                if (_arrPrios[i] != 1)
                {
                    args.IsValid = false;
                    return;
                }
            }       

            args.IsValid = true;
        }

        /// <summary>
        /// Count occurrences for every selected value (e.g. end user selected “1” 0 times, “2” 3 times.
        /// </summary>       
        private void AddSelectedValue(params DropDownList[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                var currentValue = Convert.ToInt32(args[i].SelectedValue);
                _arrPrios[currentValue] = ++_arrPrios[currentValue];
            }
        }
    }
}

Good link about SharePoint 2010 service accounts

When it’s time to plan your new SharePoint infrastructure, this article may come in handy: http://blog.falchionconsulting.com/index.php/2010/10/service-accounts-and-managed-service-accounts-in-sharepoint-2010/

Troubleshooting an SSRS report that times out

Just started a Wiki page that discusses what to do when you have a slow performing SSRS report. Everybody is more than welcome to contribute at http://social.technet.microsoft.com/wiki/contents/articles/9950.sharepoint-2010-best-practice-troubleshooting-an-ssrs-report-that-times-out.aspx

Convert SPMetal Linq query to CAML

As a follow up to article https://sharepointdragons.com/2012/04/21/how-to-check-if-the-current-user-has-already-created-a-list-item-of-a-certain-content-type/ , based on a reader’s question. This is a slightly updated version of the code that writes the underlying CAML to the console output window, like so:

astro.Log = Console.Out;

By explicitly calling it like so you’re exporting the CAML to a text file:

myconsole.exe > caml.txt

The complete code looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // Open entities context generated by spmetal
            // if a sharepoint context is available, use new AstroDataContext(SPContext.Current.Web.Url) instead.
            using (var astro = new AstroDataContext(“http://astro”))
            {
                var timeItems = (from item in astro.MyMetalList
                                                                        where item.GetType() == typeof(Timecard)
                                                                        select (Timecard) item);

                // Call it like this: myconsole.exe > caml.txt
                astro.Log = Console.Out;               

                // Enter specific user name in lambda expression below, for example using: SPContext.Current.Web.CurrentUser.LoginName
                int occurrences = timeItems.Where(item => item.UserName.ToLower() == “loisandclark\\administrator”).Count();
                if (occurrences == 0)
                {
                    Console.WriteLine(“it’s ok to add a request”);
                }
                else if (occurrences == 1)
                {
                    Console.WriteLine(“a request has already been submitted”);
                }
                else
                {
                    Console.WriteLine(“There are duplicate requests. This is an error, contact the administrator”);
                }

                foreach (var item in timeItems)
                {
                    Console.WriteLine(item.Title);
                }
            }
        }
    }
}

 

The resulting CAML looks like this:

<View><Query><Where><BeginsWith><FieldRef Name=”ContentTypeId” /><Value Type=”ContentTypeId”>0x01</Value></BeginsWith></Where></Query><ViewFields><FieldRef Name=”ID” /><FieldRef Name=”owshiddenversion” /><FieldRef Name=”FileDirRef” /><FieldRef Name=”Title” /><FieldRef Name=”ContentTypeId” /><FieldRef Name=”CustomerName_x003a__x0020_Compan” /><FieldRef Name=”CustomerName_x003a__x0020_FirstN” /><FieldRef Name=”CustomerName_x003a__x0020_LastNa” /><FieldRef Name=”MyCustWF” /><FieldRef Name=”URL” /><FieldRef Name=”Comments” /><FieldRef Name=”URLwMenu” /><FieldRef Name=”URLNoMenu” /><FieldRef Name=”Date” /><FieldRef Name=”DayOfWeek” /><FieldRef Name=”Start” /><FieldRef Name=”End” /><FieldRef Name=”In” /><FieldRef Name=”Out” /><FieldRef Name=”Break” /><FieldRef Name=”ScheduledWork” /><FieldRef Name=”Overtime” /><FieldRef Name=”NightWork” /><FieldRef Name=”HolidayNightWork” /><FieldRef Name=”Late” /><FieldRef Name=”LeaveEarly” /><FieldRef Name=”Oof” /><FieldRef Name=”ShortComment” /><FieldRef Name=”Vacation” /><FieldRef Name=”NumberOfVacation” /><FieldRef Name=”UserName” /><FieldRef Name=”PercentComplete” /><FieldRef Name=”Body” /><FieldRef Name=”StartDate” /><FieldRef Name=”TaskDueDate” /><FieldRef Name=”Priority” /><FieldRef Name=”TaskStatus” /><FieldRef Name=”AssignedTo” /><FieldRef Name=”DueDate” /><FieldRef Name=”Status” /><FieldRef Name=”Predecessors” LookupId=”TRUE” /><FieldRef Name=”FileLeafRef” /><FieldRef Name=”ItemChildCount” /><FieldRef Name=”FolderChildCount” /><FieldRef Name=”DocumentSetDescription” /><FieldRef Name=”Modified_x0020_By” /><FieldRef Name=”Created_x0020_By” /><FieldRef Name=”WikiField” /><FieldRef Name=”_vti_RoutingExistingProperties” /><FieldRef Name=”PreviewOnForm” /><FieldRef Name=”FileType” /><FieldRef Name=”ImageSize” /><FieldRef Name=”ImageWidth” /><FieldRef Name=”ImageHeight” /><FieldRef Name=”ImageCreateDate” /><FieldRef Name=”SelectedFlag” /><FieldRef Name=”NameOrTitle” /><FieldRef Name=”RequiredField” /><FieldRef Name=”Keywords” /><FieldRef Name=”Thumbnail” /><FieldRef Name=”Preview” /><FieldRef Name=”AlternateThumbnailUrl” /><FieldRef Name=”Description” /><FieldRef Name=”MyBcsName_x003a__x0020_FirstName” /><FieldRef Name=”MyySingleLineOfText” /><FieldRef Name=”MyMultiLines” /><FieldRef Name=”MyNumber” /><FieldRef Name=”MyCurrency” /><FieldRef Name=”MyDatTime” /><FieldRef Name=”MyLookup_x003a__x0020_LastName” /><FieldRef Name=”MyLookup_x003a__x0020_Company” /><FieldRef Name=”MyLookup_x003a__x0020_Phone” /><FieldRef Name=”MyYesNo” /><FieldRef Name=”MyLinkOrPic” /><FieldRef Name=”MyCalc” /><FieldRef Name=”MyExtDaa_x003a__x0020_LastName” /><FieldRef Name=”MyExtDaa_x003a__x0020_Phone” /><FieldRef Name=”MyChoice” /><FieldRef Name=”MyPersonOrGroup” /><FieldRef Name=”MySText” /><FieldRef Name=”MyMText” /><FieldRef Name=”ReviewStatus” /><FieldRef Name=”MyPeople” /><FieldRef Name=”MyYesNo0″ /></ViewFields><RowLimit Paged=”TRUE”>2147483647</RowLimit></View>

How to check if the current user has already created a list item of a certain content type?

This probably would have been a bit of a hassle before SPMetal existed, right now it’s quite easy to do. Here’s what we didi:

  • We created a custom list.
  • In advanced settings, we’ve enabled content types and added the ootb content type TimeCard.
  • Then, we added two list items: one of the default type, and one of the TimeCard type.

Having our test list set up and ready to go, we’ve used SPMetal to create entities representing, among other, this custom list. We did this by issuing the following command at the command prompt (assuming 14/bin is in your environment path variables):

spmetal /web:http://astro /code Astro.cs

Add the generated Astro.cs file to a VS.NET SharePoint project (in this case, we’ve used a simple console application).

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

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // Open entities context generated by spmetal
            // if a sharepoint context is available, use new AstroDataContext(SPContext.Current.Web.Url) instead.
            using (var astro = new AstroDataContext(“http://astro”))
            {
                var timeItems = (from item in astro.MyMetalList
                                                                        where item.GetType() == typeof(Timecard)
                                                                        select (Timecard) item);

                // Enter specific user name in lambda expression below, for example using: SPContext.Current.Web.CurrentUser.LoginName
                int occurrences = timeItems.Where(item => item.UserName.ToLower() == “loisandclark\\administrator”).Count();
                if (occurrences == 0)
                {
                    Console.WriteLine(“it’s ok to add a request”);
                }
                else if (occurrences == 1)
                {
                    Console.WriteLine(“a request has already been submitted”);
                }
                else
                {
                    Console.WriteLine(“There are duplicate requests. This is an error, contact the administrator”);
                }

                foreach (var item in timeItems)
                {
                    Console.WriteLine(item.Title);
                }
            }
        }
    }
}

Authentication when using the SharePoint client object model

Normally, when you need to log in using a specific credential set in the SharePoint client object model, you’ll have to provide the correct credentials to authenticate to the SharePoint site collection, like so:

NetworkCredential credentials = new NetworkCredential(“username”, “pwd”, “domain”);

ClientContext context = new ClientContext(“http://thesitecollection”);

context.Credentials = credentials;

This won’t work if you have a claims based site set up supporting both Windows and forms authentication. See https://sharepointdragons.com/2012/01/30/claims-in-sharepoint-2010/ for more about setting that up. Instead, you need to set up the appropriate HTTP headers to disable Forms authentication, and it’ll work again:

ClientContext clientContext = new ClientContext(“http://thesitecollection“);clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(clientContext_ExecutingWebRequest);

Web site = clientContext.Web;

clientContext.Load(site);

clientContext.ExecuteQuery();

 

static void clientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e){

    e.WebRequestExecutor.WebRequest.Headers.Add(“X-FORMS_BASED_AUTH_ACCEPTED”, “f”);

}

See http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/16cd0e26-8f3b-4ef2-bac4-c2c59849ab96 for more info.

How to set the people picker field to the current user?

An elegant way to do it is to use a bit of server side code with jQuery:

<script type=”text/javascript”> $(document).ready(function() {

$(‘div.ms-inputuserfield’).text($().SPServices.SPGetCurrentUser({fieldName: “Title”,debug: false}));

</script>