Sunday, September 30, 2012

SharePoint 2010 Security using Object Model


1-    Permission Assignment:

Mostly we want to assign SPUser/SpGroup to a SpWeb/SpList/SpListItem, below contain a generalize method to perform such operation

    ''' <summary>
    ''' Assigning SPUsers to any Securable Object
    ''' </summary>
    ''' <param name="web">Root SPWeb</param>
    ''' <param name="item">SPWeb or SpList or SplitItem
    ''' where it should be Elevated to avoid any problem during update</param>
    ''' <param name="User">Any SPUser</param>
    ''' <param name="spRoleType">Enumeration of default Permission Level</param>
    ''' <remarks></remarks>
    Public Shared Sub AssignSPUserToSecuribleObjectWithUniquePermission(ByVal web As SPWeb, ByVal Item As SPSecurableObject, ByVal User As SPUser, ByVal spRoleType As SPRoleType)
        EnsureUniquePermissions(Item)
        Dim roleAssignment As New SPRoleAssignment(User)
        Dim rolDefination As SPRoleDefinition = web.RoleDefinitions.GetByType(spRoleType)
        roleAssignment.RoleDefinitionBindings.Add(rolDefination)
        Item.RoleAssignments.Add(roleAssignment)
        'update
        UpdateSecurableObject(Item)
    End Sub


By using above method SpUser is assigned permission to SecurableObject as per SPRoleType.

Where above method can be used for assignment of SPGroup by just replacing SpUser param to SpGroup .

 ''' <summary>
    ''' Assigning SPGroup to any Securable Object
    ''' </summary>
    ''' <param name="web">Root SPWeb</param>
    ''' <param name="item">SPWeb or SpList or SplitItem
    ''' where it should be Elevated to avoid any problem during update</param>
    ''' <param name="Group">Any SPGroup</param>
    ''' <param name="spRoleType">Enumeration of default Permission Level</param>
    ''' <remarks></remarks>
    Public Shared Sub AssignSPGroupToSecuribleObjectWithUniquePermission(ByVal web As SPWebByVal Item As SPSecurableObjectByVal Group As SPGroupByVal spRoleType As SPRoleType)
        EnsureUniquePermissions(Item)
        Dim roleAssignment As New SPRoleAssignment(Group)
        Dim rolDefination As SPRoleDefinition = web.RoleDefinitions.GetByType(spRoleType)
        roleAssignment.RoleDefinitionBindings.Add(rolDefination)
        Item.RoleAssignments.Add(roleAssignment)
        'update
        UpdateSecurableObject(Item)
    End Sub

2-    Breaking Inheritance:

As we know In SharePoint there is a hierarchy as shown below



Where by each arrow Security gets inherited however we can break this security inheritance by using below method, it’s important to note that Web Application scope security is assigned globally.

    ''' <summary>
    ''' Assigning Unique Permission
    ''' </summary>
    ''' <param name="item">SPWeb or SpList or SplitItem
    ''' where it should be Elevated to avoid any problem during upate</param>
    ''' <remarks></remarks>
    Public Shared Sub EnsureUniquePermissions(ByVal item As SPSecurableObject)
        If Not item.HasUniqueRoleAssignments Then
            item.BreakRoleInheritance(True)
            UpdateSecurableObject(item)
        End If
    End Sub

    ''' <summary>
    ''' Generalize method to update Securable Object
    ''' </summary>
    Public Shared Sub UpdateSecurableObject(ByVal item As SPSecurableObject)
        If TypeOf item Is SPWeb Then
            CType(item, SPWeb).Update()
        ElseIf TypeOf item Is SPListItem Then
         If CType(item, SPListItem).ParentList.BaseType = SPBaseType.DocumentLibrary Then
                'no version update document library
                CType(item, SPListItem).SystemUpdate(False)
            Else
                CType(item, SPListItem).Update()
            End If
        ElseIf TypeOf item Is SPList Then
            CType(item, SPList).Update()
        End If
    End Sub


This post discusses basic two operations that are mostly commonly used however SPSecurableObject got some other good stuff to explore especially DoesUserHavePermissions method which is good for validation.

Tuesday, September 18, 2012

Using DevExpress Web Controls in SharePoint 2010

I use DevExpress controls in my SharePoint projects, as most developer knows there is a manually process of adding dlls to Gac then safe control entries and then web.config related changes.

To make this process a bit simpler i came up with the following steps (for SharePoint 2010)

1- Stop "SharePoint 2010 Administration" Services from windows services ,

2- Install Deveexpess setup or access system on which its installed and then open below mentioned path.
 C:\Program Files (x86)\DevExpress 2011.2\Components\Tools\SharePoint (w.r.t installed devexpress version)  Run ASPxSharePointRegisterer.exe file.
Note: this will register dlls in GAC and add some web.config safe-control entries for SharePoint Dexpress controls.

3- Start Sharepoint 2010 administration services again.

4- For using devexpress asp.net web form controls open your Web-application web.config and make following changes


  •  Add any missing safe-control entry e.g. I wanted to use ASPxTreeList

<SafeControl Assembly="DevExpress.Web.ASPxTreeList.v11.2, Version=11.2.11.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web.ASPxTreeList" TypeName="*" Safe="True" />


  •  In <system.web> <httpHandlers> add

      <add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v11.2, Version=11.2.11.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET"
      path="DX.ashx" validate="false" />
   

  • In <system.web>  <httpModules> add

      <add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v11.2, Version=11.2.11.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule"/>
 

  • In <system.webServer> <handlers> Add

     <add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v11.2, Version=11.2.11.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" name="ASPxHttpHandlerModule"
      path="DX.ashx" preCondition="integratedMode" />
 

  • In <system.webServer>  <modules> Add

     <add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v11.2, Version=11.2.11.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule"/>
 
5- In your visual studio solution make sure added assemblies properties Copy Local = true
DevExpress.Data.v11.2
DevExpress.Web.ASPxEditors.v11.2
DevExpress.Web.ASPxGridView.v11.2
DevExpress.Web.ASPxTreeList.v11.2
DevExpress.Web.v11.2 

Please share your steps or if you have developed program through SPWebConfigModification.

SharePoint Workflow Timer Job Errors "Due to heavy load..."

Today i came across a annoying problem, when i added new item in List, my visual studio created workflow wasn't starting, it was giving below mentioned error :

"Due to heavy load, the latest workflow operation has been queued. It will attempt to resume at a later time"

This was pretty annoying, I tried workflow throttling through this nice blog but this didn't solve my problem, still i was getting this error as I dig further the real problem was in my Timer Job Service, so following was my solution.

1- Create a Event Receiver.
2- On Item Added Event, manually Start workflow by code as mentioned below


Dim myAssociation As SPWorkflowAssociation = elevatedList.WorkflowAssociations.GetAssociationByName(WorkflowName, Web.UICulture)

elevatedSite.WorkflowManager.StartWorkflow(LstItem, myAssociation, myAssociation.AssociationData)

that's it, manually starting workflow through event receiver solved my problem :)

Thursday, July 5, 2012

.Net Lambda Expression

I’ll be as short and practical as possible,
So, if in one Sentence I have to explain Lambda Expression, it’s like
“Lambda Expression is short form of Anonymous delegate”
How to explain this Sentence? Best way is to explain the Evolution of Lambda Expression by an example.
Ok, suppose we have List of names and we want to find the name that starts with “A”,
1) Suppose we used Delegate or Method to Find:
//Ste#1 List of Name
List<string> names = new List<string>() { "Salman", "Noman", "Adam","man"};
//Ste#2 Using a Method that is invoked every time, in Step3
public bool EvaluteResult (string s)
{
return s.StartsWith("A");
}
//Step#3 Using List FindAll Method, that accept Predicate
List<string> matchedItem = names.FindAll(EvaluteResult);
Above Steps are fine, but a bit lengthy... So Developer wished that this Syntax become shortened a bit and there wished was granted, as Microsoft Introduced Anonymous Delegate.
2) When we used Anonymous Delegate:
//Ste#1 List of Name
List<string> names = new List<string>() { "Salman", "Noman", "Adam","man"};
//Ste#2 Anounymous Delegate, that is to create a Method inline with Deletgate
List<string> mathedItem = names.FindAll(delegate(string item) { returnitem.StartsWith("A"); });
Hmm, Developer where Happy, but in Step#2 above, Line of Code is still quite lengthy, so to further Shortened the Syntax Microsoft Introduced Lambda Expression.
1) When we used Lambda Expression:
//Ste#1 List of Name
List<string> names = new List<string>() { "Salman", "Noman", "Adam","man"};
//Ste#2 Using Lambda Expression to Shorten Anonymous delegate.
List<string> mathedItem = names.FindAll(item=> item.StartsWith("A"));
Note: To make things a bit easy, remmember “item=>” (on above) Represent input parameter as in any function/Method and “item.StartsWith("A")” Represent Body of Function/Method and they don’t require any decleration.
A Short Summary about Lambda Expression:
Basically Lambda are created mainly for LINQ as they evaluate certain value from collection quite easily as shown above, Lambda can used any where Pass In, Parameter Type is Predicate or Selector or Projection, However In our example shown above Pass in Parameter type is Predicate as names.FindAll accept Predicate.

Wednesday, November 2, 2011

Using Custom Type with Conversion Operator

So, let’s start, Today I will discuss how you can decorate your custom Type to make it usable.
Step 1: Creating Custom Type with Conversion Operators
I will create my custom type “PercentageInteger”, this is a integer with special purpose as it can only have a value between 0-100.
struct PercentageInteger
{
public int percentage;
public static implicit operator PercentageInteger(int arg)
{
PercentageInteger pi = new PercentageInteger();
if (arg <>
pi.percentage = 0;
else if (arg > 100)
pi.percentage = 100;
else
pi.percentage = arg;
return pi;
}
public static explicit operator int(PercentageInteger arg)
{
return arg.percentage;
}
public static explicit operator bool(PercentageInteger arg)
{
return true;
}
}
Step 2: Explaning Convertion Operator
public static implicit operator PercentageInteger(int arg)
Obove line tells C# compiler that this “PercentageInteger” type can accept “int” as its value.
So we can use this Type as follows..
PercentageInteger per = 100;
public static explicit operator int(PercentageInteger arg)
Obove line tells C# compiler that “PercentageInteger” type can be Cast to Type “int”.
So we can use this Type as follows..
PercentageInteger per = 100;
int x = (int)per;
bool y = (bool)per;