Blog moved :)

February 17, 2011 Leave a comment

So, I’ve moved this blog to it’s own domain that I can manage and play with rather than the freebie wordpress site🙂

>> http://www.withinsharepoint.com

I’ve already added some new content since moving everything over the other day, check it out!

Categories: Uncategorized

Setting up Claims Based Authentication in SharePoint 2010

February 15, 2011 Leave a comment

So, finding information (that’s accurate and reliable) for migrating FBA or to a claims based authentication system in SharePoint 2010 seems few and far between. After having done my own claims and FBA migration I thought I’d share my notes for what worked for me.

External References
•    http://blogs.technet.com/b/mahesm/archive/2010/04/07/configure-forms-based-authentication-fba-with-sharepoint-2010.aspx 
•    http://blogs.msdn.com/b/chunliu/archive/2010/03/13/forms-based-authentication-on-a-claim-based-web-app.aspx

 

Web.config Changes

Web.config for web application with forms based login
    <membership defaultProvider="i" userIsOnlineTimeWindow="20">
      <providers>
        <clear />
        <!-- added for SQL FBA -->
    <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    <add connectionStringName="FBAUsers" passwordStrengthRegularExpression="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,25}$" applicationName="/" maxInvalidPasswordAttempts="5" passwordAttemptWindow="15" passwordFormat="Hashed" name="SqlUserMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requiresQuestionAndAnswer="false" enablePasswordRetrieval="false" enablePasswordReset="true" />
      </providers>
    </membership>
    <roleManager enabled="true" defaultProvider="c" cacheRolesInCookie="false">
      <providers>
    <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    <add connectionStringName=" FBAUsers " applicationName="/" description="Stores and retrieves roles from SQL Server" name="FBARoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>

<connectionStrings>
    <!-- Added for SQL FBA -->
    <add name="FBAUsers " connectionString="Initial Catalog=ExternalUsers;data source=DatabaseServer;Integrated Security=SSPI;" />
  </connectionStrings>
  <location path="_layouts/login.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <system.net>
    <!-- Added for password reset/retrieval -->
    <mailSettings>
      <smtp from="email@place.doesntexist">
        <network host="mail.serverdoesntexist.amazing" />
      </smtp>
    </mailSettings>
    <!-- -->
  </system.net>

Web Config for Central Admin

<membership defaultProvider="SqlUserMembershipProvider" userIsOnlineTimeWindow="20"> <providers> <clear /> <!-- added for SQL FBA --> <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" /> <add connectionStringName=" FBAUsers " passwordStrengthRegularExpression="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,25}$" applicationName="/" maxInvalidPasswordAttempts="5" passwordAttemptWindow="15" passwordFormat="Hashed" name="SqlUserMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requiresQuestionAndAnswer="false" enablePasswordRetrieval="false" enablePasswordReset="true" /> </providers> </membership> <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" cacheRolesInCookie="false"> <providers> <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" /> <add connectionStringName=" FBAUsers" applicationName="/" description="Stores and retrieves roles from SQL Server" name="FBARoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </providers> </roleManager> <connectionStrings> <!-- Added for SQL FBA --> <add name=" FBAUsers" connectionString="Initial Catalog=Database;data source=DatabaseServer;Integrated Security=SSPI;" /> </connectionStrings>

Web.config for SecureToken Service

%programfiles%\common files\Microsoft Shared\web server extensions\14\WebServices\SecurityToken

<connectionStrings> <!-- Added for SQL FBA --> <add name=" FBAUsers" connectionString="Initial Catalog=Database;data source=DatabaseServer;Integrated Security=SSPI;" /> </connectionStrings> <system.web> <membership defaultProvider="i" userIsOnlineTimeWindow="20"> <providers> <clear /> <!-- added for SQL FBA --> <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" /> <add connectionStringName=" FBAUsers" passwordStrengthRegularExpression="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,25}$" applicationName="/" maxInvalidPasswordAttempts="5" passwordAttemptWindow="15" passwordFormat="Hashed" name="SqlUserMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requiresQuestionAndAnswer="false" enablePasswordRetrieval="false" enablePasswordReset="true" /> </providers> </membership> <roleManager enabled="true" defaultProvider="c" cacheRolesInCookie="false"> <providers> <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" /> <add connectionStringName=" FBAUsers" applicationName="/" description="Stores and retrieves roles from SQL Server" name="FBARoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </providers> </roleManager> </system.web>

Migrate Web Application to Claims Based Tokens using PowerShell

This will change existing permissions to be claims tokens rather than whatever they are currently.
$webappurl = "http://url" $account = "domain\username" $wa = Get-SpWebApplication $webappurl Set-SPWebApplication $wa -AuthenticationProvider (New-SPAuthenticationProvider) -Zone Default $account = (New-SPClaimsPrincipal -identity domain\username -identitytype 1).ToEncodedString() $zp = $wa.ZonePolicies("Default") $p = $zp.Add($account, "PSPolicy") $fc = $wa.PolicyRoles.GetSpecialRole("FullControl") $p.PolicyRoleBindings.Add($fc) $wa.Update() $wa = Get-SPWebApplication $webappurl $wa.MigrateUsers($true)
Categories: 2010, SharePoint

Example SharePoint 2010 FBA Login Page

February 15, 2011 Leave a comment

This is an example SharePoint 2010 claims based forms authentication login page. This has all the basic elements you would want, including password reset. Just update the placeholder MyCompany bits with your company information and enjoy! Remember if you include a login page within a solution it needs to go to IDENTITYMODEL\LOGIN and to update the web application properties for which login page to use.🙂

<%@ Assembly Name=“Microsoft.SharePoint.IdentityModel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

<%@ Assembly Name=“Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”%> <%@ Page Language=“C#” Inherits=“Microsoft.SharePoint.IdentityModel.Pages.FormsSignInPage” MasterPageFile=“~/_layouts/simple.master” %> <%@ Import Namespace=“Microsoft.SharePoint.WebControls” %> <%@ 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” %> <%@ Import Namespace=“Microsoft.SharePoint” %> <%@ Assembly Name=“Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

<asp:Content ContentPlaceHolderId=”PlaceHolderPageTitle” runat=”server”>

<SharePoint:EncodedLiteral runat=”server” EncodeMethod=”HtmlEncode” Id=”ClaimsFormsPageTitle” />

</asp:Content>

<asp:Content ContentPlaceHolderId=”PlaceHolderPageTitleInTitleArea” runat=”server”>

<SharePoint:EncodedLiteral runat=”server”  EncodeMethod=”HtmlEncode” Id=”ClaimsFormsPageTitleInTitleArea” />

</asp:Content>

<asp:Content ContentPlaceHolderId=”PlaceHolderSiteName” runat=”server”/>

<asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”>

<div id=”SslWarning” style=”color:red;display:none”>

<SharePoint:EncodedLiteral runat=”server”  EncodeMethod=”HtmlEncode” Id=”ClaimsFormsPageMessage” />

</div>

<style>

BODY #s4-simple-card

{

margin: 25px auto 0px !important;

width: 900px !important;

}

BODY #s4-simple-content

{

margin-left:0px !important;

}

DIV.s4-simple-iconcont

{

display:none !important;

}

BODY #s4-simple-card H1

{

display:none !important;

}

</style>

<script language=javascript type=’text/javascript’>

function showHide()

if (document.getElementById(‘resetPass’).style.display == “none”)

{

document.getElementById(‘loginArea’).style.display = “none”;

document.getElementById(‘resetPass’).style.display = “”;

}

else

{

document.getElementById(‘loginArea’).style.display = “”;

document.getElementById(‘resetPass’).style.display = “none”;

}

}

</script>

<script language=”javascript” >

if (document.location.protocol != ‘https:’)

{

var SslWarning = document.getElementById(‘SslWarning’);

SslWarning.style.display = ”;

}

</script>

<div align=”center”>

<table width=”100%”><tr><td><img src=”MyCompanyBanner.png” alt=”MyCompany – Motto” /></td></tr><tr><td>

<div id=”loginArea” align=”center”>

<asp:login id=”signInControl” FailureText=”<%$Resources:wss,login_pageFailureText%>” runat=”server” width=”100%”>

<layouttemplate>

<asp:label id=”FailureText” class=”ms-error” runat=”server”/>

<table width=”80%”>

<tr>

<td nowrap=”nowrap” align=”right”><SharePoint:EncodedLiteral runat=”server” text=”<%$Resources:wss,login_pageUserName%>” EncodeMethod=’HtmlEncode’/></td>

<td width=”100%” align=”left”><asp:textbox id=”UserName” autocomplete=”off” runat=”server” class=”ms-inputuserfield” width=”99%” /></td>

</tr>

<tr>

<td nowrap=”nowrap” align=”right”><SharePoint:EncodedLiteral runat=”server” text=”<%$Resources:wss,login_pagePassword%>” EncodeMethod=’HtmlEncode’/></td>

<td width=”100%” align=”left”><asp:textbox id=”password” TextMode=”Password” autocomplete=”off” runat=”server” class=”ms-inputuserfield” width=”99%”/></td>

</tr>

<tr>

<td></td>

<td><b><a href=”javascript:showHide()”>Lost/Reset Password?</a></b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:checkbox id=”RememberMe” text=”<%$SPHtmlEncodedResources:wss,login_pageRememberMe%>” runat=”server” /></td></td>

<td align=”right”><asp:button id=”login” commandname=”Login” text=”<%$Resources:wss,login_pagetitle%>” runat=”server” /></td>

</tr>

<tr>

<td align=”right” colspan=”2″>

</tr>

</table>

</tr>

</table>

<table width=”100%”><tr><td>

<p align=”justify” style=”color:#212020; width:800px;”>

Verbiage below login

</p>

</td></tr>

</table>

</layouttemplate>

</asp:login><div id=”resetPass” align=”center” style=”display:none”>

<asp:Label ID=”lblPR” runat=”server” ForeColor=”red” Font-Bold=”true”></asp:Label><br />

<asp:PasswordRecovery ID=”PasswordRecovery1″ runat=”server”

BackColor=”White” BorderColor=”white” BorderPadding=”4″ BorderStyle=”Solid” BorderWidth=”1px” Font-Names=”Verdana” Font-Size=”1.2em”>

<MailDefinition Priority=”High” Subject=”Password reset per your request” From=”sharepoint@mycompany.com” />

<InstructionTextStyle Font-Italic=”True” ForeColor=”Black” />

<SuccessTextStyle Font-Bold=”True” ForeColor=”#507CD1″ />

<TextBoxStyle Font-Size=”1.2em” />

<TitleTextStyle BackColor=”#507CD1″ Font-Bold=”True” Font-Size=”1.2em” ForeColor=”White” />

<UserNameTemplate>

<table border=”0″ cellpadding=”1″>

<tr>

<td>

<table border=”0″ cellpadding=”0″>

<tr>

<td align=”center” colspan=”2″>

<asp:Label runat=”server” ID=”enterName” Text=”Enter your email to reset your password.” Font-Size=”1.2em”></asp:Label></td>

</tr>

<tr>

<td align=”right”>

<asp:Label ID=”UserNameLabel” Font-Size=”1.2em” runat=”server” AssociatedControlID=”UserName”>User Name:</asp:Label></td>

<td>

<asp:TextBox ID=”UserName” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”UserNameRequired” runat=”server” ControlToValidate=”UserName”

ErrorMessage=”User Name is required.” ToolTip=”User Name is required.” ValidationGroup=”PasswordRecovery1″>*</asp:RequiredFieldValidator>

</td>

</tr>

<tr>

<td align=”center” colspan=”2″ style=”color: red”>

<asp:Literal ID=”FailureText” runat=”server” EnableViewState=”False”></asp:Literal>

</td>

</tr>

<tr>

<td align=”left”>

<b><a href=”javascript:showHide()”>Return to Login</a></b>

</td>

<td align=”right”>

<asp:Button ID=”SubmitButton” runat=”server” CommandName=”Submit” Text=”Submit” ValidationGroup=”PasswordRecovery1″ />

</td>

</tr>

</table>

</td>

</tr>

</table>

</UserNameTemplate>

<SuccessTemplate>

<table border=”0″ cellpadding=”4″ cellspacing=”0″ style=”border-collapse: collapse;”>

<tr>

<td>

<table border=”0″ cellpadding=”0″>

<tr>

<td style=”color: #507CD1; font-weight: bold;”>

<asp:literal runat=”server” Text=”Password has been reset and emailed to you.” /></td>

<a href=”javascript:showHide()”>Return to Login</a>

</tr>

</table>

</td>

</tr>

</table>

</SuccessTemplate>

<SubmitButtonStyle BackColor=”White” BorderColor=”#507CD1″ BorderStyle=”Solid” BorderWidth=”1px”

Font-Names=”Verdana” Font-Size=”0.8em” ForeColor=”#284E98″ />

</asp:PasswordRecovery>

</div>

</div>

</div>

</asp:Content>

Categories: 2010, SharePoint

Handling Feature Dependencies

February 15, 2011 Leave a comment

So a common scenario is you have to deploy a set of features to get a desired result. However Feature B is reliant on Feature A and you want them to auto-activate. However automatic activation in this scenario generates an error if Feature A hasn’t finished being activated yet.

So a simple workaround is to add a feature receiver (either in one of your core features or as a separate feature altogether that activates/deactivates everything for you). So here’s an example of how you would achieve this🙂 enjoy!

  1. using Microsoft.SharePoint;
  2. using Microsoft.SharePoint.Administration;
  3. class FeatureReceiver : SPFeatureReceiver
  4. {
  5. public override void FeatureActivating(SPFeatureReceiverProperties properties)
  6. {
  7. SPWeb web = (SPWeb)properties.Feature.Parent;
  8. //active features in current spsite
  9. SPFeatureCollection _features = web.Site.Features;
  10. bool featureActive = false;
  11. //my custom feature definition
  12. SPFeatureDefinition myFeatureDef = web.Site.FeatureDefinitions[“FeatureName”];
  13. foreach (SPFeature feature in _features)
  14. {
  15. if (feature.Definition == myFeatureDef)
  16. {
  17. //found feature as activated already
  18. featureActive = true;
  19. }
  20. }
  21. //feature is present but not activated
  22. if (!featureActive)
  23. {
  24. web.Site.Features.Add(myFeatureDef.Id, true);
  25. }
  26. }
  27. public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
  28. {
  29. SPWeb web = (SPWeb)properties.Feature.Parent;
  30. //get active features from current spsite
  31. SPFeatureCollection _features = web.Site.Features;
  32. bool featureActive = false;
  33. //get specific definition for my custom feature
  34. SPFeatureDefinition myFeatureDef = web.Site.FeatureDefinitions[“FeatureName”];
  35. foreach (SPFeature feature in _features)
  36. {
  37. if (feature.Definition == myFeatureDef)
  38. {
  39. //feature found in activate feature collection
  40. featureActive = true;
  41. }
  42. }
  43. //if we found the feature active
  44. if (featureActive)
  45. {
  46. //feature guid, force remove true/false
  47. web.Site.Features.Remove(myFeatureDef.Id, true);
  48. }
  49. }
  50. }
Categories: 2007, 2010, Code, SharePoint

Updating Items Safely in an Event Handler

February 10, 2011 Leave a comment

This caused me lots of headaches a few months back, the SharePoint application pool was randomly crashing and the SharePoint logs were showing list item contention on updates. Eventually it all came back to the event handlers we had running within that site collection and an unpublished best practice for how to safely update list items from within item events. Note that disabling event firing is only within the context of your event handler, not everything on that list/web/site etc. More information on this works can be found here: How DisableEventFiring / EventFiringEnabled works

2010
//update item with changes
this.EventFiringEnabled = false;
item.SystemUpdate();
this.EventFiringEnabled = true;

2007
this.DisableEventFiring();
item.SystemUpdate();
this.EnableEventFiring();

Categories: 2007, 2010, Code, SharePoint

Long Running Operations within an Event Handler

February 10, 2011 1 comment

So, often times when you have an event handler you have to do something that takes longer to execute than SharePoint normally allows for within an event handler. Now normal multi-threading sometimes works here, but often times also runs in to the issue where SharePoint terminates the event as timed out. So here’s a trick I’ve found that works.

You may be familiar with the UI long running job class: Microsoft.SharePoint.Publishing.Internal.LongRunningOperationJob this is what generates the page you get for long running operations with the progress bar. However, this same class can be used within your event handler to pass off your long running event operation into a site collection job.

In the below example you can see I just pass the event directly in to a LongRunningOperationJob with an extended time out of 30 minutes. This can go up to 24 hours in my testing reliably. Additionally, this gives you the option to have UI on top of some events from a custom monitoring web part or administrative web part without any more work! YAY!

Example Code:

class ItemEvent : SPItemEventReceiver

{//on item deletion

public override void ItemDeleting(SPItemEventProperties properties)

{

base.ItemDeleting(properties);

DeleteRule longRunningRules = new DeleteRule(properties.ListItem);

longRunningRules.MillisecondsToWaitForFinish = 180000;

longRunningRules.Start(properties.ListItem.Web);

}

}

 

public class DeleteRule : LongRunningOperationJob

{

private SPListItem rule;

public DeleteRule(SPListItem item)

{

rule = item;

}

 

public override void DoWork()

{

ItemEvent deleteRule = new ItemEvent();

try

{

deleteRule.deleteItem(rule, true);

}

catch (Exception ex)

{

this.SetError(ex);

}

}

}

 

Categories: 2007, 2010, Code, SharePoint

Using Native SharePoint Form Fields

February 8, 2011 Leave a comment

When making a generic web part for modifying or interacting with different SharePoint data you can’t always predict the column data type before hand. The best way to make sure your web part works regardless of what data is being tossed in to it is to just use the out of box SharePoint Form Field control. This control goes ahead and grabs the column edit and display templates depending on the state you specify. Below is a code snippet example of how to use this control. Takes a lot of the headache out when dealing with unknown data types/building generic web parts.

/// <summary>

/// returns a valid native sharepoint fieldlabel control for use in forms

/// </summary>

/// <param name=”newItemContext”></param>

/// <param name=”fld”></param>

/// <returns></returns>

private FieldLabel buildLabel(SPContext newItemContext, SPField fld)

{

FieldLabel lbl = new FieldLabel();

lbl.ControlMode = SPControlMode.New;

lbl.FieldName = fld.Title;

//lbl.ItemContext = newContext;

lbl.RenderContext = newItemContext;

lbl.ID = String.Format(LABEL, fld.InternalName);

return lbl;

}

 

/// <summary>

/// Returns a valid native sharepoint field control based ont he field type/definition of the passed spfield object for use in forms

/// </summary>

/// <param name=”newItemContext”></param>

/// <param name=”fld”></param>

/// <param name=”listID”></param>

/// <returns></returns>

private FormField buildFormField(SPContext newItemContext, SPField fld, Guid listID)

{

//build form field interaction UI using native formfield control

int id = mainFormFields.Count + repeatingFormFields.Count;

FormField formField = new FormField();

formField.ControlMode = SPControlMode.New;

formField.ListId = listID;

formField.FieldName = fld.InternalName;

formField.RenderContext = newItemContext;

formField.ID = String.Format(FIELD, fld.Id.ToString());

return formField;

}

Categories: 2007, 2010, Code, SharePoint
Follow

Get every new post delivered to your Inbox.