Wednesday, 31 October 2012

PowerShell Commands To List SharePoint Features

The more I work with SharePoint 2010 the more I am starting to love PowerShell. My scripting skills are pretty basic (!) but here are a couple of useful little snippets to get back some information from a site that previously I would have spent a while going through the UI or SharePoint Root – mainly as a reminder for myself!

List all installed features on the farm
It’s really straight forward using the Get-SPFeature command to return all installed features. To provide a little more readability to the output it can be sorted as follows:
By feature display name alphabetically,

1
Get-SPFeature | Sort -Property DisplayName

By feature ID,

1
Get-SPFeature | Sort -Property Id

By feature display name alphabetically and grouped by scope,

1
Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id

And to write this to a file to allow for viewing in Notepad, Excel etc,

1
Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id > c:\AllInstalledFeatures.txt

List all activated site scoped features
Especially in the case of hidden features it’s sometimes necessary to track down if a feature is active on a site collection. Here’s a quick way of seeing which features are activated for an SPSite:

1
Get-SPFeature -Site http://sitecollectionurl | Sort DisplayName | FT DisplayName,Id

List all activated web scoped features
And only slightly modified from the Get-Help Get-SPFeature -examples text, here is a command to list all web activated featres for a site collection:

1
Get-SPSite http://sitecollectionurl | Get-SPWeb -Limit ALL | %{ Get-SPFeature -Web $_ } | SortDisplayName -Unique | FT DisplayName,Id

Tuesday, 30 October 2012

How to Deploy ItemStyle.xsl at SharePoint site Creation

It is a known issue with SharePoint that ItemStyle.xsl doesn’t get provisioned. Styling for the Content Query Web Parts (CQWP) are done on ItemStyle.xsl file. In most of the SharePoint projects we add ItemStyle.xsl in to Branding feature, but even after the activation of the feature this file won’t get provisioned.

Most of the sites suggest to upload this file manually after creating the site. But ItemStyle.xsl can be uploaded in to the site at feature activation. Few lined of code will do this. Steps are given below.

  1. Add Event Receiver to the Branding feature (Or what ever the feature that Item.xsl File is included)

  2. Override ”FeatureActivated” Event and add below code.

 

 

1 public override void FeatureActivated(SPFeatureReceiverProperties properties)
2 {
3
4 SPSecurity.RunWithElevatedPrivileges(delegate()
5 {
6 bool IsXSLUpdated = false;
7 String fileToUpload = @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\FirstPrincipal\XslStyleSheet\ItemStyle.xsl";
8 string libraryName = "Style Library";
9 string xslFolderName = "XSL Style Sheets";
10
11 if (IsXSLUpdated == false)
12 {
13 using (SPSite spSite = (SPSite)properties.Feature.Parent)
14 {
15
16 SPFolder xslStylefolder = null;
17 SPWeb web = spSite.OpenWeb();
18 if (System.IO.File.Exists(fileToUpload))
19 {
20 SPFolderCollection stylefolders = web.Folders[libraryName].SubFolders;
21
22 foreach (SPFolder folder in stylefolders)
23 {
24 if (folder.Name == xslFolderName)
25 {
26 //upload replacing the existing
27 xslStylefolder = folder;
28 String fileName = System.IO.Path.GetFileName(fileToUpload);
29 System.IO.FileStream fileStream = System.IO.File.OpenRead(fileToUpload);
30
31 SPFileCollection xslFileCollection = xslStylefolder.Files;
32
33 foreach (SPFile file in xslFileCollection)
34 {
35 if (file.Name == fileName)
36 {
37
38 file.CheckOut();
39 break;
40 }
41 }
42 SPFile spFile = xslStylefolder.Files.Add(fileName, fileStream, true);
43
44 spFile.CheckIn("Checking in item style xsl sheet", SPCheckinType.MajorCheckIn);
45 spFile.Publish("Publishing the item style xsl sheet");
46 xslStylefolder.Update();
47 IsXSLUpdated = true;
48 break;
49 }
50 }
51
52 }
53
54
55 }
56 }
57 });
58 }

Friday, 26 October 2012

Import Data to List using PowerShell by csv

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
$csv = Import-Csv 'E:\Sharepoint\SharepointStuff\PowershellScripts\test\w\Import.csv'

$web = Get-SPWeb -identity "http://globas"

$list = $web.Lists["News"]

foreach ($row in $csv) {
$item = $list.Items.Add();
$item["Title"] =$row.Title
$item["Body"] =$row.Body
$item["Expires"] =$row.Expires
$item.Update()
}


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

 

please use CSV column as Title,Body

Remove Solution from the Central admin using Poweshell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 

Uninstall-SPSolution –Identity bamboo.logging.v1.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity bamboo.logging.v1.wsp

 

Uninstall-SPSolution –Identity basicwebpartssingle.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity basicwebpartssingle.wsp

 

Uninstall-SPSolution –Identity contentsliderwebpart.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity contentsliderwebpart.wsp

 

Uninstall-SPSolution –Identity mydocstreeview.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity mydocstreeview.wsp

 

Uninstall-SPSolution –Identity sampletodeployapage.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity sampletodeployapage.wsp

 

 

 


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Retrieve All Wsp from the Central Admin

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue
## setup our output directory
$dirName = "c:\ExportedSolutions"
Write-Host Exporting solutions to $dirName
foreach ($solution in Get-SPSolution)
{
    $id = $Solution.SolutionID
    $title = $Solution.Name
    $filename = $Solution.SolutionFile.Name
    Write-Host "Exporting ‘$title’ to …\$filename" -nonewline
    try {
        $solution.SolutionFile.SaveAs("$dirName\$filename")
        Write-Host " – done" -foreground green
    }
    catch
    {
        Write-Host " – error : $_" -foreground red
    }
}

Retrieve Single Wsp from the Central Admin

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

$dirName = "c:\ExportedSolutions\"
if (!(Test-Path -path $dirName))
{
New-Item $dirName -type directory
}
Write-Host Exporting solution to $dirName
$farm = Get-SPFarm
$file = $farm.Solutions.Item("treeviewdocumentlibrary.wsp").SolutionFile
$file.SaveAs($dirName + "treeviewdocumentlibrary.wsp")

Automated wsp installer using Powershell

######################################
######## Set Variables ###############
######################################
$InstallDIR = "C:\install"
 
######################################
#### CODE, No Changes Necessary ######
######################################
Write-Host "Working, Please wait...."
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
 
$Dir = get-childitem $InstallDIR -Recurse
$WSPList = $Dir | where {$_.Name -like "*.wsp*"}
Foreach ($wsp in $WSPList )
{
    $WSPFullFileName = $wsp.FullName
    $WSPFileName = $wsp.Name
    clear
    Write-Host -ForegroundColor White -BackgroundColor Blue "Working on $WSPFileName"
 
    try
    {
        Write-Host -ForegroundColor Green "Checking Status of Solution"
        $output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
    }
    Catch
    {
        $DoesSolutionExists = $_
    }
    If (($DoesSolutionExists -like "*Cannot find an SPSolution*") -and ($output.Name -notlike  "*$WSPFileName*"))
    {
        Try
        {
            Write-Host -ForegroundColor Green "Adding solution to farm"
            Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
 
            Write-Host -ForegroundColor Green "Checking Status of Solution"
            $output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
            $gobal = $null
            if ($output.Deployed -eq $false)
            {
                try
                {
                    Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
                Catch
                {
                    $gobal = $_
                }
                If ($gobal -like "*This solution contains*")
                {
                    Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
            }
 
            Sleep 1
            $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
            If ($dpjobs -eq $null)
            {
                Write-Host -ForegroundColor Green "No solution deployment jobs found"
            }
            Else
            {
                If ($dpjobs -is [Array])
                {
                    Foreach ($job in $dpjobs)
                    {
                        $jobName = $job.Name
                        While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                        {
                            Write-Host -ForegroundColor Yellow -NoNewLine "."
                            Start-Sleep -Seconds 5
                        }
                        Write-Host
                    }
                }
                Else
                {
                    $jobName = $dpjobs.Name
                    While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                    {
                        Write-Host -ForegroundColor Yellow -NoNewLine "."
                        Start-Sleep -Seconds 5
                    }
                    Write-Host
                }
            }
        }
        Catch
        {
            Write-Error $_
            Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
            Read-Host
        }
    }
    Else
    {
        $skip = $null
        $tryagain = $null
        Try
        {
            if ($output.Deployed -eq $true)
            {
            Write-Host -ForegroundColor Green "Retracting Solution"
            Uninstall-SPSolution -AllWebApplications -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
            }
        }
        Catch
        {
            $tryagain = $_
        }
        Try
        {
            if ($tryagain -ne $null)
            {
                Uninstall-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
            }
        }
        Catch
        {
            Write-Host -ForegroundColor Red "Could not Retract Solution"
        }
 
        Sleep 1
        $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
        If ($dpjobs -eq $null)
        {
            Write-Host -ForegroundColor Green "No solution deployment jobs found"
        }
        Else
        {
            If ($dpjobs -is [Array])
            {
                Foreach ($job in $dpjobs)
                {
                    $jobName = $job.Name
                    While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                    {
                        Write-Host -ForegroundColor Yellow -NoNewLine "."
                        Start-Sleep -Seconds 5
                    }
                    Write-Host
                }
            }
            Else
            {
                $jobName = $dpjobs.Name
                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                {
                    Write-Host -ForegroundColor Yellow -NoNewLine "."
                    Start-Sleep -Seconds 5
                }
                Write-Host
            }
        }       
 
        Try
        {
            Write-Host -ForegroundColor Green "Removing Solution from farm"
            Remove-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
        }
        Catch
        {
            $skip = $_
            Write-Host -ForegroundColor Red "Could not Remove Solution"
            Read-Host
        }
        if ($skip -eq $null)
        {
            Try
            {
                Write-Host -ForegroundColor Green "Adding solution to farm"
                Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
                $gobal = $null
                try
                {
                    Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
                Catch
                {
                    $gobal = $_
                }
                If ($gobal -like "*This solution contains*")
                {
                    Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
            }
            Catch
            {
                Write-Error $_
                Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
                Read-Host
            }
 
            Sleep 1
            $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
            If ($dpjobs -eq $null)
            {
                Write-Host -ForegroundColor Green "No solution deployment jobs found"
            }
            Else
            {
                If ($dpjobs -is [Array])
                {
                    Foreach ($job in $dpjobs)
                    {
                        $jobName = $job.Name
                        While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                        {
                            Write-Host -ForegroundColor Yellow -NoNewLine "."
                            Start-Sleep -Seconds 5
                        }
                        Write-Host
                    }
                }
                Else
                {
                    $jobName = $dpjobs.Name
                    While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                    {
                        Write-Host -ForegroundColor Yellow -NoNewLine "."
                        Start-Sleep -Seconds 5
                    }
                    Write-Host
                }
            }
    }
    Else
    {
        Write-Host -ForegroundColor Red "Cannot Install $WSPFileName, Please try manually"
        Read-Host
    }
}
}

How to get absolute URLs in SharePoint

Use the SPSite.MakeFullUrl() function:

public string MakeFullUrl(
string strUrl
)
Simply pass in the string of the relative URL and it returns you the absolute URL.
For example:
string imageUrl = site.MakeFullUrl("/_layouts/images/siteIcon.png"); 

Get the current URL in a SharePoint page or web part

 

Three ways:

#1 (preferred if there is also a query string in the URL)

   string url = Request.Url.AbsoluteUri;

#2

   string url = "http://" + Request.ServerVariables["SERVER_NAME"] + Request.ServerVariables["URL"];

#3 (preferred for web parts - see below)

   string url = SPContext = " + SPContext.Current.Web.Url + "/" + SPContext.Current.File.Url;

Notes:

#1 will return the query string, while #2 and #3 will not.

#1 and #2 will give you odd results when used in a Layouts application page:

URL of page:
  http://intranet/sites/training/_layouts/SharePointProject3/ApplicationPage1.aspx

Returned from both #1 and #2:
  http://intranet/_layouts/SharePointProject3/ApplicationPage1.aspx

#2 when used in a web part will need System.Web.HttpContext.Current.Request:

"http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + System.Web.HttpContext.Current.Request.ServerVariables["URL"];

BreadCrumb

<asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb" runat="server">
<SharePoint:ListSiteMapPath
runat="server"
SiteMapProviders="SPSiteMapProvider,SPContentMapProvider"
RenderCurrentNodeAsLink="false"
PathSeparator=""
CssClass="s4-breadcrumb"
NodeStyle-CssClass="s4-breadcrumbNode"
CurrentNodeStyle-CssClass="s4-breadcrumbCurrentNode"
RootNodeStyle-CssClass="s4-breadcrumbRootNode"
NodeImageOffsetX=0
NodeImageOffsetY=353
NodeImageWidth=16
NodeImageHeight=16
NodeImageUrl="/_layouts/images/fgimg.png"
RTLNodeImageOffsetX=0
RTLNodeImageOffsetY=376
RTLNodeImageWidth=16
RTLNodeImageHeight=16
RTLNodeImageUrl="/_layouts/images/fgimg.png"
HideInteriorRootNodes="true"
SkipLinkText="" />
</asp:ContentPlaceHolder>

Thursday, 25 October 2012

Split

Split separates strings. Strings often have delimiter characters in their data. Delimiters include "\r\n" newline sequences and the comma and tab characters. The C# language introduces the Split method. This method handles splitting upon string and character delimiters.

Key point:Use Split to separate parts from a string. If your input string is "A B C" you split on the space to get an array of: "A" "B" "C".

Example

To begin, let's examine the simplest Split method overload. You already know the general way to do this, but it is good to see the basic syntax before we move on. This program splits on a single character.

Program that splits on spaces [C#]

using System;

class Program
{
static void Main()
{
string s = "there is a cat";
//
// Split string on spaces.
// ... This will separate all the words.
//

string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}

Output

there
is
a
cat

The input string, which contains four words, is split on spaces. The result value from Split is a string array. The foreach-loop then loops over this array and displays each word.

Multiple characters

Split strings

Next we use the Regex.Split method to separate based on multiple characters. Please note that a new char array is created in the following usages. There is an overloaded method with that signature if you need StringSplitOptions. This is used to remove empty strings.

Program that splits on lines with Regex [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
static void Main()
{
string value = "cat\r\ndog\r\nanimal\r\nperson";
//
// Split the string on line breaks.
// ... The return value from Split is a string[] array.
//

string[] lines = Regex.Split(value, "\r\n");

foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}

Output

cat
dog
animal
person

RemoveEmptyEntries


The Regex type methods are used to Split strings effectively. But string Split is often faster. The next example specifies an array as the first argument to string Split. It uses the RemoveEmptyEntries enumerated constant.

Program that splits on multiple characters [C#]

using System;

class Program
{
static void Main()
{
//
// This string is also separated by Windows line breaks.
//

string value = "shirt\r\ndress\r\npants\r\njacket";

//
// Use a new char[] array of two characters (\r and \n) to break
// lines from into separate strings. Use "RemoveEmptyEntries"
// to make sure no empty strings get put in the string[] array.
//

char[] delimiters = new char[] { '\r', '\n' };
string[] parts = value.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}

//
// Same as the previous example, but uses a new string of 2 characters.
//

parts = value.Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
}
}

Output
(Repeated two times)

shirt
dress
pants
jacket

One useful overload of Split receives char[] arrays. The string Split method receives a character array as the first parameter. Each char in the array designates a new block.

Char ArrayArray type

Using string arrays. Another overload of Split receives string[] arrays. This means a string array can also be passed to the Split method. The new string[] array is created inline with the Split call.

String Array

Explanation of StringSplitOptions. The RemoveEmptyEntries enum is specified. When two delimiters are adjacent, we end up with an empty result. We can use this as the second parameter to avoid empty results. The following screenshot shows the Visual Studio debugger.

Split string debug screenshot

Separate words


You can separate words with Split. Usually, the best way to separate words is to use a Regex that specifies non-word chars. This example separates words in a string based on non-word characters. It eliminates punctuation and whitespace from the return array.

Program that separates on non-word pattern [C#]

using System;
using System.Text.RegularExpressions;

class Program
{
static void Main()
{
string[] w = SplitWords("That is a cute cat, man");
foreach (string s in w)
{
Console.WriteLine(s);
}
Console.ReadLine();
}

/// <summary>
/// Take all the words in the input string and separate them.
/// </summary>

static string[] SplitWords(string s)
{
//
// Split on all non-word characters.
// ... Returns an array of all the words.
//

return Regex.Split(s, @"\W+");
// @ special verbatim string syntax
// \W+ one or more non-word characters together

}
}

Output

That
is
a
cute
cat
man

In the example, we showed how to separate parts of your input string based on any character set or range with Regex. Overall, this provides more power than the string Split methods.

Regex.Split Examples

Text files

Note

Here you have a text file containing comma-delimited lines of values—this is called a CSV file. We use the File.ReadAllLines method here, but you may want StreamReader instead. This code reads in both of those lines. It parses them.

Then:It displays the values of each line after the line number. The output shows how the file was parsed into the strings.

Contents of input file: TextFile1.txt

Dog,Cat,Mouse,Fish,Cow,Horse,Hyena
Programmer,Wizard,CEO,Rancher,Clerk,Farmer

Program that splits lines in file [C#]

using System;
using System.IO;

class Program
{
static void Main()
{
int i = 0;
foreach (string line in File.ReadAllLines("TextFile1.txt"))
{
string[] parts = line.Split(',');
foreach (string part in parts)
{
Console.WriteLine("{0}:{1}",
i,
part);
}
i++; // For demo only
}
}
}

Output

0:Dog
0:Cat
0:Mouse
0:Fish
0:Cow
0:Horse
0:Hyena
1:Programmer
1:Wizard
1:CEO
1:Rancher
1:Clerk
1:Farmer

Directory paths

Path type

You can Split the segments in a Windows local directory into separate strings. Please note that directory paths are complex and this may not handle all cases correctly. It is also platform-specific. You could use System.IO.Path. DirectorySeparatorChar for more flexibility.

Path Examples

Program that splits Windows directories [C#]

using System;

class Program
{
static void Main()
{
// The directory from Windows
const string dir = @"C:\Users\Sam\Documents\Perls\Main";
// Split on directory separator
string[] parts = dir.Split('\\');
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}

Output

C:
Users
Sam
Documents
Perls
Main

Internal logic

Framework: NET

The logic internal to the .NET Framework for Split is implemented in managed code. The methods call into the overload with three parameters. The parameters are next checked for validity.

Next:It uses unsafe code to create the separator list, and then a for-loop combined with Substring to return the array.

ForSubstring

Benchmarks


I tested a long string and a short string, having 40 and 1200 chars. String splitting speed varies on the type of strings. The length of the blocks, number of delimiters, and total size of the string factor into performance. The Regex.Split option generally performed the worst.

And:I felt that the second or third methods would be the best, after observing performance problems with regular expressions in other situations.

Strings used in test [C#]

//
// Build long string.
//

_test = string.Empty;
for (int i = 0; i < 120; i++)
{
_test += "01234567\r\n";
}
//
// Build short string.
//

_test = string.Empty;
for (int i = 0; i < 10; i++)
{
_test += "ab\r\n";
}

Methods tested: 100000 iterations

static void Test1()
{
string[] arr = Regex.Split(_test, "\r\n", RegexOptions.Compiled);
}

static void Test2()
{
string[] arr = _test.Split(new char[] { '\r', '\n' },
StringSplitOptions.RemoveEmptyEntries);
}

static void Test3()
{
string[] arr = _test.Split(new string[] { "\r\n" },
StringSplitOptions.None);
}

Longer strings of 1200 chars. The benchmark for the methods on the long strings is more even. It may be that for long strings, such as entire files, the Regex method is equivalent or even faster. For short strings Regex is slowest. For long strings it is fast.

Benchmark of Split on long strings

[1] Regex.Split: 3470 ms
[2] char[] Split: 1255 ms [fastest]
[3] string[] Split: 1449 ms

Benchmark of Split on short strings

[1] Regex.Split: 434 ms
[2] char[] Split: 63 ms [fastest]
[3] string[] Split: 83 ms

Short strings of 40 chars. This shows the three methods compared to each other on short strings. Method 1 is the Regex method. It is by far the slowest on the short strings. This may be because of the compilation time. Smaller is better.

Performance optimization

Performance recommendation. For programs that use shorter strings, the methods that split based on arrays are faster and simpler. They will avoid Regex compilation. For somewhat longer strings or files that contain more lines, Regex is appropriate.

Escaped characters


You can use Replace on your string input to substitute special characters in for any escaped characters. This solves lots of problems on parsing computer-generated code or data.

Replace

Delimiter arrays


Let's focus on how you can specify delimiters to the Split method. My further research into Split shows that it is worthwhile to declare your char[] array you are splitting on as a local instance. This reduces memory pressure. It improves runtime performance.

Note:We see that storing the array of delimiters separately is good. My measurements show the above code is less than 10% faster when the array is stored outside the loop.

Slow version, before [C#]

//
// Split on multiple characters using new char[] inline.
//

string t = "string to split, ok";

for (int i = 0; i < 10000000; i++)
{
string[] s = t.Split(new char[] { ' ', ',' });
}

Fast version, after [C#]

//
// Split on multiple characters using new char[] already created.
//

string t = "string to split, ok";
char[] c = new char[]{ ' ', ',' }; // <-- Cache this

for (int i = 0; i < 10000000; i++)
{
string[] s = t.Split(c);
}

StringSplitOptions

Question and answer

What effect does the StringSplitOptions argument have? It affects the behavior of the Split method. The two values of StringSplitOptions—None and RemoveEmptyEntries—are actually just integers that tell Split how to work.

Program that uses StringSplitOptions [C#]

using System;

class Program
{
static void Main()
{
// Input string contain separators.
string value1 = "man,woman,child,,,bird";
char[] delimiter1 = new char[] { ',' }; // <-- Split on these

// ... Use StringSplitOptions.None.
string[] array1 = value1.Split(delimiter1,
StringSplitOptions.None);

foreach (string entry in array1)
{
Console.WriteLine(entry);
}

// ... Use StringSplitOptions.RemoveEmptyEntries.
string[] array2 = value1.Split(delimiter1,
StringSplitOptions.RemoveEmptyEntries);

Console.WriteLine();
foreach (string entry in array2)
{
Console.WriteLine(entry);
}
}
}

Output

man
woman
child


bird

man
woman
child
bird
String type

The input string in the example contains five commas, which are the delimiters. However, two fields between commas are 0 characters long (empty). In the first call to Split, these fields are put into the result array. In the second call, where we specify StringSplitOptions.RemoveEmptyEntries, the two empty fields are not in the result array.

Tip:You can use the StringSplitOptions.RemoveEmptyEntries enumerated constant as the second parameter in the Split method. By removing empty entries, you can simplify some logic.

However:Sometimes empty fields are useful for maintaining the order of your fields.

StringReader

Programming tip

We can instead use the StringReader type to separate a string into lines. StringReader can additionally lead to performance improvements over using Split. This is because no arrays are allocated.

StringReader

Summary

The C# programming language

We saw several examples and benchmarks of the Split method in the C# programming language. You can use Split to divide or separate your strings while keeping your code as simple as possible.

Tip:Using IndexOf and Substring together to parse your strings can sometimes be more effective.

IndexOf

Saturday, 20 October 2012

XSL Read More and Full Data Content Query

 

Edit in ItemStyle.xsl


  <xsl:template name="FullData" match="Row[@Style='FullData']" mode="itemstyle">
   <xsl:variable name="SafeLinkUrl">
                     <xsl:call-template name="OuterTemplate.GetSafeLink">
                           <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                           <xsl:with-param name="UseFileName" select="1"/>
                     </xsl:call-template>
              </xsl:variable>
 
   <xsl:variable name="DisplayTitle">
                     <xsl:call-template name="OuterTemplate.GetTitle">
                           <xsl:with-param name="Title" select="@Title"/>
                           <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                     </xsl:call-template>
              </xsl:variable>
                 <xsl:value-of select="@Body" disable-output-escaping="yes"/>
<div align="right" style="color:black;">                  
  <input type="button" onclick="test('dsf');" value="Close"></input>  </div>

 

<SCRIPT language="JavaScript"><![CDATA[
            function test(avalue) {
               var url = location.search;
               var getIndex = url.indexOf("Source=");
               var getUrl=url.substring(getIndex,url.length).replace("Source=","");
window.location = decodeURIComponent(getUrl);
              
            }
      ]]></SCRIPT> 

       </xsl:template>

 
 
 
  <xsl:template name="ReadMore" match="Row[@Style='ReadMore']" mode="itemstyle">
 
 
   <xsl:variable name="SafeLinkUrl">
                     <xsl:call-template name="OuterTemplate.GetSafeLink">
                           <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                           <xsl:with-param name="UseFileName" select="1"/>
                     </xsl:call-template>
              </xsl:variable>
 
   <xsl:variable name="DisplayTitle">
                     <xsl:call-template name="OuterTemplate.GetTitle">
                           <xsl:with-param name="Title" select="@Title"/>
                           <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                     </xsl:call-template>
              </xsl:variable>
                 <xsl:value-of select="concat(substring(@Body,0,500),'...')" disable-output-escaping="yes"/>
<div align="right" style="color:black">                     <a href="{$SafeLinkUrl}">Read more</a></div>
            

       </xsl:template>

Restore Site BackUp Using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

      Write-Host  
      Write-Host  
      Write-Host "Backup starting at $backupStart for $Site "  
      Write-Host "******************************************"
     Restore-SPSite -Identity http://globas:1040/ -Path "E:\Sharepoint\FirstPrincipal\SiteBackUp\FPBakup\Latest\fp_04oct2012-latest.bak" -force   
   
      Write-Host  
      Write-Host  
      Write-Host "Backup Completed at $backupComplete for $Site "  
      Write-Host "******************************************"

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Save Site Template using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
$Web=Get-SPWeb http://globas/

$Web.SaveAsTemplate("test4","test4","test4",0)


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Remove Web Application using Powershell


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
Remove-SPWebApplication http://globas:1030 -Confirm -DeleteIISSite -RemoveContentDatabases

Remove Solution using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 

Uninstall-SPSolution –Identity readmorewsp.wsp  -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Start-Sleep -Seconds 30

Remove-SPSolution –Identity readmorewsp.wsp -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Start-Sleep -Seconds 5

Uninstall-SPSolution –Identity fpmasterpage .wsp  -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Start-Sleep -Seconds 30

Remove-SPSolution –Identity fpmasterpage .wsp -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green

 

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

New Site And Templates Using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 

      Write-Host  
      Write-Host  
      Write-Host "Creating New Site....  "  

 

 

$newSite = New-SPWeb -URL "http://globas:1030" -Template "STS#1" -Name "Home"


$siteURL = $newSite

$owner = “Administrator”

$secondOwner = “Administrator”

$template = “STS#1?

$description = “This is a sample site that was built using PowerShell.”

New-SPSite $siteURL -OwnerAlias $owner -SecondaryOwnerAlias $secondOwner -name “PowerShell for SharePoint” -Template $template -Description $description

List All Web Application Lists using Powershell


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
Get-SPWebApplication

Export List Data using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

$MyWeb = Get-SPWeb "http://Globas"
$MyList = $MyWeb.Lists["sample"]
$exportlist = @()
$Mylist.Items | foreach {
$obj = New-Object PSObject -Property @{
            “Column1” = $_["Body"]
                          
}
$exportlist += $obj
$exportlist | Export-Csv -path 'C:\dom.csv'
}

Enable Site Features using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

Enable-SPFeature "SharePoint Server Standard Site features" -Url http://globas:1050

Delete Particular Subsite using Powershell

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

$ParentSiteUrl = "http://globas:1050/"

function DeleteSubSite([string]$SiteUrlName)
{
$SiteUrlName = $ParentSiteUrl + $SiteUrlName
Write-Host "SiteUrlName:" $SiteUrlName

Remove-SPWeb $SiteUrlName -Confirm:$false
Write-Host "Web:" $SubWeb.Title " deleted!"
}


DeleteSubSite "sun"

rm function:/DeleteSubSite

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Delete List using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
$web = Get-SPWeb http://globas:1010
$custom = $web.lists["Articles"]
$custom.Delete()

$custom1 = $web.lists["BasicWebparts - Gallery"]
$custom1.Delete()

$custom2 = $web.lists["ContentSlides"]
$custom2.Delete()

$custom3 = $web.lists["domphoto"]
$custom3.Delete()

$custom4 = $web.lists["dp"]
$custom4.Delete()

$custom5 = $web.lists["gallery"]
$custom5.Delete()

$custom6 = $web.lists["photo1"]
$custom6.Delete()

 

 

 

 


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Create Subsite using Powershell


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

New-SPWeb http://globas:1060/test -Template "STS#1"  -Name "test"

 

 

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Daily Site Backup Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
try
{
    $today = (Get-Date -Format dd-MM-yyyy)
    $backupDirectory = "D:\Backup\DailySiteCollectionBackUp\$today"
  # Backup file Location
    $backupFile = "D:\Backup\DailySiteCollectionBackUp\$today\Backup.bak"
  # Log file location
    $logFile = "$backupDirectory\BackupLog.log"  
  # Address of the Site Collection to backup
    $Site = "http://globas:1060/"
  
# Location of the Backup Folder
    if (-not (Test-Path $backupDirectory))
    {
      [IO.Directory]::CreateDirectory($backupDirectory)
      #New-Item $logPath -type $backupDirectory
    }
 
# Get backup start date and time
    $backupStart = Get-Date -format "MM-dd-yyyy HH.mm.ss"
  
  # creates a log file  Start-Transcript -Path
    Start-Transcript -Path $logFile
    
# This will actually initiate the backup process.
      Write-Host  
      Write-Host  
      Write-Host "Backup starting at $backupStart for $Site "  
      Write-Host "******************************************"
     Backup-SPSite -Identity $Site -Path $backupFile -Force
     $backupComplete = Get-Date -format "MM-dd-yyyy HH.mm.ss"
      Write-Host  
      Write-Host  
      Write-Host "Backup Completed at $backupComplete for $Site "  
      Write-Host "******************************************"
 
Stop-Transcript
}
Catch
{
  $ErrorMessage = $_.Exception.Message
  write "$today BackUp Failed   $ErrorMessage  ">>$logFile
 
}

Create Site Collection Using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue


#Get-SPWebApplication


     # Remove-SPWebApplication http://globas:1050 -Confirm -DeleteIISSite -RemoveContentDatabases

#Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
#Read-Host


function Start-SiteCollectionCreate(
    [string]$settingsFile = "sites.xml") {
    [xml]$config = Get-Content $settingsFile
   
    $config.SiteCollections.SiteCollection | ForEach-Object {

 

#Create WebApplication
Write-Host  
      Write-Host  
      Write-Host "WebApplication Creating........"  
      Write-Host "******************************************"
New-SPWebApplication -Name $_.Name -Port $_.Port -AllowAnonymousAccess  -URL $_.SiteCreationUrl -ApplicationPool $_.Pool -ApplicationPoolAccount (Get-SPManagedAccount $_.OwnerLogin)

Write-Host  
      Write-Host  
      Write-Host "WebApplication Sucussfully Created........" 

 

 


Write-Host  
      Write-Host  
      Write-Host "Site collection Creating........"  
      Write-Host "******************************************"


        #Creating site collection
        Write-Host "Creating site collection $($_.Url)..."
        $gc = Start-SPAssignment
        $site = $gc | New-SPSite `
            -Url $_.Url `
            -Description $_.Description `
            -Language $_.LCID `
            -Name $_.Name `
            -Template $_.Template `
            -OwnerAlias $_.OwnerLogin `
            -OwnerEmail $_.OwnerEmail `
            -SecondaryOwnerAlias $_.SecondaryLogin `
            -SecondaryEmail $_.SecondaryEmail
            Stop-SPAssignment -SemiGlobal $gc
        # Associate Default Groups (Dan Holme: http://www.sharepointpromag.com/article/sharepoint/Create-a-SharePoint-Site-Collection-with-Windows-PowerShell-UI-Style)
        $MembersGroup = "$_.Name Members"
        $ViewersGroup = "Viewers"
        $web = Get-SPWeb $_.url
        $web.CreateDefaultAssociatedGroups($_.OwnerLogin,$_.SecondaryLogin,"")
        $PrimaryAdmin = Get-SPUser $_.OwnerLogin -Web $_.url
        $PrimaryAdmin.Name = $_.OwnerDisplay
        $PrimaryAdmin.Update()
        $SecondaryAdmin = Get-SPUser $_.SecondaryLogin -Web $_.url
        $SecondaryAdmin.Name = $_.SecondaryDisplay
        $SecondaryAdmin.Update()

        # Finish by disposing of the SPWeb object to be a good PowerShell citizen
        $web.Dispose()
        }
    }

# Execute the script           
Start-SiteCollectionCreate


Write-Host  
      Write-Host  
      Write-Host "Site Collection Created........"  


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

 


 

Xml File

 

<SiteCollections>                   
    <SiteCollection Name="globas-1020"
                    Description=""
                    SiteCreationUrl="http://globas:1020/"
                    Port="1020"
                    Pool="globas1020"
                    Url="http://globas:1020"
                    LCID="1033"
                    Template="STS#0"
                    OwnerLogin="glob\administrator"
                    OwnerEmail="administrator@sgs.com"
                    OwnerDisplay="Administrator"
                    SecondaryLogin="glob\administrator"
                    SecondaryEmail="admin@cdfdontoso.com"
                    SecondaryDisplay="SharePoint Farm">
    </SiteCollection>

 

</SiteCollections>

Monday, 8 October 2012

CQWP PageQueryString and PageFieldValue

CQWP PageQueryString and PageFieldValue

PageQueryString allows to configure the Content Query Webpart dynamically using the query string in the url. Let's configure the CQWP to retrieve different categories of announcements based on the query string value. 
Add a CQWP to the page and configure Query section as follows :
Source: Show items from all sites in this site collection
List Type: Announcements
Content Type:Show items of this content type group : My Content Types


Content Type:
Show items of this content type: Company
 Announcements

In additional filters Select "Announcement Category" filed is equal to [PageQueryString : Category]
Save the webpart. I have placed the CQWP on the homepage of my site "http://intranet.contoso.com", so if I change the url to "http://intranet/SitePages/Home.aspx?Category=Technology", this is the result I get.

PageFieldValue is used to show the related content. Following examples illustrates it. Go to your list which contains our custom content type "Company Announcements". In the ribbon select List->Customize Form->Modify Form Webparts->Default Display Form 
Add CQWP and configure the webpart to use our custom content type. In Additional filters section select Announcement Category is equal to [PageFieldValue:Announcement Category] and  Title is not equal to [PageFieldValue:Title]

This will ensure that when we click on an item we will also get to see related items based on the Announcement Category of the current item and at the same current item will not be shown in the related announcements section.

CQWP XSL customizations - Read More Option

CQWP XSL customizations  - Read More Option

Posted by Nadeem Yousuf | 05:13 | , | 0 comments » Content Query webpart series:
Part 1: Configuring SharePoint 2010 CQWP

Part 2: CQWP PageQueryString and PageFieldValue
Part 3: CQWP XSL customizations
Part 4 : CQWP QueryOverride
CQWP style sheets are present inside a folder "XSL Style Sheets" in Style Library at the root site collection. ItemStyle.xsl file contains the style templates which can applied to the items returned by CQWP. The best practice to create custom styles is to make the copy of  ItemStyle.xsl and make changes in it and then upload the new customized xsl file to the style library.
Now let's create a custom style which will show the Title of our Company Announcements in bold font and show  first 200 characters of the Body field followed by ...Read More link. Create a copy ItemStyle.xsl file and name it  CustomItemStyle.xsl file. Open the file in any editor and paste the following at the end of the file before </xsl:stylesheet>. Upload the CustomItemStyle.xsl to Style Library inside XSL Style Sheets folder.


<xsl:template name="CustomStyle" match="Row[@Style='CustomStyle']" mode="itemstyle">
              <xsl:variable name="SafeLinkUrl">
                     <xsl:call-template name="OuterTemplate.GetSafeLink">
                           <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                           <xsl:with-param name="UseFileName" select="1"/>
                     </xsl:call-template>
              </xsl:variable>
              <xsl:variable name="DisplayTitle">
                     <xsl:call-template name="OuterTemplate.GetTitle">
                           <xsl:with-param name="Title" select="@Title"/>
                           <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                     </xsl:call-template>
              </xsl:variable>
              <p>
                     <strong>
                           <xsl:value-of select="$DisplayTitle"/>
                     </strong><br />
                     <xsl:value-of select="substring(@Body,0,200)" disable-output-escaping="yes"/>
                     <a href="{$SafeLinkUrl}">...Read more</a>
              </p>

       </xsl:template>

Now add a fresh CQWP to your page and then export it. Save the generated file and open it in notepad. Locate property ItemXslLink and replace it with following:
<property name="ItemXslLink" type="string">/Style Library/XSL Style Sheets/CustomItemStyle.xsl</property>
Locate property ItemStyle and replace it with following:
<property name="ItemStyle" type="string">DetailedOverview</property>
Save the webpart file and upload it to the SharePoint page.
After you upload the webpart file, you can find the webpart in Imported Web Parts category. Now add the web part to the page and edit it. Make the webpart to read data from whole site collection, select Announcements List, select My Content Types Group and Company Announcements content type. 
In the presentation section select following:
As can be seen a field named Body has been added. This is called a Slot. If we want to show more fields we can add them in xsl as we added Body field. Click OK to save the settings. The final result will be something like this.