Monday, July 8, 2013

Sharepoint programatically activate feature if it is not active and instaled

Here is a small code sample which will activate featrue using C#

In this sample we i am checking feature is activated or not and installed or not before trying to activate

// This is to check if feature is installed or not
if (SPFarm.Local.FeatureDefinitions[new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb")] != null)

//This is to check feature is activated or not
  if (web.Features[new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb")] != null)
  web.Features.Remove(new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"));

Thank you !!!

Friday, July 5, 2013

Restore-SPSite : The operation that you are attempting to perform cannot be completed successfully

Issues : 

Deleted a site collection and try to restore the same site collection with the Restore-SPSite command in SharePoint you will get the below error :

Restore-SPSite : The operation that you are attempting to perform cannot be completed successfully.  No content databases in the web application were available to store your site collection.  The existing content databases may have reached the maximum number of site collections, or be set to read-only, or be offline, or may already contain a copy of this site collection.  Create another content database for the Web application and then try the operation again.
Root cause :

This is because even though you delete a site collection from CA. It will be deleted from the content database from front end. But logically that site collection still be there in database. This can be restored from Recycle bin but not able to do further migrations.

Please execute Get-SPDeletedSite command from PowerShell it will list all the site collections deleted from CA like the below report :

WebApplicationId   : 2f210dbb-f6bb-43d2-b730-9cb61222cbdb
DatabaseId         : 213a1719-929b-420c-89f8-d03f52a06bc7
SiteSubscriptionId : 00000000-0000-0000-0000-000000000000
SiteId             : 5ce0264c-1dad-4ffa-8360-8195i24dac69
Path               : /teams/Test2
DeletionTime       : 7/4/2013 6:30:36 AM

Solution :
Solution for this is just 2 steps :
1. Remove the site collection permanently from database.
2. Run the Gradual site delete timer job for immediate effect

Remove site collection permanently from datbase :
this can be achieved by simple PowerShell script
Remove-SPDeletedSite –Identity 5ce0264c-1dad-4ffa-8360-8195i24dac69

Run the Gradual site delete timer job for immediate effect :
After that Get-SPDeletedSite won't show this site collection, but Restore-SPSite will still give the same error.

So , go to  Central administration > Monitoring > Job definitions and run the “Gradual Site Delete” job for the web application where you are trying to restore the site collection.

After that wait some time (depends on the size of your site collection) and try to restore site collection again. This time it should work without problems.

Thank you !!!

Thursday, July 4, 2013

sharepoint split content database

This is one of the requirement you will get when you work with large scale environments.

Split of content databases between site collection.

Here are the steps to perform this operation :

1.       Create a new content database in web application. Content database should be mapped to web application.

2.       Make sure executer should have full control on both the content databases.

3.       Perform enum command to get all the sites collections in the web application
Stsadm.exe –o enumsites –url “{web app url } > “Local path to save the output in xml format”

4.       The above command will get all the site collections in the web application.

5.       Remove all the site collection url from the xml files except that you want to move Content database. All the entries should have only one source database names.

6.       Limitation of entries in xml file is 1000

7.       Perform IISRESET

8.       Per form PrepareToMove command to make the sync in profiles before you do the actual split
stsadm -o preparetomove -contentDB SQLServer01:ContentDB name

9.       Now you can perform the analyzing of split databases operation with the following command.
Stsadm -o mergecontentdbs –url {web app url} –sourcedatabasename {Source DB name } -destinationdatabasename {Destination DB name } –operation 1 –filename C:\MySiteURLs1.xml

10.   The above command will give you the estimation of the split operation if any errors or warnings will be listed there.

11.   After that you can perform the actual split operation with the command given.

1     Stsadm -o mergecontentdbs –url {web app url} –sourcedatabasename {Source DB name } -destinationdatabasename {Destination DB name } –operation 3 –filename C:\MySiteURLs1.xml

Observations / Limitations:

1.       Action performer must have full control on both the databases and he must have farm admin, local administrator and site collection administration rights to perform this operation.

2.       This operation cannot be performed more than 1000 sites in single shot.

3.       IIS must be restarted before and after the operation.

4.       Site collection might not be accessible until the operation completes.

5.       Both the content databases must be in same SQL instance and must be attached to same web application.

6.       As per MSDN this operation might through errors if the site collection size is more than 10 GB

7.       Action performer account must have db_owner permissions in SQL Server.

8.       Search crawl, Profile crawl must stop before performing this operation.

Known errors/issues:

1.       Ensure that data is synchronized between the profiles feature and the sites in the databases

2.       Navigation may fail some times ( Global navigation , left navigation )

3.       Always back up the source and target databases before you use the STSADM MergeContentDBs command

4.       Run the STSADM MergeContentDBs command during off-peak hours because the STSADM MergeContentDBs command places significant additional load on the server that is running SQL Server.

5.       Some articles were confirming that this command may result in data loss. Please find the reference link below :

6.       Audit logs might be created at server end with huge in disk size occupation. Please find the reference below :

c# console application relative path

Here is the one of the common requirement i am going to explain.

I have a requirement to create a console application in that exe file should read input from xml file.

After developing that application i hardcoded and it is working fine in Dev box.

Now, when we move the exe file to production it is failing because of the path not found issue.

After that i changed the code to read file from exe file loaction with an absolute path.

Here is the peace of code for that

 string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();

In the above code String Path will get the location of the exe file where ever it is irrespective of the folder or environment.

Thank you !!

Copy dll from GAC

Here is an requirement i came across lot of time. Every time i used to Google for sometime.

Sometimes, we need to copy the assembly from GAC to our local folder or application.

Wasted lot of time for this. I am giving the solution for this.

Go to run -> type "C:\Windows\assembly\gac_Msil"

Your GAC will be opened as folder structure and you can copy your assemblies easily.

Thank you !!!

Alerts not working in sharepoint 2010 after migration

Here is the one issue we will face post migration from 2007 to 2010 or 2010 to 2013

Issue : In SQL database the alerts still refer to old URL's post migration. You can find this from SQL instance by executing the below SQL query

select WebUrl,Properties from immedsubscriptions

This can be fixed by executing a PowerShell script from Kirk stark msdn artcle

NOTE : Save the file, naming it Invoke-AlertFixup.ps1.You must use the provided name or the script will fail, and you must save the file as an ANSI-encoded text file.

Execute the Script report before Actual Replacement :
Invoke-AlertFixup -site "http://teams/sites/newteam"  -Oldurl 
"http://teams/sites/oldteam" -whatif
Actual URL replacement : 
Invoke-AlertFixup -site "http://teams/sites/newteam"  -Oldurl 

After executing this script you can check the SQL server data you will find with the updated URL.

Thank you !!

PowerShell code to delete bulk users from SharePoint site

here is a simple code sample of PowerShell script to delete users from SharePoint site.

Function DeletePermissions($web)
         $usersToDelete = @("Domain\UserName")
         # Iterate through the site's users and add usernames to
            # an array of users to delete if the name contains
            # contains the username filter.
            foreach ($user in $web.SiteUsers)
                $UserName = $user.Name
                if($arrUsers -notcontains $UserName.ToLower() -and $UserName -notlike "*svc_*")
                    Echo $user.Name
                    $usersToDelete += $user.LoginName

                # Delete each user selected from the SiteUsers array.
                # The SiteUsers array can't be iterated through directly
                # as it gets changed as users are removed from it.
                foreach ($user in $usersToDelete)
                 "Removing user : " + $user


powershell add bulk users to sharepoint site

Here is a simple PowerShell script code to add multiple users to SharePoint site

Function AddUsers($web)
    $AccountList = @("Domain\user1","Domain\user2")
    # Get the site owners group from web
    foreach($Group in $web.SiteGroups)
        if($Group.Name -like "*Owner*")
           $MyGrp = $web.SiteGroups[$Group.Name] 

    #Add the array users to Site owners group.
    foreach ($Account in $AccountList)
        $user1 = $web.Site.RootWeb.EnsureUser($Account)
        Write-host "$Account was added as admin " $web.Url -Foregroundcolor DarkGreen

Thank you !!

SharePoint programmatically get custom workflows in sharepoint

Here i comes to a requirement as part of some migrations.

I need to get all the list of worflows in site collections and need to differentiate the list of SPD workflows and OOTB workflows.


foreach (SPWorkflowAssociation workflowAssociation in workflowCollection)
        string WorkflowType = string.Empty;
        if (workflowAssociation.BaseTemplate == null && workflowAssociation.InternalName.Contains("Xoml"))
        WorkflowType = "SPD";
        WorkflowType = "OOTB";
Console.WriteLine(workflowAssociation.ParentSite.Url + "$" + workflowAssociation.ParentList.DefaultViewUrl + "$" + workflowAssociation.Name + "$" + workflowAssociation.RunningInstances + "$" + WorkflowType);

Reference for this post has taken from one of my friends blog

Thank you !!