Saturday, January 26, 2013

Refresh GAC using Powershell

Scenario:
Refreshing GAC is always a painful thing.
Do IISReset / remove old stuff / put new one. Can we automate it ?

Solution:
Certainly.. mighty power-shell can do it easily

If you are running on new machine - you might need to relax executing policy

Set-ExecutionPolicy Unrestricted
Code:
iisreset /stop

Set-Alias Gacutil "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe"

Gacutil /uf EntLibContrib.Data.OdpNet
Gacutil /i "MS ENT dlls\EntLibContrib.Data.OdpNet.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Caching
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Caching.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Common
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Common.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Data
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Data.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Logging
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Logging.dll"

Gacutil /uf Microsoft.Practices.ServiceLocation
Gacutil /i "MS ENT dlls\Microsoft.Practices.ServiceLocation.dll"

Gacutil /uf Microsoft.Practices.Unity.Configuration
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Configuration.dll"

Gacutil /uf Microsoft.Practices.Unity
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.dll" 

Gacutil /uf Microsoft.Practices.Unity.Interception.Configuration
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Interception.Configuration.dll"

Gacutil /uf Microsoft.Practices.Unity.Interception
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Interception.dll" 

Gacutil /uf Telerik.Web.Design
Gacutil /i "Telerik.Web.Design.dll"

Gacutil /uf Telerik.Web.UI
Gacutil /i "Telerik\Telerik.Web.UI.dll" 

Gacutil /uf Telerik.Reporting
Gacutil /i "Telerik\Telerik.Reporting.dll"

Gacutil /uf Telerik.Web.UI.Skins
Gacutil /i "Telerik\Telerik.Web.UI.Skins.dll"

iisreset /start

Tuesday, January 15, 2013

Event receiver with Elevated Privileged

Scenario:
Client wanted to run the event receiver code with elevated access.

Solution:
Using Elevated Privileged is one option but better options was using System User Token
Code:

/// 
        /// An item is being added.
        /// 
        public override void ItemAdding(SPItemEventProperties properties)
        {
            SPSite site = properties.Web.Site;
            SPUserToken sysToken = site.SystemAccount.UserToken;
            site.Dispose();

            using (var systemSite = new SPSite(properties.SiteId, sysToken))
            {
                using (SPWeb sysWeb = systemSite.OpenWeb(properties.Web.ID))
                {
                       // Code goes here 
                }
            }

Friday, December 14, 2012

Powershell to hide fields from edit form

Scenario:
We build a small solution for our client.
Solution had a custom UI for all CRUD operations and client want to block everyone from editing the list using Edit Form.

Solution:
While there can be many ways, considering site is running perfectly in PROD, writing a quick power shell will be enough.

Code:

cls
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

$webUrl = "http://sp2010/siteX"
$web = Get-SPWeb $webUrl
$list = $web.Lists.TryGetList("Tasks")

$fieldDisplayNames = "Status","Priority"
$showFields = $false 

$fieldDisplayNames |foreach {
 
$spfield = $list.Fields[$_]
$spfield.ShowInEditForm = $showFields
$spfield.Update()

}
Article:

Friday, September 21, 2012

SharePoint programatically apply claims

Scenario:
Claim based authentication is way to go if you want to have dynamic roles for user based on certain attribute of an item/document. But question is how to apply a claim to the item :)

Solution:
Sample code
Code:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;

namespace SKN
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            using (SPSite site = new SPSite("http://intranet/Sites/LoadTest"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Shared Documents");
                    SPView view = list.Views["Missing Claims"];
                    SPQuery query = new SPQuery(view);
                   
                    foreach (SPListItem item in list.GetItems(query))
                    {
                        i = item.ID;
ApplyClaims(web, item, true, "0000" + item.ID.ToString(), true,"Myclient");
                    }
                }
            }

            Console.Write(i);
            Console.ReadKey();
        }

        /// 
        /// Applies claims to the item.
        /// 
public static void ApplyClaims(SPWeb web, SPListItem item,string claimValue , string client)
        {
            item.BreakRoleInheritance(false);

            SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
            if (claimMgr != null)
            {
               SPClaim claim = new                               SPClaim(Microsoft.IdentityModel.Claims.ClaimTypes.Role,
               claimValue,
Microsoft.IdentityModel.Claims.ClaimValueTypes.String,
SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, client));

                string userName = claimMgr.EncodeClaim(claim);

                // SPUser spUser = web.EnsureUser(userName);
                SPUserInfo info = new SPUserInfo
                {
                    LoginName = userName,
                    Name = claimValue 
                };

                SPRoleAssignment roleAssignmentClaim = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes);
                roleAssignmentClaim.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]);
                item.RoleAssignments.Add(roleAssignmentClaim);
            }
        }

        /// 
        /// Adds the role assignment.
        /// 
        /// The item./// The role assignment.public static void AddRoleAssignment(SPListItem item, SPRoleAssignment roleAssignment)
        {
            bool isNotFound = true;
            foreach (SPRoleAssignment roleAssign in item.RoleAssignments)
            {
                if (roleAssign.Equals(roleAssignment))
                {
                    isNotFound = false;
                    break;
                }
            }

            if (isNotFound)
            {
                item.RoleAssignments.Add(roleAssignment);
            }

            item.SystemUpdate();
        }
    }
}

Friday, September 14, 2012

SharePoint Powershell Test Data script

Scenario:
Working on a project and we need to test the software limit of SharePoint 2010.
MS Documentation is not clear about things/ community blogs have different experience.
So without taking chance, here a small script to create test items

Solution:
Powershell script

Code:

cls
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

$webUrl = Read-Host 'Please specify site url'
$web = Get-SPWeb $webUrl;
$list = $web.Lists.TryGetList("Announcements");
(1..50000)|%{
$item = $list.Items.Add();
$item["Title"]="Test";
$item.Update();
# Optional 
# $item.BreakRoleInheritance($True);
$item.ID
}
$web.Dispose()

Wednesday, September 5, 2012

Cannot start the conversion job because it does not contain any files.

Scenario:
While working with a small POC. I encountered a weird error.
Cannot start the conversion job because it does not contain any files.

Solution:
Error was coming when I was trying to convert all files of a document library from word to pdf.

I googled the error - but no luck , so thought of posting once I found the fix.

I read error and as per the message there are no files in the library.
I validated and there were files in there. So what could be it :)

Permission.
I checked the account running the Word Automation Service and gave "Contribute" access the account. That was it.

Sunday, August 26, 2012

Quickly identifying claim based site

Scenario:
I love user group as you get question from every angle. I got a very simple question from one of the user. How do I know my site is already configured for claims ?

Solution:
If you login to your site and click on My Settings from Welcome menu , you will see clean Account name , with no weird characters :)



If claims is enabled you will see something like this. Notice those weird characters as prefix to account name.


Article:
In case you want to switch from Classic > Claims based or vice-versa, you can use my old article Enable Claim Based Authentication for existing web application