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 !!!