Monday, August 12, 2013

Exception setting „Hidden” Cannot change Hidden attribute for this field”

Requirements:
Requirements was to remove the Taxonomy field „Parent Company” from the Sharepoint List  as this field is not used by anyone.
Issue:
Issue with the „Parent Company” field deleting with PowerShell script. After the script run the following error message has appeared. „Exception setting „Hidden” Cannot change Hidden attribute for this field”
Investigation:
This is an internal issue in SharePoint2010.
The common issue description can be found here: http://blogs.msdn.com/b/spblog/archive/2013/04/27/sps2010-field-cannot-be-made-again-visible-if-defined-to-be-hidden-using-visual-studio-2010.aspx .
During development the field „Parent Company” was created usisng xml definition in Visual Studio 2010 and a field attribute „Hidden” was set to value „True” (true if the field is hidden; otherwise, false.)
<Field
       ID="{747FC1CF-FCED-44EB-B895-568E9F423174}"
        Name="ALLegalCompanyTaxHTField1"
        StaticName="ALLegalCompanyTaxHTField1"
        Type="Note"
        Overwrite="TRUE"
        RowOrdinal="0"
        DisplayName="$Resources:IntranetGroupDirectory,Fields_ParentCompany_DisplayName;"
        Group="$Resources:IntranetGroupDirectory,GroupDirectory_CT_Group;"
        Description="$Resources:IntranetGroupDirectory,Fields_ParentCompany_Description;"
        Hidden ="TRUE">
  </Field>
An taxonomy field consists of  two fields (example: „Parent Company” can be seen on screenhot)
The „Parent Company” is a taxonomy field and consists of two fields definition ALLegalCompany and ALLegalCompanyTaxHTField1
<Field
        ID="{B5FE2B9E-CDF9-4B4A-B34C-85650481A280}"
        Name="ALLegalCompany"
        StaticName="ALLegalCompany"
        Type="TaxonomyFieldType"
        ShowField="Term1033"
        Overwrite="TRUE"
        Mult="TRUE"
        DisplayName="$Resources:IntranetGroupDirectory,Fields_ParentCompany_DisplayName;"
        Group="$Resources:IntranetGroupDirectory,GroupDirectory_CT_Group;"
        Description="$Resources:IntranetGroupDirectory,Fields_ParentCompany_Description;"
        Hidden ="FALSE">
</Field>
The field ALLegalCompany has „Hidden” proeprty set value to False.
The field ALLegalCompanyTaxHTField1 has property „Hidden” set to True that caused the difficulties to delete this field.
Fields in SharePoint can be added using xml definition via Visual Studio, but cannot be delete that way, therefore the Powershell commands must be used to delete fields from Lists or Content Type. But the field „Parent Comapny” cannot be deleted that’s way using scrips, because fields should be visible and property „Hidden” is set to false. Property „Hidden” cannot be set to false, because this property depends (relies) on other property called „CanToggleHidden” and it’s value should be set to True. „CanToggleHidden” property is Read-only and  and it’s value cannot be change directly, because there is no setter method (this is a SharePoint property that stored in native assemly (SPField) and was developed that way, the reason of that fact is unknown).
To be possible to change property Hidden to false, the property „CanToggleHidden” value should be set to True in a field definition, the way like in this example below (but in this case the property is absent at all in the field definition).
<Field
        ID="{747FC1CF-FCED-44EB-B895-568E9F423174}"
        Name="ALLegalCompanyTaxHTField1"
        StaticName="ALLegalCompanyTaxHTField1"
        Type="Note"
        Overwrite="TRUE"
        RowOrdinal="0"
        DisplayName="$Resources:IntranetGroupDirectory,Fields_ParentCompany_DisplayName;"
        Group="$Resources:IntranetGroupDirectory,GroupDirectory_CT_Group;"
        Description="$Resources:IntranetGroupDirectory,Fields_ParentCompany_Description;"
        Hidden ="TRUE"
   CanToggleHidden ="TRUE">
  </Field>
By default CanToggleHidden is return false as it is not presented in the definition. Adding the property and deploy solution don’t change the field defintion.
If we have a look in code at the „Hidden” property setter in assembly Microsoft.SharePoint.SPField  it also sets „CanToggleHidden” property to true, but cannot be reached because it is value by default is false and throw the error message shown in the picture above „Exception setting „Hidden” Cannot change Hidden attribute for this field”.
this.SetFieldBoolValue("CanToggleHidden", true)
[ClientCallable]
    public bool Hidden
    {
      get
      {
        if (this.HasExternalDataSource)
        {
          return SPExternalList.IsFieldHidden(this);
        }
        return this.GetFieldBoolValue("Hidden", 4);
      }
      [ClientCallableExceptionConstraint(FixedId="1", ErrorCode=-2146232832, Condition="Thrown when attempting to set Hidden property for a field that does not allow this property to be toggled.", ErrorType=typeof(SPException))]
      set
     {
        if (!this.CanToggleHidden)
        {
          throw new SPException(SPResource.GetString("HiddenAttributeUpdateNotAllowed", new object[0]));
        }
        this.SetFieldBoolValue("Hidden", value);
        this.SetFieldBoolValue("CanToggleHidden", true);
      }
    }

Solution:
Solution was found to use reflection to change property „CanToggleHidden” value to True, cahnge Hidden property to false and delete the field from the List via PowerShell

PowerShell example:

$web = Get-SPWeb  "http://sharepoint/
$listLegComp = $web.Lists["YourList"]
$pcFieldTax = $listLegComp.Fields.GetFieldByInternalName("ALLegalCompanyTaxHTField1")
$pcField = $listLegComp.Fields.GetFieldByInternalName("ALLegalCompany")
if(!$pcFieldTax.CanToggleHidden)
{
   $bindingFlags = [Reflection.BindingFlags] "NonPublic,Instance"
   [System.Type] $type = $pcFieldTax.GetType()
   [Reflection.MethodInfo] $mdInfo = $type.GetMethod("SetFieldBoolValue",$bindingFlags)
   $object = [System.Object] @("CanToggleHidden",$true)
   $mdInfo.Invoke($pcFieldTax,$object)
   $pcFieldTax.Hidden = $false
   $pcFieldTax.AllowDeletion = $true
   $pcFieldTax.Update()
     
}
if(!$pcField.CanToggleHidden)
{
   $bindingFlags = [Reflection.BindingFlags] "NonPublic,Instance"
   [System.Type] $type = $pcField.GetType()
   [Reflection.MethodInfo] $mdInfo = $type.GetMethod("SetFieldBoolValue",$bindingFlags)
   $object = [System.Object] @("CanToggleHidden",$true)
   $mdInfo.Invoke($pcField,$object)
   $pcField.Hidden = $false
   $pcField.AllowDeletion = $true
   $pcField.Update() 
}

$pcFieldTax.Delete()
$pcField.Delete()
$listLegComp.Update()
$web.Dispose()

Wednesday, August 7, 2013

How to use RegEx in c# to remove or replace HTML characters

If you need to remove HTML tags from string you can use reqular expression to do that.
For Example you get the following code from client side "<p>Hi, How are you?</p><div>I'm fine.</div>".


using System.Text.RegularExpressions;


public static string HtmlToString(string HTMLText)
{
  Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);

  return reg.Replace(HTMLText, "");
}



The output of the method HtmlToString will be: "Hi, How are you?I'am fine"

Tuesday, July 9, 2013

Change permissions level for the groups in a SharePoint 2010 List or Library

Hi, Recently I needed to breake inherirites for a list on  Sharepoint 2010 site page and change the group permissions to specific one. So here is a powershell script that does the job. You will need to change $OwnerGroupName, $web = Get-SPWeb  $SiteUrl and $list = $web.Lists["<ListName>"]; to your own values.

Task:

Only users in site owner group can have "Full Control"  permissions for specific list on this site. Other groups permissions should be changed to "Read"



What Powershell script does:

1. It breaks inheritance from site
2. Gets all groups on the site
3. Goes via a list role assignments

and

4  If group name is equal to list Role Assignments removes group existing permissions and assign new role with "Read" permissions


Scripts:

[string]$OwnerGroupName = "Owners";

$web = Get-SPWeb  "<SiteUrl>";


$list = $web.Lists["<ListName>"];

$groupCollection =  $web.Groups;

 if ($list -ne $null)
  {
    if (!$list.HasUniqueRoleAssignments)
      {
    $list.BreakRoleInheritance($true);
      }
   $web.AllowUnsafeUpdates = $true;
           foreach ($group in $groupCollection)
{
                Write-Host $group.Name
                if ($group.Name -ne $OwnerGroupName)
                {
                    $roleColl = $list.RoleAssignments
foreach($roleAss in $roleColl){
 
if($roleAss.Member.Name -eq $group.Name){

$permissions = $roleAss.RoleDefinitionBindings
$roleColl.Remove($group)

$roleDef = $web.RoleDefinitions["Read"]
$roleAssign = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
$roleAssign.RoleDefinitionBindings.Add($roleDef)
$list.RoleAssignments.Add($roleAssign)
break
}
}        
    }
}  
$web.AllowUnsafeUpdates = $false;
}

Thursday, May 16, 2013

Add Users to SharePoint Group using PowerShell

$USER_TO_ADD = $null;
 $web = Get-SPWeb -Identity "http://yoursite.com"
$manageGroup = $web.SiteGroups["GroupName"]
 try {
 $adUsername = "$USER_TO_ADD";
 $spUser = $web.Site.RootWeb.EnsureUser($adUsername.Split('\',1));    $manageGroup.AddUser($spUser);
 $manageGroup.Update();
 write-host "User: "
 $spUser.Name "was added to group" }
 catch
 {
    $_ Write-Host $spUser " does not exists"
 }
 } $web.Update(); $web.Dispose();

Thursday, May 9, 2013

Sharepoint 2010 disable event firing using Powershell script



Here is a code:


#Add SharePoint PowerShell SnapIn if not already added
 if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$web = Get-SPWeb "http://mysharepoint.com/mypage/"


$list = $web.Lists.TryGetList("<ListName>")

$item = $list.Items.GetItemById("<ItemID>")

   try
   {

Write-Host "Deleting" $item.Title;
$myAss = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
    $type = $myAss.GetType("Microsoft.SharePoint.SPEventManager");
    $prop = $type.GetProperty([string]"EventFiringDisabled",[System.Reflection.BindingFlags] ([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static));

$prop.SetValue($null, $true, $null);
$prop.GetValue($null,$null)
$item.Title;
     $item.Delete()
    Write-Host  $item.Title "was deleted";

$prop.SetValue($null, $false, $null);
$prop.GetValue($null,$null);
$prop.GetValue(
}
catch
{
     
}

Tuesday, March 26, 2013

Validate the existence of user account in AD using Powershell


Check for user AD account existing with PowerShell script.
Once I needed to check if AD user account exists on server and is enabled.
There are two option to do that.
The first option is to use  Get-ADUser.
Make sure you install the module Active Directory.  


How to install and use Active Directory Module
http://blogs.technet.com/b/heyscriptingguy/archive/2011/08/30/install-active-directory-management-service-for-easy-powershell-access.aspx

The following example shows how to use the function:

Import-Module ActiveDirectory

$AccountName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName].Value ;

$SplitUserName = ($AccountName.Split("\")[1])
$UserExists = Get-ADUser -Filter {sAMAccountName -eq $UserName}
$UserName = $splitusername;
if ($UserExists -eq $null)
{
      Write-Host "User $AccountName does not exist in AD "
}
else 
{
   if (!$UserExists.Enabled)
     {
       Write-Host "User $AccountName is disabled"
     }
     Else
     {
        Write-Host "AD account  $AccountName is ok";
     }
 }
In my case I didn’t have the module Active Directory installed on production server, so I need to find the second way. I couldn’t use the function Get-ADUser from module ActiveDirectory. My opinion is to better to install the module because it has a lot of usefull functions that will makes yourlife easear. I didn’t have such opotunaty because installing module means to restart production server, but this approach I needed to escape, so I found the second option and wrote function.

# function Check-ADUser gets user name as a parametr
# return two properties:
# Status
#              return "0" if AD account doesn't exist in Active directory or was deleted
#              return "1" if the user exists.
# AccountEnable
#              return "0" if AD account is disabled
#          return "1" if AD account is enabled
#Example:
# $UserStatus = (Check-ADUser -Username "testuser1").Status;
# $UserAccountEnabled = (Check-ADUser -Username "$SplitUserName").AccountEnable;
function Check-ADUser
{
Param ($Username)

    $ADRoot = [ADSI]''
    $ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot);
    $SAMAccountName = "$Username";
$ADSearch.Filter = "(&(objectClass=user(sAMAccountName=$SAMAccountName))";
    $Result = $ADSearch.FindAll();
     
      $Status = "-1";
      $Enabled = "-1";
    if($Result.Count -eq 0)
    { # "No such user on the Server"
        $Status = "0";
    }
    Else
    { #"User exist on the Server"
        $Status = "1";
            foreach ($objResult in $Result)
      {
            $objResult = $objResult.GetDirectoryEntry()
             if ($objResult.accountdisabled)
             {
             #"Account diabled"
             $Enabled = "0";
      }
            else
            {  # "Account enabled"
            $Enabled = "1";
            }
           
      }
    }
    $Results = New-Object Psobject
    $Results | Add-Member Noteproperty Status $Status
      $Results | Add-Member Noteproperty AccountEnable $Enabled
    Write-Output $Results   
}

Example how to use the function Check-ADUser:

$AccountName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName]
.Value 
$SplitUserName = ($AccountName.Split("\")[1])
$UserName = $splitusername;
# check if user exists in AD
$UserExists = (Check-ADUser -Username $SplitUserName).Status;
$UserAccountEnabled = (Check-ADUser -Username $SplitUserName).AccountEnable;

if ($UserExists -ne 1)
 {
   #"User does not exist in AD"
 }
else
 {
   if ($UserAccountEnabled -eq 0)
    {
             #"Account is disabled"
    }
    else
    {
           #"Account is ok"
     }

I hope you will help this information.
Have a good day. :)

Tuesday, February 12, 2013

Create SharePoint Site Quota Templates using PowerShell

Original article

Here you can find PowerShell script that creates and changes Quota Template for Site Collection. You can find full original article here

Create SharePoint Site Quota Templates using PowerShell


function New-SPQuotaTemplate {
<#
    This advanced function creates a new Site Quota Template.
    This function uses .NET code to instantiate an instance of an
    SPQuotaTemplate class. Once the object is created, an instance of the
    SPWebService class is instantiated and the Quota Template is added to the
    Quota Templates Collection.
.Example
    C:\PS>New-SPQuotaTemplate -Name "Custom" -StorageMaximumLevel 2GB -StorageWarningLevel 1GB -UserCodeMaximiumLevel 100 -UserCodeWarningLevel 75
    This example creates an SP Quota Template called Custom with a maximum size
    of 2GB and a warning size of 1GB. Sandboxed solutions are
    limited to 100, with a warning level of 75.
.Example
    C:\PS>New-SPQuotaTemplate -Name "Custom" -StorageMaximumLevel 4GB -StorageWarningLevel 3GB
    This example creates an SP Quota Template called Custom with a maximum size
    of 4GB and a warning size of 3GB
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][String]$Name,
[Parameter(Mandatory=$true)][Int64]$StorageMaximumLevel,
[Parameter(Mandatory=$true)][Int64]$StorageWarningLevel,
[Parameter(Mandatory=$false)][System.Double]$UserCodeMaximumLevel,
[Parameter(Mandatory=$false)][System.Double]$UserCodeWarningLevel
)
# Instantiate an instance of an SPQuotaTemplate class #
Write-Host "Instantiating an instance of an SPQuotaTemplate class"
$Quota = New-Object Microsoft.SharePoint.Administration.SPQuotaTemplate
# Set the Properties #
Write-Host "Setting properties on the Quota object"
$Quota.Name = $Name
$Quota.StorageMaximumLevel = $StorageMaximumLevel
$Quota.StorageWarningLevel = $StorageWarningLevel
$Quota.UserCodeMaximumLevel = $UserCodeMaximumLevel
$Quota.UserCodeWarningLevel = $UserCodeWarningLevel
# Get an Instance of the SPWebService Class #
Write-Host "Getting an instance of an SPWebService class"
$Service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
if ($Service.QuotaTemplates[$Name] -eq $null )
{
# Use the Add() method to add the quota template to the collection #
Write-Host "Adding the $($Name) Quota Template to the Quota Templates Collection"
$Service.QuotaTemplates.Add($Quota)
# Call the Update() method to commit the changes #
$Service.Update()
}
else
{
Write-Host "Quota Template $Name exists"
}
}

To change the quota template for a site collection by using Windows PowerShell

function Set-SPQuotaTemplate ($SiteCollectionName,$QuotaTemplateName)
{
    Set-SPSite -Identity $SiteCollectionName -QuotaTemplate $QuotaTemplateName 
Write-Host "Quota template $QuotaTemplateName was set to site collection $SiteCollectionName"
}