Friday, September 9, 2011

Machine Caching in SharePoint 2010

Some caching techniques in SharePoint 2010:-

1. Object Caching (Configurable)
2. BLOB Cache (Configurable) :  Open web.config in SharePoint Root Hive:
<BlobCache location="D:\BLOB\" path="\.(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|
wmv)$" maxSize="10" enabled="true" />

3. Caching in code (Programmable)

Important Links about Caching in SharePoint

Web Part Caching – A simple approach:-

Open Visual Studio2010 and select a WebPart form SharePoint 2010 Template:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace VisualWebPartProject1.VisualWebPart1
    public class VisualWebPart1 : WebPart
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartProject1/VisualWebPart1/VisualWebPart1UserControl.ascx";
        protected override void CreateChildControls()
            Control control = Page.LoadControl(_ascxPath);

            List<SPList> lists = new List<SPList>();
            string status = "";

            if (HttpRuntime.Cache["SimpleSampleCache"] == null)
                status = "The following items are <strong>NOT</strong> fetched from the cache<br/><br/>";

                SPWeb web = SPContext.Current.Web;
                foreach (SPList list in web.Lists)

                System.Web.Caching.CacheItemPriority.Default, null);
                status = "The following items <strong>ARE</strong> fetched from the cache!<br/><br/>";
                lists = (List<SPList>)HttpRuntime.Cache["SimpleSampleCache"];
            Controls.Add(new LiteralControl(status));

            foreach (SPList l in lists)
                Controls.Add(new LiteralControl(l.Title + " - " + l.ItemCount + " items<br/>"));   

Press F5 and add WebPart to an WebPart Page and Show the Result as follows:-

Thank You.

Developer Dashboard

Activating the Developer Dashboard

•    PowerShell
•    STSADM.exe
•    SharePoint Object Model (API's)

Activate the Developer Dashboard using PowerShell:-
$devdash = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$devdash.DisplayLevel = 'OnDemand';
$devdash.TraceEnabled = $true;

Activate the Developer Dashboard using STSADM.EXE:-
STSADM.EXE -o setproperty -pn developer-dashboard -pv ondemand

Activate the Developer Dashboard using the SharePoint Object Model:-
using Microsoft.SharePoint.Administration;
SPWebService svc = SPContext.Current.Site.WebApplication.WebService;
svc.DeveloperDashboardSettings.DisplayLevel =

•    Off (Disables the Developer Dashboard)
•    On (Enables the Developer Dashboard)
•    OnDemand (Enables the Developer Dashboard upon request by clicking the icon in the upper right corner)

SPMonitoredScope to track performance in your applications:-
 using (new SPMonitoredScope("Monitoring"))
    Controls.Add(new Literal { Text = "When the awesomeness is flying... " });
    using (new SPMonitoredScope("Sub-Monitoring"))
        Controls.Add(new Literal { Text = "Hello this is --Sub-Monitoring! " });

        using (new SPMonitoredScope("Sub-Sub-Monitoring"))
            Controls.Add(new Literal { Text = "<br/>Hello this is Sub-Sub-Monitoring!" });

        using (new SPMonitoredScope("Sub-Sub-Monitoring_1"))
            Controls.Add(new Literal { Text = "Hello this is Sub-Sub-Monitoring_1" });

Now go and test Doveloper Dashboard to find the Result with about scope names
1. Sub-Monitoring
2. Sub-Sub-Monitoring
3. Sub-Sub-Monitoring_1

Friday, September 2, 2011

SharePoint 2010 Backup and Recovery

Initial Backup Configuration
•    Farm, Service Applications, Content Databases: Local Administrator Group Member
•    Site collections, sites, lists, document libraries: Farm Administrator Group Member

Backing Up the Farm
following services must be running at the time you are issuing the backup command from CA:
•    Timer Service
•    SharePoint Foundation Administration Service

    In order to be able to back up the content databases, you must have the db_backupoperator role assigned to the user you are trying to perform the backup with.
Backing Up Content Databases
Backup-SPFarm -Directory "path" -BackupMethod "Full|Differential" -Item

•    Directory: Set the backup folder
•    BackupMethod: Specify whether to run a full or differential backup
•    Item: Specify the farm, web application or (shared) service application you want to backup

    At the end of the backup/restore operation you will find either spbackup.log or sprestore.log.
Backing Up Site Collection, Lists and Document Libraries
    The preferred file extension is .bak.
Backup-SPSite -Identity "Site Collection Name" -Path "path"  [-UseSqlSnapshot] [-NoSiteLock]

we can back up single sites, lists or document libraries:
Export-SPWeb -Identity "Site/List/Library name" -Path "path" [-IncludeUserSecurity] [-GradualDelete] [-IncludeVersions]

Backing Up Log Files
Merge-SPLogFile -Path"path" -Overwrite

Initial Restore Configuration
1.    Start the SharePoint Foundation Administration Service on all farm servers
2.    Do not restart services using the Product Configuration Wizard (which causes custom configuration of the service apps to be lost).

Restoring an Entire Farm
1.    Restore-SPFarm –Directory "path" –RestoreMethod Overwrite [-BackupId "guid"]
2.    Get-SPBackupHistory -Directory "path"

Start and Stop Service using Powershell
1.    Get-SPServiceInstance | Stop-SPServiceInstance
2.    Get-SPServiceInstance | Start-SPServiceInstance

Restore Using the SQL Server Tools
•    You cannot restore the SharePoint 2010 configuration data.
•    You cannot restore SharePoint 2010 search.

Backing Up and Restoring Configuration Settings on Another Farm
What you need to bear in mind for the mentioned scenario is that you must copy and restore the configuration settings for the following elements:
•    The farm
•    Web applications
•    Service applications
1.    Get-SPWebApplication | %{$_.Name;$_.Url;%{$_.ContentDatabases|%{$_.Name}; Write-Host “” }}
2.    Get-SPContentDatabase | Dismount-ContentDatabases3.   
4.    Backup-SPFarm –Directory "path" -BackupMethod "Full | Differential"
5.    Mount-SPContentDatabase –Name "WSS_Content" -WebApplication "URL"
6.    Restore-SPFarm –Directory "path" -RestoreMethod Overwrite -ConfigurationOnly
7.    Restore-SPFarm –Directory <backup folder> -RestoreMethod Overwrite –ConfigurationOnly –Item "web app | service app"
8.    Update-SPSecureStoreApplicationServerKey –Passphrase <passphrase>
9.    Mount-SPContentDatabase –Name <db name> -WebApplication <web app URL>

Restoring Site Collections
1.    Restore-SPSite –Identity <site_collection_url> -Path <network_shared_path>\newteamsite.bak -Force

Import list and libraries
1. Import-SPWeb –Identity <site_collection_url> -Path <network_shared_path>\listname.cmp

Create a network shared folder
1. Start, Command Prompt
2. cd /
3. mkdir SPBackupFolder
4. Cacls SPBackupFolder /G <DomainName>\Administrator:F
5. Net Share SPBackupFolder=C:\SPBackupFolder /GRANT:<DomainFolder>\Adminstrator,FULL
Get-Help Restore-SPSite -detailed
Get-Help Import-SPWeb -detailed
Get-Help Get-SPBackupHistory -detailed
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup -ShowBackup
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup -ShowRestore

Thursday, September 1, 2011

People Search in Silverlight WebPart

Step1: File->New Project->Silverlight->Silverlight Application->SP_SilverligetApplication1
(Name)->click OK

Pleas make sure check the box "Host the silverlight application in a new web site"->Click OK

Step2: Right clink on SP_SilverlightApplication1->Add service referece->Address as type "http://servername/_vti_bin/People.asmx"->click on "Go" and select an service "People" and give namespace as "PeopleWS"

Step3: Open SP_SilverlightApplication1->MainPage.xml and type following code.

<UserControl x:Class="SP_SilverlightApplication1.MainPage"
    d:DesignHeight="240" d:DesignWidth="280">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border BorderThickness="4" BorderBrush="Black">
                    <RowDefinition Height="30" />
                    <RowDefinition Height="145" />
                    <RowDefinition Height="25" />
                    <RowDefinition Height="*" />
                    <ColumnDefinition Width="*" />
                <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="3" VerticalAlignment="Top">
                    <TextBlock HorizontalAlignment="Left" Name="textBlock1" Text="Search:" VerticalAlignment="Center" />
                    <TextBox x:Name="SearchTxt" Width="200" KeyUp="SearchTxt_KeyUp" />
                    <Button x:Name="SearchBtn" Click="SearchBtn_Click">
                        <Image Source="/SilverSite;component/Images/search32x32.png" Width="16" Height="16" />                    </Button>
                <StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Left" Margin="3">
                    <ListBox x:Name="ResultsLst" Width="265" Height="135" />
                <StackPanel Grid.Row="2" Orientation="Horizontal" Margin="3">
                    <Button x:Name="AddNameBtn" Content="Add ->" Click="AddNameBtn_Click" />
                    <TextBlock x:Name="UserNameTxt" Width="143" Padding="5" VerticalAlignment="Center" />
                <StackPanel Grid.Row="3" Orientation="Horizontal" Margin="3" HorizontalAlignment="Right">
                    <Button x:Name="OKBtn" Content="OK" Width="75" Click="OKBtn_Click" Height="20" Padding="3" />
                    <Button x:Name="CancelBtn" Content="Cancel" Width="75" Height="20" Padding="3" Click="CancelBtn_Click" />

Step4: open SP_SilverlightApplication1->MainPage.xaml.cs and type the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Diagnostics;

namespace SP_SilverlightApplication1
    public partial class MainPage : UserControl
        public string HostName { get; set; }
        public string SelectedAccountName { get; set; }
        public MainPage HostControl { get; set; }
        public enum AddressType
        public AddressType PickerAddressType { get; set; }
        private class PickerEntry
            public string DisplayName { get; set; }
            public string AccountName { get; set; }
            public PickerEntry() { }
            public PickerEntry(string displayName, string accountName)
                this.DisplayName = displayName;
                this.AccountName = accountName;
            public override string ToString()
                return this.DisplayName;
        public MainPage()
            UserNameTxt.TextDecorations = TextDecorations.Underline;
        private void OKBtn_Click(object sender, RoutedEventArgs e)
            //make sure a value was selected
            if (string.IsNullOrEmpty(UserNameTxt.Text))
                MessageBox.Show("You must select a user before clicking OK; if you wish to " +
                    "cancel this operation then click the Cancel button.", "Select User",
            //plug in the values
            if (PickerAddressType == AddressType.Primary)
                HostControl.PrimaryAdmin = SelectedAccountName;
                HostControl.PrimaryDisplayName = UserNameTxt.Text;
                HostControl.SecondaryAdmin = SelectedAccountName;
                HostControl.SecondaryDisplayName = UserNameTxt.Text;

        private void CloseDialog()
            //clear out selections for next time
            SearchTxt.Text = string.Empty;
            UserNameTxt.Text = string.Empty;

            //cast the parent to popup and close; don't set visibility or it
            //causes more code the next time you want to open it up
            Popup p = (Popup)this.Parent;
            p.IsOpen = false;          
        private void SearchBtn_Click(object sender, RoutedEventArgs e)
            //make sure a search value was entered
            if (string.IsNullOrEmpty(SearchTxt.Text))
                MessageBox.Show("You must enter a search term.", "Missing Search Term",
                //change the cursor to hourglass
                this.Cursor = Cursors.Wait;
                //the main control has code like this to get the HostName
                //get info on the current host
                //string curUrl = HtmlPage.Document.DocumentUri.AbsoluteUri.ToString();

                //get the host name; note that this assumes the user has rights to the root site
                //site collection; that may not be true in your scenario
                //Uri curUri = new Uri(curUrl);
                //HostName = curUri.Scheme + "://" + curUri.Host + ":" + curUri.Port.ToString();
                //set the search request
                PeopleWS.PeopleSoapClient ps = new PeopleWS.PeopleSoapClient();
                //use the host name property to configure the request against the site in
                //which the control is hosted
                ps.Endpoint.Address =
                    new System.ServiceModel.EndpointAddress(HostName + "/_vti_bin/People.asmx");

                //create the handler for when the call completes
                ps.SearchPrincipalsCompleted +=
                    new EventHandler<PeopleWS.SearchPrincipalsCompletedEventArgs>(ps_SearchPrincipalsCompleted);               
                //execute the search
                ps.SearchPrincipalsAsync(SearchTxt.Text, 50, PeopleWS.SPPrincipalType.User);
            catch (Exception ex)
                //ERROR LOGGING HERE

                MessageBox.Show("There was a problem executing the search; please try again " +
                    "later or contact your Help Desk if the problem continues.", "Search Error",
                //reset cursor
                this.Cursor = Cursors.Arrow;
        void ps_SearchPrincipalsCompleted(object sender, PeopleWS.SearchPrincipalsCompletedEventArgs e)
                if (e.Error != null)
                    MessageBox.Show("An error was returned: " + e.Error.Message, "Search Error",
                        results = e.Result;
                    //clear the search results listbox
                    foreach (PeopleWS.PrincipalInfo pi in results)
                        ResultsLst.Items.Add(new PickerEntry(pi.DisplayName, pi.AccountName));
            catch (Exception ex)
                MessageBox.Show("There was an error processing the search results: " + ex.Message,
                    "Search Error", MessageBoxButton.OK);
                //reset cursor
                this.Cursor = Cursors.Arrow;
        private void AddNameBtn_Click(object sender, RoutedEventArgs e)
            //see if an item is selected
            if ((ResultsLst.Items.Count == 0) || (ResultsLst.SelectedItem == null))
                MessageBox.Show("You must run a search and select a name first.",
                    "Add User Error", MessageBoxButton.OK);

        private void AddPickerEntry()
            //cast the selected name as a PickerEntry
            PickerEntry pe = (PickerEntry)ResultsLst.SelectedItem;
            UserNameTxt.Text = pe.DisplayName;
            SelectedAccountName = pe.AccountName;

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        private void SearchTxt_KeyUp(object sender, KeyEventArgs e)
            if (e.Key == Key.Enter)
                SearchBtn_Click(sender, new RoutedEventArgs());

        public string PrimaryAdmin { get; set; }
        public string PrimaryDisplayName { get; set; }
        public string SecondaryAdmin { get; set; }
        public string SecondaryDisplayName { get; set; }

Step5: Right Click SP_SilverlightApplication->Properties->Build->Output->Output path->"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin\silverlight\"

save all and build the solution

Step6: go to sharepoint application and edit any page and add a silverlight webpart from Categories->Media and Content->Silverlight web part->Add->Url->"_LAYOUTS/ClientBin/silverlight/SP_SilverlightApplication1.xap"->click OK.

Setp7: Test the Application

Featured Post

Azure Scripts

 Azure Scripts: Azure > Storage account > File shares > SMB File share To connect to this Azure file share from Windows, run the Po...

Popular posts