Sunday, November 10, 2013

The transaction log for database 'Sharepoint_Config' is full

The above problem i faced serveral times earlier and that lead me to post it here for someone who is looking for solution.

Solution : 

1. On your SQL Server -> open the SQL Server Management Studio.

2. Connect to the local SQL Server

3. Right click SharePoint_Config -> Properties -> Options.  Change Recover Model from Full to Simple.

4.  Click OK.

5. Right click SharePoint_Config, go to Tasks -> Shrink -> Shrink Files.  Select a File type of Log, then Shrink

This should solve the problem.

Thank you !!!

Wednesday, September 4, 2013

SPSite.usage returning null or zero

Here is the small issue i faced and found the solution after 4 hours struggle.

Scenario : I came accross a requirement create a powershell script to get the site usage in MB for all the site collections in a web application.

Below is the code to get the same :

$usage = $spSite.usage.storage/1MB

Issues : when i ran the above script most of the site collections the it is returning null / zero. When i check the same using STSADM enumsites command it is again diffarent.

Solution : Log off from the server re login as farm administrator account.


Conclusion : Farm administrator who has full control on all the SQL, SharePoint can only be allowed to pull the information.

SharePoint Programatically get site quota template name

Here is the script to get the site collection quota template details using powershell.

$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService

$quotaTemplate = $contentService.QuotaTemplates | where {$_.QuotaID -match $spSite.Quota.QuotaID}

write-host $quotaTemplate.Name
  
Thank you !!! 

powershell script relative path


Here is the sample code to get the relative path of the powershell script which will help to make consistency when you run script files in multiple environments.

function scriptDirectory()
{
   $path = ""
   $path = [IO.Path]::GetFullPath((join-path $MyInvocation.ScriptName ".\.."))
   return $path
}


The above function will return the script file path as a string value.

One or more field types are not installed properly. Go to List settings page to delete these fields. Error while viewing Manage Content and Structure Page

In SharePoint 2010 publishing site,  when you go to Site Settings -> Manage Content and Structure menu, you will get an error message saying One or more field types are not installed properly. Go to List settings page to delete these fields with an associated correlation ID.

Root cause :
  • The publishing site uses SharePoint Server Publishing Infrastructure to support the publishing features in SharePoint.
  • This feature automatically creates an internal List “Relationships List” which is used to store the variations details.
  • This list is normally not visible in View All Site Content menu but you can browse it through the url http://site_url/Relationships%20List/allitems.aspx.
  • The actual issue is after migration of the site, the list will have a column GroupId which is of type Text. But actually it should be GroupGuid with type as GUID.
  • So we need to resolve this column name & type inconsistency.
Solution for the Issue :
  • You will not be able to delete and re-create the column since SharePoint doesn’t support creation of column of type GUID through UI.
  • So only way is to delete and re-create the list.
  • Go to Site Settings -> Modify All Site Settings -> Site Collection Features and deactivate SharePoint Server Publishing Infrastructure feature.
  • This removes the association between the feature and the Relationships list, which allows you to delete the list.
  • Navigate to the URL http://site_url/Relationships%20List/allitems.aspx and delete the list from the list settings.
  • Now go to site collection features and activate the SharePoint Server Publishing Infrastructure feature.
  • Note that Relationships list will be created automatically. You can check the same by navigating to the URL as states above.
  • You can check the list containing the column GroupGuid of type GUID.
Now check your Manage Content and Structure page which will be working fine. Hope it helps

Please refer to the actual post on this issue from this blog

Thank you !!


SharePoint Create new site One or more field types are not installed properly. Go to List settings page to delete these fields

Here is the issue usually comes when you migrate sites from 2007 to 2010 using SPContentDatabase mount operation.

This issue is an intermittent and not exists for all the site collections and not sure about why investigating more on this.


Root cause :
  • The publishing site uses SharePoint Server Publishing Infrastructure to support the publishing features in SharePoint.
  • This feature automatically creates an internal List “Relationships List” which is used to store the variations details.
  • This list is normally not visible in View All Site Content menu but you can browse it through the url http://site_url/Relationships%20List/allitems.aspx.
  • The actual issue is after migration of the site, the list will have a column GroupId which is of type Text. But actually it should be GroupGuid with type as GUID.
  • So we need to resolve this column name & type inconsistency.
Solution for the Issue :
  • You will not be able to delete and re-create the column since SharePoint doesn’t support creation of column of type GUID through UI.
  • So only way is to delete and re-create the list.
  • Go to Site Settings -> Modify All Site Settings -> Site Collection Features and deactivate SharePoint Server Publishing Infrastructure feature.
  • This removes the association between the feature and the Relationships list, which allows you to delete the list.
  • Navigate to the URL http://site_url/Relationships%20List/allitems.aspx and delete the list from the list settings.
  • Now go to site collection features and activate the SharePoint Server Publishing Infrastructure feature.
  • Note that Relationships list will be created automatically. You can check the same by navigating to the URL as states above.
  • You can check the list containing the column GroupGuid of type GUID.
Now check your Manage Content and Structure page which will be working fine. Hope it helps

Please refer to the actual post on this issue from this blog

Thank you !!

Error Deleting Site Collection The system cannot find the path specified

Here is the interesting issue i came across while doing some migrations.

Post migration when i try to delete site collections from SP 2007 envionment, I deleted a site collection which is huge in size the operation went for such a long time and finally resulted failure to delete the site collection.

After that when i see the site collection from CA i see the site collection listed in CA but none of the properties for the site collection were listed there like Title, URL, Description, Database name.
All the above properties were empty.

An error like this prevents you from upgrading SharePoint aswell, because you won't be able to access the site collection either

Root cause :  The site collection deleted from content database but some references still there in database.

Solution :

1. Execute database repair command : 

Execute the following two commands one after one.

STSADM.EXE -o databaserepair -url "url of the application" -databasename "Name of the DB" >"C:\Result.txt"

STSADM.EXE -o databaserepair -url "url of the application" -databasename "Name of the DB" -deletecorruption

First command should result as <OrphanedObjects Count="0" />

2. Delete and add Content DB : 

To resolve the error, detach and attach the content database of the afflicted site collection.

stsadm -o deletecontentdb -databasename "DB name" -url "site collection url"

stsadm -o addcontentdb -databasename "DB name" -url "site collection url" 

NOTE : Executing above script will not delete anything in the content database except the issue causing things or partially deleted site collections.

After this you can go and check in CA and found the site collections deleted completely. 

Thank you !!!


 



Thursday, August 22, 2013

sharepoint powershell get all web applications

function GetAllWebApplications()
{
 
  write-host "Sitecollection List Extraction started...." -foregroundcolor yellow
  $contentWebAppServices = (Get-SPFarm).services |
  ? {$_.typename -eq "Microsoft SharePoint Foundation Web Application"}

  foreach($webApp in $contentWebAppServices.WebApplications)
  {
  Write-Host "Web Application : " $webApp.name
 
 } 

PowerShell script to get all site collections details in web application

function GetAllWebApplications()
{
 
 write-host "Sitecollection List Extraction started...." -foregroundcolor yellow
 $contentWebAppServices = (Get-SPFarm).services |
 ? {$_.typename -eq "Microsoft SharePoint Foundation Web Application"}

 foreach($webApp in $contentWebAppServices.WebApplications)
 {
 Write-Host "Web Application : " $webApp.name
 
 #Fetch the site collections from the web application.
 GenerateAllSitecollectionsInWebapplication $webApp.Url 
 } 
}


function GenerateAllSitecollectionsInWebapplication ($url)
{
 
 try
 {
 $Site=Get-SPSite $url -ErrorAction SilentlyContinue
 $spWebApp = $Site.WebApplication
 $TotalList = @()
 $logfilepath = scriptDirectory
  
 foreach($spSite in $spWebApp.Sites)
 {
  $list = $spSite.url
 #write-host $list -foregroundcolor green 
  
 #Code to get the storage used in MB's
 [int]$usage = $spSite.usage.storage/1MB
 
 #Code to get the quota template name
 $contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
 $quotaTemplate = $contentService.QuotaTemplates | where {$_.QuotaID -match $spSite.Quota.QuotaID}
 
 #write-host $spSite.RootWeb.Title "|" $spSite.Url "|" $spSite.ContentDatabaseName "|" $usage "|" $spSite.Quota.QuotaID
 $outputString += $spSite.RootWeb.Title
 $outputString += " | "
 $outputString += $spSite.Url
 $outputString += " | "
 $outputString += $spSite.ContentDatabase.Name
 $outputString += " | "
 $outputString += $usage
 $outputString += " | "
 $outputString += $quotaTemplate.Name
 
write-host $logfilepath $outputString
 
 } 
 }
 catch
 {
 write-host "Unable to Extract Sitecollection List..." -foregroundcolor red
 break
 }
}

Monday, August 5, 2013

SharePoint Word Web App cannot open this document for viewing because of unexpected error. To view this document open it in Microsoft Word

Here is the one of the strange issue i cam acoross in my SharePoint environment.

When we try to open the documents / power point files in SharePoint site i see its not opening some of the files and throwing the below error and the same is working for other files.

NOTE : this issue is only when you try to open the document within the browser. if you check in google it will give you some different message.






Below are the error details :
Word Web App cannot open this document for viewing because of unexpected error. To view this document open it in Microsoft Word

Resolution : 
There are couple of resolution for this. below are the details one of these can work out for different scenarios.
1. Download such issue causing documents and change the latest version of the MS Office installed in your local machine then rename and again upload to the same location will work.

2. This might be a caching issue with in sharepoint.

  1. Every "Web App" have one site collection dedicated for Office Web App Cache except central admin.
  2. Office Web App settings are Shared within a particular Web App (even if site collections on the Web App have different Content Data Base), so plan office web app cache per web app.
  3. To set size of cache or delete the cache you need to use powershell
  4. Go to CA -> Application management -> View all site collections -> selete you web application and then
  5. check for site collection with URL /sites/Office_Viewing_Service_Cache and make sure it is there.
  6. Then open https://{webapp url }/sites/Office_Viewing_Service_Cache/cache here you will see the cached files of this web application. All these should be deleted using PowerShell.
3. Try adding some web.config entry to get rid of this issue like below :
<compilation optimizeCompilations="true">

try for any of the above solution one those might work for you.

Thank you !!


SharePoint PowerShell basic tips or help

Here are some of the tips in PowerShell were you can use PowerShell with more efficient way.

PowerShell Intellisece :
Power will also provide intellisece like all the other micrsoft devlopment tools by using some of the external tools PowerGUI is one of them.

In Windows 8 this is inbuilt functionality no need to do any integration for this.

PowerShell to text file :
Powershell file will also all the resulted output to a local text file same like other tools. Here is the small example on how to do this.

Get-SPContentDatabase >"C:\Files\output.xml"

PowerShell to Gridview output : 
This is the other addition from PowerShell where you can get the result in Output gridview with filtering and search option. Her is the sample code to run this.
Get-SPContentDatabase | Out-GridView

Personally i am a big fan of this feature.

PowerShell help :
Here is the sample to get the help for any command in Powershell with example.
get-Help Get-SPContentDatabase -example 

Read inputs for PowerShell script file :
Scenario :
You have created a script file with a function named AddIntegers(). this function will take inputs from the input file in the script file location. This file placed in folder "D:\SourceCode\PowerShell\Test.ps1"
Input file is also placed in the same location.
Issue :
Usually PS script file will be executed from "C:\users\{Login account name}".
If you try to load the ps1 file by providing the location you will get an exception saying that the input file cannot be found in the "C:\users\{accountname}" location.
Solution :
First you need to traverse to the ps1 script file location in my case i need to traverse to "D:\SourceCode\PowerShell\Test.ps1" location then i can call ps1 file this time it should work without any errors.

Multiple PowerShell: 
We have multple PowerShell available for any 64 bit operating systems we have 2 PowerShell files available.one is for 32 bit and other is for 64 bit.
But interestingly, for both 64 bit or 32 bit operating systems by default PowerShell will locd from 32 bit setup file only.
Below are the paths for both the versions you can verify.
32 bit : C:\Windows\System32\WindowsPowerShell\v1.0
64 bit : C:\Windows\SysWOW64\WindowsPowerShell\v1.0
SharePoint PowerShell will be loaded from 32 bit only with the SP snap in PS file from C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration location.

Here are some of tips and i will keep update on this post further...



Resolving Missing References when upgrading to SharePoint 2010

When doing some migrations from SP 2007 to SP 2010 there are some issue we commonly find in Test-SPContentDatabase command.

Please find the some of the common issues we see in report and the workaround for the issues and also solutions for the same.

Missing Site definition:
Log entry : Sites in database {} has reference(s) to a missing site definition, Id = {}, Lcid = {}. Remedy: The site definitions with Id {} is referenced in the database {}, but is not installed on the current farm. The missing site definition may cause upgrade to fail. Please install any solution which contains the site definition and restart upgrade if necessary
SQL query to fetch the details :
select fullurl from webs where webtemplate = {Template id from the above error message}
Resolution : Try to open the sites url got from the above query and see if site works as expected if not delete site and perform the migration.

Missing Features : 
Log entry : Database {} has reference(s) to a missing feature: Id = {}. Remedy: The feature with Id {} is referenced in the database  {}, but is not installed on the current farm. The missing feature may cause upgrade to fail. Please install any solution which contains the feature and restart upgrade if necessary.
SQL query to fetch the details :
select fullurl, description from features join webs on (features.webid = webs.id) where featureid = { Feature ID }
Resolution : Open the Url and see all the feature related files were placed in the new envrionment if not place all the feature related files on all the WFE servers. If still problem persists deactivate the feature and perform the migration. Then insall the same feature in new environment separately.

Missing Setup File

Log Entry:
File {} is referenced [1] times in the database {}, but is not installed on the current farm. Please install any feature/solution which contains this file. Remedy: One or more setup files are referenced in the database {}, but are not installed on the current farm. Please install any feature or solution which contains these files.
SQL Query : 
select * from AllDocs where SetupPath like '%{ Path got from above error message}%'

Resolution : Mostly this issue will occur only when you try to perform a migration on a site collection / sub site which is not accessibly or corrupted sites. Please fix the issues in current site / sub site or delete the issue causing sites and perform migration.

Missing Web Part

Log Entry:
WebPart class {} is referenced [1] times in the database {}, but is not installed on the current farm. Please install any feature/solution which contains this web part. Remedy: One or more web parts are referenced in the database {}, but are not installed on the current farm. Please install any feature or solution which contains these webparts.
SQL Query : 
select s.fullurl, d.DirName, d.leafname, tp_ZoneID, tp_partOrder
from webparts p
join alldocs d on (p.tp_PageUrlID = d.ID)
join sites s on (s.id = p.tp_siteid) 
where tp_WebPartTypeId  = ‘{ WebPart ID from aove error message }’
Resolution : 
You can get the site that has the web part. You will usually see that the web part does not render properly or says something about an error for a particular web part. That is usually the issue. it can be a bit tricky if everything looks ok though. In other words you may not see the issue on the site though. The problem in this case is usually that someone has closed a web part instead of deleting it.
There are two ways to delete the web parts.
  1. Add a ?contents=1 to bring up the Web Part Maintenance page. Click the ones that says Error and then click the Delete button. Much simpler
  2. To delete it you need to add it back to the page and then delete it. To add them click the Add a web part button on one of the zones and then click the Advanced Web Part gallery and options link at the bottom right on the screen. Then in the Add Web Parts panel that shows up on the page, click the Closed Web Parts collection. The web parts that have errors will say (Web Part Error) in the list of web parts before you add them.

NOTE: The query also has the zone id which tells you what zone it is in. This is usually something life left, right, top, bottom, etc. You can use this to get an idea of where on the page the web part is. The problem is that if it was closed it appears to show the last zone it was part of instead of null or something like that. Each zone can have multiple web parts. The order that they are displayed is shown in the partOrder. 1 = first, 2 = second, etc.



Missing Assembly

Log Entry:
Assembly {} is referenced in the database {}, but is not installed on the current farm. Please install any feature/solution which contains this assembly. Remedy: One or more assemblies are referenced in the database {}, but are not installed on the current farm. Please install any feature or solution which contains these assemblies.
SQL Query : 
SELECT s.fullurl, webs.fullurl, assembly, hostType
from EventReceivers e
join webs on (e.webid = webs.id)
join sites s on (s.id = e.siteid)
where Assembly = ‘{ webpart 4 part details from the above errror message}'

Comments: 
I went to the url (that I got from the query above) and investigated. I didn’t find that very useful. Then I looked at the hostType column in the results and in my case had a value of 2. Which according to the Microsoft reference is for a list. So, I used SharePoint Manager to go to each of the lists for the site and looked at the EventReceivers Property (Collection). You can then delete the appropriate Event Receiver using Powershell. Do the deletion at your own risk. I tried it on a copy of the content database and I didn’t see any adverse effects, and I have read that others have done it also, but it seems a bit risky to me in general. Try this on a copy of your content database before you do it on production would be my recommendation. You can also use SharePoint Manager to delete any hidden lists which have the EventReceiver. Again, use caution. If this is not a show stopper, you may consider just leaving the issue alone. That is what I did in my production environment since I was to chicken.

NOTE : I have taken some of the msdn references and also JustGeeks blog spot for the references for the solutions mentioned above and changed as per my personal experience on the same.

Thank you !!!

Propramatically create wiki pages in sharepoint



Here is the sample peace of code to create wiki pages libary in sharepoint

 public void CreateWikiPagesLibray(SPWeb web)
        {
            try
            {
               // SPList list = web.Lists.TryGetList("Site Pages");
                SPList list = web.Lists.TryGetList("EID");
                if (list == null)
                {
                    SPListTemplate template = web.ListTemplates["Wiki Page Library"];
                    Guid listID = new Guid();
                    listID = web.Lists.Add("EID", "", template);
                    list = web.Lists[listID];
                    list.OnQuickLaunch = true;
                    list.Update();
                }

            }
            catch (Exception ex)
            {
                throw new SPException(ex.ToString());
            }
        }



This is the code to create wiki page in library

 public void CreateWikiPage(SPList list, string pageTitle, int layoutTemplate)
        {
            try
            {
                SPFolder rootFolder = list.RootFolder;
                SPFile wikiPage = rootFolder.Files.Add(String.Format("{0}/{1}", rootFolder.ServerRelativeUrl, pageTitle), SPTemplateFileType.WikiPage);
                SPListItem wikiItem = wikiPage.Item; 
                //wikiItem[SPBuiltInFieldId.WikiField] = "My Wiki Page with [[wiki link]]"; 
                wikiItem.UpdateOverwriteVersion(); 
            }
            catch (Exception ex)
            {
                throw new SPException(ex.ToString());
            }
        }



Thank you !!!

C# code to reset permissions of webpart page in sharepoint



Here is the small peace of code to reset the permissions of a sharepoint page.

Following are the steps i am doing here.

1. Breaking the role inheritance
2. Remove all the permissions of the file
3. Giving access to only the site owners group

public void ResetASPXPagePermissions(SPFile file, SPWeb web)
        {

            file.Item.BreakRoleInheritance(true);

            SPRoleAssignmentCollection SPRoleAssColn = file.Item.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssColn.Remove(i);
            }
            SPGroup grp = web.AssociatedOwnerGroup;
            if (grp != null)
            {
                SPRoleAssignment Assignment = web.RoleAssignments.GetAssignmentByPrincipal((SPPrincipal)grp);
                file.Item.RoleAssignments.Add(Assignment);
                file.Item.Update();
            }
            
        }

Thank you !!



SharePoint PowerShell deactivate feature site collection

Please find the code to deactivate features at site collection level.

[System.Reflection.Assembly]::LoadWithPartialName("System.Xml")


function Feature_Deactivation_sitecollection($featName)
{
    try
    {
                   
        [xml]$userfile = Get-Content C:\Site.xml
        Write-Log "Feature_Deactivation_sitecollection" "Process started.."
       
        foreach($site in $userfile.Sites.Site)
        {   
            $url = $site.Url
            $spSite=Get-SPSite $url
               
                $Featuretobeactivated = Get-SPFeature -Site $spSite.Url | Where {$_.DisplayName -eq $featName}
               
               
                if($Featuretobeactivated -eq $null)
                {
                    Write-Log "Feature_Deactivation_sitecollection" "Feature not active in "$site.Url                                     
                    Write-host -foregroundcolor green "Feature not found "
                }
                else
                {
                    Disable-SPFeature -Identity $featName -Url $spSite.Url –Confirm:$false
                    Write-Log "Feature_Deactivation_sitecollection" "Feature deactivated in site collection "$site.Url
                    write-host -foregroundcolor green "Feature deactivated successfylly "$site.Url
                }
        
        }
       
        Write-Log "Feature_Deactivation_sitecollection" "Operation completed successfully.."
        write-host -foregroundcolor green "Operation completed succesfully.."
       
    }
    catch [System.Exception]
    {
        write-Host -foregroundcolor red "Exception: "$_.Exception
    }
}

function Write-Log($FunctionName,$message)
{       
    $now = Get-Date -Format "dd-MMM-yyyy HH:mm:ss"
    $now + "`t$message" >>  .\$FunctionName.txt
}

Thank you !!


SharePoint PowerShell Deactivate feature sub site level

Here is the peace of Powershell code for that


[System.Reflection.Assembly]::LoadWithPartialName("System.Xml")


function Feature_Deactivation_subsites($featName)
{
    try
    {
   
        [xml]$userfile = Get-Content C:\Site.xml
        Write-Log "Feature_Deactivation_subsites" "Process started.."
       
        foreach($site in $userfile.Sites.Site)
        {   
            $url = $site.Url
            $spSite=Get-SPWeb $url
            DeactivateFeature $spSite $featName
      
            foreach($web in $spSite.Webs)
            {   
                DeactivateFeature $web $featName
                 Write-Log "Feature_Deactivation_subsites" "Feature deactivated in web "$web.Url
            }         
           
        }
        Write-Log "Feature_Deactivation_sitecollection" "Operation completed successfully.."
        write-host -foregroundcolor green "Operation completed succesfully.."
       
    }
    catch [System.Exception]
    {
        write-Host -foregroundcolor red "Exception: "$_.Exception
    }
}
function DeactivateFeature($web, $featName)
{
        $Featuretobeactivated = Get-SPFeature -Web $web.Url | Where {$_.DisplayName -eq $featName}
        $webURL = $web.Url
                   
        if($Featuretobeactivated -eq $null)
        {
           
            Write-Host "Feature not found "$webURL
            Write-Log "Feature_Deactivation_subsites" "Feature not active in $webURL"
        }
        else
        {
            Disable-SPFeature -Identity $featName -Url $web.Url –Confirm:$false
            Write-Log "Feature_Deactivation_subsites" "Feature deactivated in web "$webURL
            Write-host -foregroundcolor yellow "Feature deactivated at web "$webURL
        }
}

function Write-Log($FunctionName,$message)
{       
    $now = Get-Date -Format "dd-MMM-yyyy HH:mm:ss"
    $now + "`t$message" >>  C:\$FunctionName.txt
}

Thank you !!


sharepoint designer email html format

Here is the some peculiar scenario i will explain about sharePoint designer.

When we create a sharepoint designer workflow with send email functionality. Email body format will not behave as expected most of the times.

Alignments will not work even though you set it to align 'top' bottom'

This is the wired behavior.

Solution :
The solution for that is very simple and interesting. You need to put your html code in a single line. i.e

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

This will cause alignment issue.

<table border="1"><tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr><tr>td>row 2, cell 1</td><td>row 2, cell 2</td></tr></table>

Aboue code will fix this alignment issue in Designer email format. Everything should be in one line.


Thank you !!!


PowerShell SPWeb.Webs exception has been thrown by the target of an invocation

When I am working with PowerShell to do some operations on sub sites I found the below issue :

Code for this issue :

foreach($web in $MainWeb.Webs)
{

}


In the above code $MainWeb.Webs is throwing error.

Issue :
Exception has been thrown by the target of an invocation

Cause :
I have done so much work around for this issue. Finally figured out that issue is because of the Permissions.

Resolution :
Script executor / Remote server login user must be site collection administrator to get rid of this error.

Thank you !!!

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 
"http://teams" 


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

Thank you !!