Monday, April 2, 2012

Troubleshoot Sharepoint Crawler with Fiddler

This Blog is simple but extremely useful (Thanks Matthew MCDermott):

http://www.ableblue.com/blog/archive/2012/01/04/troubleshooting-sharepoint-search-crawl

Find SPLists without Default View

One issues why sometimes the search crawler in SharePoint takes too long, is because of the lack of Default View on the lists form the Site. See the C# Code and explanation at
http://blogs.technet.com/b/victorbutuza/archive/2010/01/15/crawl-taking-indefinitely-to-complete.aspx
This is the power-shell version of the c# code shown on the mentioned site.

 
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear
$spwa = Get-SPWebApplication -Identity "http://myWebAppURL"
foreach ($osite in $spwa.Sites)
{
      foreach ($oweb in $osite.AllWebs)
      {
           write-host $oweb.Url
           write-host "========================================================="
           foreach ($olist in $oweb.Lists)
        {
            if ($olist.Hidden -eq $false)
            {
                  try
                {
                  write-host "Title: "  $olist.Title;
                    if ($olist.DefaultView -eq $null)
                    {
                                   write-host "ERROR: No default list view found " -ForegroundColor Red
                             }
                    else
                    { 
                        #remove this if you have lots of lists
                        write-host "DefaultViewURL: " $olist.DefaultViewUrl
                        write-host "DefaultViewTitle: " $olist.DefaultView.Title
                    }
                }
                catch
                {
                   write-host "ERROR"

                }
            }
            }
           write-host "========================================================="
        $oweb.Dispose();
      }
      $osite.Dispose();
}

Tuesday, March 27, 2012

Find out the attaches SPEventReceivers on a given SPList

Small script to find out what event receivers are attached to a given list / document library.
Of course, you don't need that if you can have the luxury of having SharePointManager on your server.

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear

$url = "https://myservername/mysite/mysubweb"
$listWebRelativeUrl = "/lists/thelist" # for a doc lib just "/DocLibName"

$site = Get-SPSite $url
$web = $site.OpenWeb()
$list =$web.GetList($web.ServerRelativeUrl + $listWebRelativeUrl)
$list.EventReceivers | foreach{write-host $_.Type " " $_.Name " " $_.ID}


$web.Dispose()
$site.Dispose()

Monday, March 26, 2012

Upload Douments in Document Library Sharepoint 2010

I needed to make some tests on Sharepoint Tresholds, so I needed a small script that uploads a large amount of documents (The same document) in my Doc Libraries.
For that I just created in the same folder where my Powershell script is running a small Test.txt file. And Uploaded it a given number of times under a new name.
Here's the script:

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear

$uploadURL = "http://MYWEBURL/"
$fileName = "test.txt"
$uploadLibraries = @("Documents", "Documents2")
#I'm Uploading to the root, but you could put there a folder like "Documents/FolderName"
#I want to uplaod 6000 docs on each library... that takes a while
$TOTALDOCSTOUPLOAD =6000
$startFileIndex = 0
$thisScriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$oldFilePath =  $thisScriptPath + "\" + $fileName
                   
$site = Get-SPSite -Identity $uploadURL
if($site -ne $null){
    $web = $site.OpenWeb()
      if($web -ne $null -and $web.Exists){
        foreach($uploadLibrary in $uploadLibraries)
        {
            try
            {
                $docLib = $web.GetFolder("/"+$uploadLibrary)
            }
       
            catch
            {
               write-host 'Document  Library is unavailable'
                $docLib = $null
            }
            for($i = $startFileIndex; $i -lt $TOTALDOCSTOUPLOAD; $i++)
            {
                if($docLib -ne $null)
                {
                    $fileParts = $fileName.split(".")
                    $fileParts[0] = $fileParts[0]+ $i.ToString()
                    $newFileName = [string]::join('.', $fileParts)
               
                    $newFilePath =  $thisScriptPath + "\" + $newFileName
                   
                    Rename-Item $oldFilePath $newFilePath
                    $docUrl = $docLib.ServerRelativeUrl + "/" + $newFileName
                    if($docLib.Files[$docurl].Exists)
                    {
                        $file = $docLib.Files[$docurl]
                        if($file.LockType -eq "None" -and $docLib.RequiresCheckout)
                        {
                                $file.CheckOut()
                        }
                    }
                    $fileStream =$((Get-ChildItem $newFilePath).OpenRead())
                    $docLib.Files.Add($docUrl, $fileStream, $true) | Out-Null
                    $file = $docLib.Files[$docurl]
                    if($file.CheckOutType -ne "None")
                    {
                       if($docLib.RequiresCheckout) {
                        $file.CheckIn("Updated Template", 1)
                        }
                    }
                    $fileStream.Dispose()
                    Rename-Item  $newFilePath $oldFilePath
                    write-Host "Uploade "$newFilePath "to "$uploadLibrary
                }
             }  
        }

        $web.Update()
        $web.Dispose()
    }
    $site.Dispose()
}


Wednesday, March 7, 2012

Enabling / Adding Sharepoint Search Autocompletion

Ever wonder how to get that Auto-completion to work on the SharePoint search box?


Select the Service application:

$srchSvcApp = Get-SPEnterpriseSearchServiceapplication -Identity "Search Service Application"

Add a new Suggestion:

$lang = "de-de"
$newQuerySuggestion = "Powershell for Sharepoint 2010"
 New-SPEnterpriseSearchLanguageResourcePhrase -SearchApplication $srchSvcApp -Language $lang  -Type QuerySuggestionAlwaysSuggest -Name $newQuerySuggestion

Run the time Job:
$querySugestionTimer=Get-SPTimerJob|? {$_.Name -eq "Prepare Query Suggestions"}

$querySugestionTimer.RunNow()


Tuesday, February 28, 2012

Get and Renaming SPFolder c#

This is how you can rename a SPFolder. There is no need to use MoveTo() as suggested by others.
The user has to have rights to do it, or enclose the whole thing inside a

var siteId = "Guid of my site";
var webUrl= "Server relative path to my web";
SPSecurity.RunWithElevatedPrivileges(delegate(){
    using (SPSite elevatedSite = new SPSite(siteId))
   {
       using (SPWeb elevatedWeb = elevatedSite.OpenWeb(webUrl))
      {

          string requestFolderUrl = webUrl+ "/MYLIST/OldFolderName";
          SPFolder requestFolder = elevatedWeb.GetFolder(requestFolderUrl);

          if (requestFolder.Exists)
          {

               requestFolderItem[SPBuiltInFieldId.Title] = "NewName"; //not really needed for renaming
               //requestFolderItem[
SPBuiltInFieldId.BaseName] =  "NewName"; //this Fails.don't know why
               requestFolderItem["BaseName"] =  "NewName"; //this Works!
               //don't want to update the Modified time nor the modified by Info
              //If you want to modify this info use Update, and avoid being in a RunWithElevatedPrivileges
             ///because else you would have the System User registered
               requestFolderItem.SystemUpdate(false);

           }
      }
   }
}

Thursday, February 16, 2012

Remove Event Handlers from SPList Powershell

This is how you can  delete Event handlers from a SPList

$webUrl= "http://yoursite.com/subsite"
$listName = "myList"

$site = Get-SPSite($siteUrl)
$web = $site.OpenWeb()
$listWithEventHandlers = $web.Lists[$listName]

#you can find out the index of the eventhadler through a selector, or just beeing lazy
#and loop the eventhanlders


 $allEvenReceivers  = $list.EventReceivers
foreach($ev in $allEvenReceivers  )
{
   write-host $ev.Name;
}
$index = 0
$eventHandlerToDelete = $listWithEventHandlers.EventReceivers[$index]$eventHandlerToDelete.Delete()
$listWithEventHandlers.Update()

$web.Dispose()
$site.Dispose()

Access MasterPage catalog with Powershell

To acces the Masterpage catalog via Powershell, and then use it as a list the following script might help

if(-not(Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"}))
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

clear
$siteUrl = "http://yourserver.com"

$masterPageCatalog = "_catalogs/masterPage"

$site = Get-SPSite $siteUrl

$rootWeb = $site.RootWeb;

$folder = $rootWeb.GetFolder($masterPageCatalog)

$masterPageCatList = $rootWeb.Lists[$folder.ParentListId]

#do some list operations on it


$rootWeb.Dispose()
$site.Dispose()

Wednesday, January 25, 2012

Reorder field in existing Contentype withPowershell

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"}))
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear
$dirURL = "Url of the Content Type"
$contentTypeName = "ContentTypeName"
$fieldInternalName= "Internal name of the field to reorder"
$field0BasedIndex = 8 #Position on the contentytpe this field is wanted

if($site -ne $null){
    $web = $site.RootWeb
    if($web -ne $null){
        $ct = $web.ContentTypes[$contentTypeName]
        if($ct -ne $null){
            write-Host "content Type Found"  -foregroundcolor green
           
            $fields = New-Object 'System.Collections.Generic.List[string]' ;
            [Microsoft.SharePoint.SPFieldLinkCollection]$flinks = $ct.FieldLinks;
            #Read all the InternalNames of the FieldLinks into a list
            foreach($fieldLink in $flinks){
             $fields.Add($ct.Fields[$fieldLink.ID].InternalName);
            }
            if($fields.Contains($fieldInternalName)){           
                write-Host "Field found in Content Type" -foregroundcolor green;
                $indexFound = $fields.IndexOf($fieldInternalName)
                if($indexFound -ne $field0BasedIndex )
                {
                    $fields.RemoveAt($indexFound)
                    #insert or append the field
                    if($field0BasedIndex -le $fields.Count -1){
                        $fields.Insert( $field0BasedIndex,$fieldInternalName)
                    }
                    else{
                        $fields.Add($fieldInternalName);
                    }
                    #Add the array to the reorder
                    $flinks.Reorder($fields.ToArray());
                    #Update the ContentYpe
                    $ct.Update($true)
                 }
            }
            else{
               write-Host "Field not found in Content Type" -foregroundcolor red;
            }
        }
        else{
            write-Host "Content type not found"  -foregroundcolor red
        }
        $web.Update()
        $web.Dispose();
    }
    $site.Dispose();
}

Insert new Site Column in existing Contentype with PowerShell

# Check if Snap-in is loaded
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$dirURL = "Type here the abolute Url to the Sitecollection where the contentytpe is defined"
$contentTypeName = "Traktandum"
$fieldId = [Guid]"{516ae749-c8b4-4a9b-858f-50881aae4165}"  
#fieldId mus match the one on the fieldXML

$site = Get-SPSite -Identity $dirURL
if($site -ne $null){
    $web = $site.RootWeb
    if($web -ne $null){
        #Assign fieldXML variable with XML string for site column
        $fieldXML = '<Field
    Description="$Resources:MyCustom,Field_MyPortalOtherGuest_Description"
    DisplayName="$Resources:MyCustom,Field_MyPortalOtherGuest_DisplayName"
    Hidden="FALSE"
    Name="SomeName"
    Title="SomeName"
    Required="FALSE"
    Sealed ="FALSE"
    Sortable="FALSE"
    List="UserInfo"
    ShowField="ImnName"
    Mult="TRUE"
    Type="UserMulti"
    UserSelectionMode="0"
    UserSelectionScope="0"
    ID="{516ae749-c8b4-4a9b-858f-50881aae4165}"
    Group="$Resources:MyCustom,Field_Group"
    StaticName="SomeName" />'
    
        #Add the field to the web
        $web.Fields.AddFieldAsXml($fieldXML)
        $web.Update()

        $field = $web.AvailableFields[$fieldId]
        $ct = $web.ContentTypes[$contentTypeName]
        if($field -ne $null -and $ct -ne $null){
            #Delete any existing Field with that ID from the ContentType
            $ct.FieldLinks.Delete($fieldId)
            #Update the Contentype includeing childs
            $ct.Update($true, $true)
            #Creat a new SPFieldLink for that field and insert it to the ContentType
            $link = new-object Microsoft.SharePoint.SPFieldLink $field            
            $ct.FieldLinks.Add($link)
            $ct.Update($true, $true)
        }
        $web.Update()
        $web.Dispose()
    }
$site.Dispose()
}

Tuesday, June 14, 2011

Swithc DB to Simple Recovery Mode

http://vstoolsforum.com/blogs/sqlserver/archive/2007/05/11/setting-the-recovery-model-of-a-database-to-simple.aspx

Simple and works perfectly.

Tuesday, May 3, 2011

GAC (Global Assebly Folder) empty- Trick to reenable

As my work is, I have to deploy x-times some assembly in my GAC and test it.

Well once in a while my assembly folder just seems empty, And then I can't  build / deploy my solution anymore.

Here is the trick: (It is not mine.. but the more places it is published, the easier you guy find it:)

Start your  windows services management console (services.msc) and restart the Indexing Service  and everything is back to normal.!

Cool... once agian.. it was not our fault... we where just working!

Tuesday, April 19, 2011

Faster VMWare

I was struggeling with the slowliness of my VMWare Workstation machine. I gave it 12 GB ram and 4 core processors
.
Well it turned out that assigning it more processors, actually made it slower. I reduced the processor to 1
 
I also modified some settings in the config.ini located in c:\programmdata\vmware\vmware workstation\
(This file might not exist if you have the default settings, so make any kind of settings in the VMWare to make the file appear)

installerDefaults.autoSoftwareUpdateEnabled = "yes"
installerDefaults.componentDownloadEnabled = "yes"
installerDefaults.dataCollectionEnabled = "no"
mks.ctlAltDel.ignore = "TRUE"
host.cpukHz = "3000000"
host.noTSC = "TRUE"
ptsc.noTSC = "TRUE"
prefvmx.minVmMemPct = "100"
datastore.name = "local"
defaultVMPath = "E:\DEV_Image"

datastore.localpath = "E:\DEV_Image\"

sched.mem.pshare.enable = "FALSE"
prefvmx.useRecommendedLockedMemSize = "TRUE"
prefvmx.minVmMemPct = "100"
priority.grabbed = "normal"
priority.ungrabbed = "normal"

security.host.ruissl = "FALSE"

mainMem.partialLazySave = "FALSE"
mainMem.partialLazyRestore = "FALSE"
mainMem.useNamedFile = "FALSE"

Isolation.tools.copy.enable = "true"
Isolation.tools.paste.enable = "true"
Isolation.tools.HGFS.disable = "false"

What these settings mean and what they are for you can look up  here
http://sanbarrow.com/vmx/vmx-config-ini.html

Thursday, April 14, 2011

Sharepoint 2010 Rename Assembly of WebPart

I came across of a new issue in SharePoint 2010 today. My client wished the web parts assembly name changed from some name A to some name B.
Well I thought easy, rebuild the web part, verify that the web part file is correct, retract old solution, deploy new solution (Web part is deployed as feature).
Well... When I inserted the web part with the new name everything worked. but all the pages that had the web part already inserted stopped working, saying that the type was not found.
The old web parts where trying to load the old assembly.
After looking and "googling" I didn't find any solution.. So my last resource... change the entry on the Content DB.  Here is the script

UPDATE
[SiteCollection_Content_DB].[dbo].[AllWebParts]SET [tp_WebPartTypeId] ='NewWebPartTypeId',[tp_Assembly] = 'NewAssemblyBaseNamespace, Version=NewVersion, Culture=neutral, PublicKeyToken=newtoken',[tp_Class] = 'NewCompleteClassNameWithNamespace'
[tp_Class]
WHERE [tp_Assembly] = 'OldAssemblyBaseNamespace, Version=OldVersion, Culture=neutral, PublicKeyToken=oldtoken' and = 'OldCompleteClassNameWithNamespace' and[tp_WebPartTypeId] ='OldWebPartTypeId'
To  know the new values I just inserted one web part with the new dll and copied the values form the record I found on the AllWebParts table .


I strongly recommend though to make a backup of your DB!
I actually never touch the DB of SharePoint. I even convinced my client not to change the Assembly name... But still I tried the script in my Dev environment and it seemed to work.




UPDATE: Wow.. why do it the Unsupported way!... there is the supported way: Open your webApplication, loop through all of your sites & webs. Open each page, check if the webpart's in it, if so get the position(s) of the current web part(s). remove it (them) and insert the new webpart(s) with the new definition in the position(s) fetched.
 

Monday, April 11, 2011

Powershell Script to insert large amount of ListItems in Sharepoint List

A small script I wrote to insert a large amount of items in a custom list. It is just for testing purposes, so I can learn a little bit more about optimizing SPQueries and about ListView thresholds.

if((Get-PSSnapin -Name Microsoft.Sharepoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.Sharepoint.PowerShell
}
clear
#Get-Command  -Module Microsoft.Sharepoint.PowerShell
$assignment = Start-SPAssignment
$webUrl="http://myweburl/"
$listName = "OneMillionRecords"
$spWeb = Get-SPWeb -Identity $webUrl -AssignmentCollection $assignment
$template = $spWeb.ListTemplates["Custom List"] 
$listId=$spWeb.Lists.Add($listName,"List with one million records",$template)
$spNewList = $spWeb.Lists[$listName]
$spFieldTypeText = [Microsoft.SharePoint.SPFieldType]::Note
$spFieldTypeNumber = [Microsoft.SharePoint.SPFieldType]::Number
$spNewList.Fields.Add(“Description”,$spFieldTypeText,$false)
$spNewList.Fields.Add(“ItemNr”,$spFieldTypeNumber,$false)
$i =1
$max = 1000000
while ($i -le $max) {
$j=$i.ToString()
$title="Item $j"
$itemNr=$i
$description="The Item is called Item $j and is stored with some useless text"
$newItem=$spNewList.items.Add() 
$newItem["Title"] = $title
$newItem["ItemNr"] = $itemNr
$newItem["Description"]=$description
$newitem.Update()
Write-Host $title
$i=$i+1
}
#Dispose all objects
Stop-SPAssignment $assignment

Saturday, April 9, 2011

PowerShell: Create Users in active directory and Sharpoint 2010

Small powerschell script that creates an amount of users in the Active Directory and inserts them in the Sharepoint 2010

Import-Module ActiveDirectory
if((Get-PSSnapin -Name Microsoft.Sharepoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.Sharepoint.PowerShell
}
#Get-Command -Module ActiveDirectory
clear
$i =3
while ($i -le 100000) {
$j=$i.ToString()
$username="Dev$j"
$webUrl="http://sharepoint website url/"
$group="Development Owners"

New-ADUser -SamAccountName $username -Name $username -UserPrincipalName "$username@domain.com" -DisplayName "$username User" -GivenName $username -Surname "User" -AccountPassword (ConvertTo-SecureString -AsPlainText "pass@word1" -Force) -Enabled $true -PasswordNeverExpires $false -Path 'CN=Users,DC=Domain,DC=com'

New-SPUser -UserAlias "Domain\$username" -Web $webUrl -DisplayName "$username User" -Group $group

Set-SPUser -Identity "Domain\$username" -Web $webUrl  -SyncFromAD:$true
$i=$i+1
}

Thursday, March 31, 2011

Sharepoint 2010 Creating Colleagues (bidirectional) by code

This is a sample how impersonating the System Account a  two way colleagues relationship can be established by code:

Thanks to the replies of Tony for  error-when-trying-to-add-a-colleague-to-a-user-profile
Problem was that I actually got an error if I run his code with elevetad privilege, so slightly modified his solution.



using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace SharePointProject1.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void AddUser_Click(object sender, EventArgs e)
        {
                using (SPSite siteCol = new SPSite("MySiteUrl"))
                {
//Open the Site with the SystemAccount
                    using (SPSite siteAdmin = new SPSite(siteCol.ID,siteCol.SystemAccount.UserToken))
                    {
                        try
                        {
//This is really needed, else you get an exception
                           siteAdmin.AllowUnsafeUpdates = true;
                            using (SPWeb spwebAdmin = siteAdmin.OpenWeb())
                            {
                               //I didn't test if this 3 line are really needed
                                SPUser inviter = spwebAdmin.EnsureUser(@"Domain\User1");
                                SPUser invited = spwebAdmin.EnsureUser(@"Domain\User2");
                                spwebAdmin.Update();
                                SPServiceContext ctx = SPServiceContext.GetContext(siteAdmin);

                                //Get the user'sprofilemanager from the current context and ignore privacy
                                UserProfileManager upcm = new UserProfileManager(ctx, true);
                                //Gettheuserprofile
                                UserProfile userInvitee = upcm.GetUserProfile(@"Domain \User1");
                                UserProfile userInviter = upcm.GetUserProfile(@"Domain \User2");
                                //updateinviter
                                if (!userInviter.Colleagues.IsColleague(userInvitee.ID))
                                {

                                    Colleague newColleague = userInviter.Colleagues.Create(userInvitee,ColleagueGroupType.General,"General", false,
Privacy.Public);
                                    newColleague.Commit();
                                    userInviter.Commit();
                                }
                                //updateinvitee
                                if (!userInvitee.Colleagues.IsColleague(userInviter.ID))
                                {
                                    Colleague newColleague = userInvitee.Colleagues.Create(userInviter,ColleagueGroupType.General,"General", false,Privacy.Public);
                                    newColleague.Commit();
                                    userInvitee.Commit();
                                }

                            }
                        }
                        finally
                        {
                            siteAdmin.AllowUnsafeUpdates = false;
                        }
                    }
                }
        }

    }
}


.Hope it works for you guys too