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
http://msdn.microsoft.com/en-us/library/aa661294.aspx
http://msdn.microsoft.com/en-us/library/aa661294.aspx
http://msdn.microsoft.com/en-us/library/ms550239.aspx
http://msdn.microsoft.com/en-us/library/aa622758.aspx
http://technet.microsoft.com/en-us/library/cc770229.aspx
http://technet.microsoft.com/en-us/library/cc770229.aspx#BLOB
http://www.zimmergren.net/archive/2008/10/07/web-part-caching-%E2%80%93-a-simple-approach.aspx
http://msdn.microsoft.com/en-us/library/bb687949%28office.12%29.aspx#UsingSPData
http://technet.microsoft.com/en-us/library/ee424404.aspx#Section1c


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
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {       
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartProject1/VisualWebPart1/VisualWebPart1UserControl.ascx";
       
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);

            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)
                    lists.Add(list);

                HttpRuntime.Cache.Add("SimpleSampleCache",
                lists,
                null,
                DateTime.MaxValue,
                TimeSpan.FromMinutes(10),
                System.Web.Caching.CacheItemPriority.Default, null);
            }
            else
            {
                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;
$devdash.Update()

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 =
    SPDeveloperDashboardLevel.Off;
svc.DeveloperDashboardSettings.Update();

•    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
0.Monitoring
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"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="240" d:DesignWidth="280">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border BorderThickness="4" BorderBrush="Black">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="30" />
                    <RowDefinition Height="145" />
                    <RowDefinition Height="25" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <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>
                <StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Left" Margin="3">
                    <ListBox x:Name="ResultsLst" Width="265" Height="135" />
                </StackPanel>
                <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>
                <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" />
                </StackPanel>
            </Grid>
        </Border>
    </Grid>
</UserControl>

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
        {
            Primary,
            Secondary
        }
        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()
        {
            InitializeComponent();
            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",
                    MessageBoxButton.OK);
                CancelBtn.Focus();
                return;
            }
            //plug in the values
            if (PickerAddressType == AddressType.Primary)
            {
                HostControl.PrimaryAdmin = SelectedAccountName;
                HostControl.PrimaryDisplayName = UserNameTxt.Text;
            }
            else
            {
                HostControl.SecondaryAdmin = SelectedAccountName;
                HostControl.SecondaryDisplayName = UserNameTxt.Text;
            }

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

            //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",
                    MessageBoxButton.OK);
                SearchTxt.Focus();
                return;
            }
            try
            {
                //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
                Debug.WriteLine(ex.Message);

                MessageBox.Show("There was a problem executing the search; please try again " +
                    "later or contact your Help Desk if the problem continues.", "Search Error",
                    MessageBoxButton.OK);
                //reset cursor
                this.Cursor = Cursors.Arrow;
            }
        }
        void ps_SearchPrincipalsCompleted(object sender, PeopleWS.SearchPrincipalsCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    MessageBox.Show("An error was returned: " + e.Error.Message, "Search Error",
                        MessageBoxButton.OK);
                else
                {
                    System.Collections.ObjectModel.ObservableCollection<PeopleWS.PrincipalInfo>
                        results = e.Result;
                    //clear the search results listbox
                    ResultsLst.Items.Clear();
                    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);
            }
            finally
            {
                //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);
                return;
            }

            AddPickerEntry();
        }
        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)
        {
            CloseDialog();
        }
        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