Friday, July 6, 2012

Save the value in sharepoint property bags



Hello,
In this article we will see the sharepoint property bag CRUD operation at different access level( farm level , Web application level , Site Collection level and web level )

Add the property farm level
---------------------------------
SPFarm farmObject = SPFarm.Local;
farmObject .Properties.Add("PropertyKey", "PropertyValue");
farmObject .Update();

Get the property farm level
------------------------------------
SSPFarm farmObject = SPFarm.Local;
if (farmObject.Properties != null && farmObject.Properties.Count > 0)
{
if (farmObject.Properties.ContainsKey("PropertyKey"))
{
String propertyValue = myWebApplication.Properties["PropertyKey"].ToString();
}
}

Change the property farm level
------------------------------------
SPFarm farmObject = SPFarm.Local;
if (farmObject.Properties != null && farmObject.Properties.Count > 0)
{
if (farmObject.Properties.ContainsKey("PropertyKey"))
{
farmObject.Properties["PropertyKey"] = "New Property Value";
        farmObject.Update();
}
}

Remove the property farm level
-------------------------------
SPFarm farmObject = SPFarm.Local;
if (farmObject.Properties != null && farmObject.Properties.Count > 0)
{
if (farmObject.Properties.ContainsKey("PropertyKey"))
{
farmObject.Properties["PropertyKey"] = null;
        farmObject.Properties.Remove("PropertyKey");
        farmObject.Update();
}
}

Add the property web application level
--------------------------------------
SPWebApplication webApplicationObject = SPWebApplication.Lookup(new Uri("http://YourWebApplicationURL"));
webApplicationObject.Properties.Add("PropertyKey", "PropertyValue");
webApplicationObject.Update();

Get the property web application level
--------------------------------------
SPWebApplication webApplicationObject = SPWebApplication.Lookup(new Uri("http://YourWebApplicationURL"));
if (webApplicationObject.Properties != null && webApplicationObject.Properties.Count > 0)
{
if (webApplicationObject.Properties.ContainsKey("PropertyKey"))
{
String propertyValue = webApplicationObject.Properties["PropertyKey"].ToString();
}
}

Change the property web application level
-------------------------------------------
SPWebApplication webApplicationObject = SPWebApplication.Lookup(new Uri("http://YourWebApplicationURL"));
if (webApplicationObject.Properties != null && webApplicationObject.Properties.Count > 0)
{
if (webApplicationObject.Properties.ContainsKey("PropertyKey"))
{
webApplicationObject.Properties["PropertyKey"] = "New Property Value";
webApplicationObject.Update();
}
}

Remove the property web application level
-----------------------------------------
SPWebApplication webApplicationObject = SPWebApplication.Lookup(new Uri("http://YourWebApplicationURL"));
if (webApplicationObject.Properties != null && webApplicationObject.Properties.Count > 0)
{
if (webApplicationObject.Properties.ContainsKey("PropertyKey"))
{
webApplicationObject.Properties["PropertyKey"] = null;
webApplicationObject.Properties.Remove("PropertyKey");          
webApplicationObject.Update();
}
}

Add the property site level
----------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    SPWeb rootWeb = site.RootWeb;  
    rootWeb.Properties.Add("PropertyKey", "PropertyValue");//In sharepoint there is no any provision to store the property value in SPSite object so we can use the RootWeb object
    rootWeb.Properties.Update();          
}

Get the property site level
--------------------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    SPWeb rootWeb = site.RootWeb;  
if (rootWeb.Properties != null && rootWeb.Properties.Count > 0)
{
if (rootWeb.Properties.ContainsKey("PropertyKey"))
{
String propertyValue = rootWeb.Properties["PropertyKey"].ToString();      
}
}
}

Change the property site level
--------------------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    SPWeb rootWeb = site.RootWeb;  
if (rootWeb.Properties != null && rootWeb.Properties.Count > 0)
{
if (rootWeb.Properties.ContainsKey("PropertyKey"))
{
rootWeb.Properties["PropertyKey"] = "New Property Value";
rootWeb.Update();    
}
}
}

Remove the property site level
-----------------------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    SPWeb rootWeb = site.RootWeb;  
if (rootWeb.Properties != null && rootWeb.Properties.Count > 0)
{
if (rootWeb.Properties.ContainsKey("PropertyKey"))
{
rootWeb.Properties["PropertyKey"] = null;
rootWeb.Properties.Remove("PropertyKey");            
rootWeb.Update();    
}
}
}

Add the property web level
----------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    using(SPWeb web = site.OpenWeb())
{  
web.Properties.Add("PropertyKey", "PropertyValue");
web.Properties.Update();          
}
}

Get the property web level
--------------------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    using(SPWeb web = site.OpenWeb())
{
if (web.Properties != null && web.Properties.Count > 0)
{
if (web.Properties.ContainsKey("PropertyKey"))
{
String propertyValue = web.Properties["PropertyKey"].ToString();      
}
}
}
}

Change the property web level
--------------------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    using(SPWeb web = site.OpenWeb())
{
if (web.Properties != null && web.Properties.Count > 0)
{
if (web.Properties.ContainsKey("PropertyKey"))
{
web.Properties["PropertyKey"] = "New Property Value";
web.Update();    
}
}
}
}

Remove the property web level
-----------------------------------------
using(SPSite site = new SPSite("http://server:port"))
{
    using(SPWeb web = site.OpenWeb())
{
if (web.Properties != null && web.Properties.Count > 0)
{
if (web.Properties.ContainsKey("PropertyKey"))
{
web.Properties["PropertyKey"] = null;
web.Properties.Remove("PropertyKey");            
web.Update();    
}
}
}
}

Regards
Hiren Patel

Thursday, July 5, 2012

Custom application page for the sharepoint RSS feeds.




Hello in this topic we will develope the custom application page for the sharepoint rss feeds.

- Here the different news(with different content type(1. Sharepoint News Page and 2.Sharepoint Article Page)) is associated with the Sharepoint Pages library.
And we have created the page library inside the "NewsSite" site.so my news site url will like "http://YourServer:Port/NewsSite/"

- Published date for the "Sharepoint News Page" content type is stored in "PressReleasePublihshedDate" field and
Published date for the "Sharepoint Article Page" content type is stored in the "PublihshedDate" field.

So above two types of news are stored in the SharePoint pages library.

- We have enabled the "Allow RSS for this list" settings for the Pages library.

- You can enabled it by go to the list settings - > go to the Communications section and click on the Rss Settings - >
  set the "Allow RSS for this list? " is true and press OK.
 
- We will display the news of both the content type together for the rss feeds.

- We will use the custom application page for that and stored it in the "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS" location.

- We will use the application page name as "SharepointCustomRSSFeeds.aspx"

- Now add the following line of code inside the aspx page.

- So SharepointCustomRSSFeeds.aspx application page will look like below

/*******************************************************************************************************************************/
<%@ Page Language="C#" %>

<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="Microsoft.SharePoint.Utilities" %>
<script runat="server">
public void Page_Load()
{
Response.Clear();
Response.ContentType = "text/xml";

try
{          
Response.Write(
GetRSSFromListView(
Request.QueryString["List"],
Request.QueryString["View"])
);
}
catch (Exception ex)
{
Response.Write("<pre>");
Response.Write(ex.ToString());
Response.Write("</pre>");
}
}
 
private static string GetRSSFromListView(string strListGUID, string strViewGUID)
{
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\"?>");
sb.Append("<rss version=\"2.0\">");
Guid listGuid = new Guid(
HttpContext.Current.Server.UrlDecode(strListGUID));
string siteUrl = SPContext.Current.Web.Url;
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = null;
try
{ list = web.Lists[listGuid]; }
catch { list = null; }
if (list != null)
{
SPView view = null;
if (strViewGUID != null)
{
Guid viewGuid = new Guid(
HttpContext.Current.Server.UrlDecode(strViewGUID));
view = list.Views[viewGuid];
}
else
{
view = list.DefaultView;
}
sb.Append("<channel>");
AddTag("title", list.Title, sb);
AddTag("description", list.Description, sb);
SPListItemCollection items = GetTheRssRecords(list);
DataTable FianlResults1 = MergedNewsRecords(items);
DataTable FianlResults = RecordsWithRFCDateFormat(FianlResults1);
string str="";
string str1="";
if (FianlResults.Rows.Count > 0)
{
foreach (DataRow row in FianlResults.Rows)
{
sb.Append("<item>");
AddTag("link", Convert.ToString(row["FileRef"]), sb);
AddTag("title", Convert.ToString(row["Title"]), sb);
IFormatProvider culture = new CultureInfo(SPContext.Current.Web.UICulture.ToString(), true);

str="<pubDate>";
str+=Convert.ToString(row["PublishedDate"]);
str+="</pubDate>";

sb.Append(str);

AddTag("description",Convert.ToString("<b style='font-size:12px'>"+row["PublishedDate"]+"</b>"), sb);

sb.Append("</item>");
}
}
sb.Append("</channel>");
sb.Append("</rss>");
}
}
}
return sb.ToString();
}
private static void AddTag(string tagText, string tagValue, StringBuilder sb)
{
sb.Append("<");
sb.Append(tagText.Replace(" ", "_"));
sb.Append(">");
sb.Append(HttpContext.Current.Server.HtmlEncode(tagValue));
sb.Append("</");
sb.Append(tagText.Replace(" ", "_"));
sb.Append(">");

}

public static DataTable MergedNewsRecords(SPListItemCollection items)
{
DataTable dtFinalRecords = new DataTable();
DataColumn Title = new DataColumn("Title", typeof(string));
DataColumn FileRef = new DataColumn("FileRef", typeof(string));
DataColumn PublishedDate = new DataColumn("PublishedDate", typeof(DateTime));
dtFinalRecords.Columns.Add(Title);
dtFinalRecords.Columns.Add(FileRef);
dtFinalRecords.Columns.Add(PublishedDate);
try
{
foreach (SPListItem item in items)
{
if (item.File.Item.ContentType.Name == "Sharepoint News Page" && !string.IsNullOrEmpty(Convert.ToString(item.Properties["PressReleasePublihshedDate"])))
{
DataRow rowFinal = dtFinalRecords.NewRow();
rowFinal["Title"] = item.File.Title;
rowFinal["FileRef"] = item.File.ServerRelativeUrl;
rowFinal["PublishedDate"] = Convert.ToDateTime(SPUtility.CreateDateTimeFromISO8601DateTimeString(item.Properties["PressReleasePublihshedDate"].ToString()));
dtFinalRecords.Rows.Add(rowFinal);
}
else if (item.File.Item.ContentType.Name == "Sharepoint Article Page" && !string.IsNullOrEmpty(Convert.ToString(item.Properties["PublihshedDate"])))
{
DataRow rowFinal = dtFinalRecords.NewRow();
rowFinal["Title"] = item.File.Title;
rowFinal["FileRef"] = item.File.ServerRelativeUrl;
rowFinal["PublishedDate"] = Convert.ToDateTime(SPUtility.CreateDateTimeFromISO8601DateTimeString(item.Properties["PublihshedDate"].ToString()));
dtFinalRecords.Rows.Add(rowFinal);
}
}
if (dtFinalRecords.Rows.Count > 0)
{
DataView viewResults = new DataView(dtFinalRecords);
viewResults.Sort = "PublishedDate DESC";
dtFinalRecords = viewResults.ToTable();
}
}
catch { }
return dtFinalRecords;
}

public static DataTable RecordsWithRFCDateFormat(DataTable items)
{
DataTable dtFinalRecords = new DataTable();
DataColumn Title = new DataColumn("Title", typeof(string));
DataColumn FileRef = new DataColumn("FileRef", typeof(string));
DataColumn PublishedDate = new DataColumn("PublishedDate", typeof(string));
dtFinalRecords.Columns.Add(Title);
dtFinalRecords.Columns.Add(FileRef);
dtFinalRecords.Columns.Add(PublishedDate);
try
{
if (items != null && items.Rows.Count > 0)
{
foreach (DataRow row in items.Rows)
{
DataRow rowFinal = dtFinalRecords.NewRow();
rowFinal["Title"] = row["Title"];
rowFinal["FileRef"] = row["FileRef"];
rowFinal["PublishedDate"] = Convert.ToDateTime(row["PublishedDate"]).ToString("dddd, d MMM yyyy hh:mm:ss");
dtFinalRecords.Rows.Add(rowFinal);
}
}
}
catch { }
return dtFinalRecords;
}

public static SPListItemCollection GetTheRssRecords(SPList list)
{
SPQuery query = new SPQuery();
SPListItemCollection results = null;
string strQuery = string.Empty;
strQuery = @"
<Where>
<Or>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>Sharepoint News Page</Value>
</Eq>
<Eq>
<FieldRef Name='ContentType' />
<Value Type='Text'>Sharepoint Article Page</Value>
</Eq>
</Or>
</Where>
";
}
query.Query = strQuery;
results = list.GetItems(query);
return results;
}
</script>
/*******************************************************************************************************************************/

- Now put this aspx page to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS"

- Now use our custom application page to rendered the RSS feeds.
  i.e. http://YourServer:Port/NewsSite/_layouts/SharepointCustomRSSFeeds.aspx?List=%7BA5EEB0B7%2DA64E%2D40F6%2D9F8D%2D319B3A86A337%7D

- You can get the list id from the address bar by go to the list settings page.
  Here we have not created any list view therefore the Query string parameter "View" will be null.

- Now paste the http://YourServer:Port/NewsSite/_layouts/SharepointCustomRSSFeeds.aspx?List=%7BA5EEB0B7%2DA64E%2D40F6%2D9F8D%2D319B3A86A337%7D url to the address bar,
  Our custom application page will render the rss feed.

 Regards
 Hiren Patel


Upgrade the SharePoint solution using PowerShell.


Hello today we will write the powershell script to upgrade the existing wsp to the sharepoint solution store.

1. Open any text editor.

2. Copy the below lines of script code inside it and save the file as like "Upgrade.ps1".

#************************************************************************************************************************
Write-Host ''
Write-Host 'Legal Intelligence deployment upgradation started.....' -foregroundcolor Cyan

# Ensure SharePoint cmdlets are loaded :
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Add-PsSnapin Microsoft.SharePoint.PowerShell
}

# Variables
$solutionNameCollection = @("Sharepointcustom.wsp")
$CurrentDir="D:\Solution Package"

# Upgrading the solution one by one
foreach ($solutionName in $solutionNameCollection)
{
Write-Host ''
Write-Host 'Starting upgradation of' $solutionName 'solution......' -foregroundcolor Cyan
$SolutionPath=$CurrentDir + "\" + $solutionName
Write-Host ''
Update-SPSolution -Identity $solutionName -LiteralPath $SolutionPath -GACDeployment -Local
Write-Host  'Completed upgradation of' $solutionName 'solution......' -foregroundcolor Cyan
Write-Host ''
}

Write-Host 'Upgradation completed.......' -foregroundcolor Cyan
Write-Host ''
Write-Host "Resetting IIS to clear application pools" -foregroundcolor Cyan
IISRESET
#************************************************************************************************************************

3. You need to change the current directory path of the wsp inside the script .For that find the "$CurrentDir" and replace it with your existing wsp path.
i.e. if you existing wsp is located to "D:\Solution Package" then value of the $CurrentDir is
$CurrentDir="D:\Solution Package"

4. Once the solution path will modified then change name of your wsp package.For that find the $solutionNameCollection value and replace it with your existing wsp name.
   i.e.if your wsp name is like "Sharepointcustom.wsp" then the value of $solutionNameCollection is
   $solutionNameCollection = @("Sharepointcustom.wsp")
   Note: if tou want to install the multiple wsp to the sharepoint solution store then seperate the wsp with comaa(,)
i.e. $solutionNameCollection = @("Sharepointcustom1.wsp","Sharepointcustom2.wsp","Sharepointcustom3.wsp")  

5. Save all the changes and open the "SharePoint Management Shell"  as an administrator mode from
   All Program -> Microsoft Sharepoint 2010 Products -> SharePoint Management Shell
 
6. Change the direcory path with the existing wsp path that you have already set the value of $CurrentDir="D:\Solution Package" in the script.
   From the powershell command propmt type the following command and press enter button.
   cd "D:\Solution Package"
 
7. Now type the following command and press enter.
   .\Upgrade.ps1
 
8. Likewise powershell script is used to upgrade the single or multiple wsp packages to the sharepoint solution store

Regards
Hiren Patel

Install the SharePoint solution using PowerShell.


Hello today we will write the powershell script to install the wsp to the sharepoint solution store.

1. Open any text editor.

2. Copy the below lines of script code inside it and save the file as like "Install.ps1".

#********************************************************************************
Write-Host ''
Write-Host 'Checking whether the required services are running...' -foregroundcolor Yellow
#Start necessary services
#Start service of World Wide Web
$WorldWideWebService = Get-Service -Name W3SVC
if ($WorldWideWebService.Status -ne "Running")
{
#Start-SPAdminJob
Write-Host ''
Write-Host  'Starting  World Wide Web Service ....' -foregroundcolor Cyan
Start-Service W3SVC
}

#Start service of Sharepoint admin
$adminService = Get-Service -Name SPAdminV4
if ($adminService.Status -ne "Running")
{
#Start-SPAdminJob
Write-Host ''
Write-Host  'Starting  SharePoint 2010 Administration Service ....' -foregroundcolor Cyan
Start-Service SPAdminV4
}

#Start service of Sharepoint Timer
$timerService = Get-Service -Name SPTimerV4
if ($timerService.Status -ne "Running")
{
#Start-SPTimerV4
Write-Host ''
Write-Host  'Starting  SharePoint 2010 Timer Service ....' -foregroundcolor Cyan
Start-Service SPTimerV4
}

# Ensure SharePoint cmdlets are loaded :
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Add-PsSnapin Microsoft.SharePoint.PowerShell
}

# Variables
$CurrentDir= "D:\Solution Package"
$solutionNameCollection = @("Sharepointcustom.wsp")
$SiteUrl="http://server:port"

# Foreach loop to add and deploy the multiple solution to the solution store.
foreach ($solutionName in $solutionNameCollection)
{
$SolutionPath=$CurrentDir + "\"+$solutionName

function WaitForJobToFinish([string]$SolutionFileName)
{
$JobName = "*solution-deployment*$SolutionFileName*"
$job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
if ($job -eq $null)
{
Write-Host 'Timer job not found' -foregroundcolor Red
}
else
{
$JobFullName = $job.Name
Write-Host ''
Write-Host -NoNewLine 'Waiting to finish "'
Write-Host -NoNewLine $JobFullName -foregroundcolor Green
Write-Host -NoNewLine '" job ' -foregroundcolor DarkGray

while ((Get-SPTimerJob $JobFullName) -ne $null)
{
Write-Host -NoNewLine . -foregroundcolor DarkGray
Start-Sleep -Seconds 2
}

Write-Host -NoNewLine ' Done'  -foregroundcolor Green
Write-Host ''
}
}

Write-Host ''
Write-Host 'Checking whether the solution exists in the Solutions Store.' -foregroundcolor Yellow
$solution = Get-SPSolution $solutionName -ErrorAction:SilentlyContinue

if ($solution -ne $null)
{
Write-Host $solutionName 'Already exists'
Write-Host ''

Write-Host 'Checking if' $solutionName 'is already deployed' -foregroundcolor Yellow

# Check whether the solution is already deployed.
if ($solution.Deployed)      
{
Write-Host $solutionName "is already deployed"
Write-Host ''

Write-Host "Uninstalling " $solutionName -foregroundcolor Cyan

if ($solution.ContainsWebApplicationResource)
{
Write-Host "Retracting" $solutionName " from all web applications" -foregroundcolor Cyan
Uninstall-SPSolution -identity $solutionName -allwebapplication -confirm:$false
}
else {
Write-Host "Retracting" $solutionName -foregroundcolor Cyan
Uninstall-SPSolution -identity $solutionName -confirm:$false
}

#Write-Host 'Waiting for job to finish' -foregroundcolor DarkGray
WaitForJobToFinish $solutionName

Write-Host ''
}

# Remove solution from store.
Write-Host 'Removing ' $solutionName -foregroundcolor Cyan
Remove-SPSolution -identity $solutionName -confirm:$false -Force:$true
Write-Host ''
}

# Add solution to Solutions Store. :
Write-Host "Adding" $solutionName " to the Solutions Store" -foregroundcolor Cyan
Add-SPSolution -LiteralPath $solutionPath
#Add-SPSolution $SolutionPath
Write-Host ''

Write-Host "Deploying" $solutionName -foregroundcolor Cyan
# Can use -CASPolicies also here
# Not to use -AllWebApplications option.
# If the solution contains Web Application Resource, use this command.

Install-SPSolution –Identity $solutionName -WebApplication $SiteUrl –GACDeployment -Force:$true

#Note: If you want to install the wsp globally then replace the above line with below
#Install-SPSolution –Identity $solutionName –GACDeployment -Force:$true
}
Write-Host ''

WaitForJobToFinish $solutionName
Write-Host ''
Write-Host 'Done Deploying Solutions' -foregroundcolor Green


Write-Host ''
Write-Host "Resetting IIS to clear application pools" -foregroundcolor Cyan
iisreset /noforce
#********************************************************************************

3. You need to change the current directory path of the wsp inside the script .For that find the "$CurrentDir" and replace it with your existing wsp path.
i.e. if you existing wsp is located to "D:\Solution Package" then value of the $CurrentDir is
$CurrentDir="D:\Solution Package"

4. Once the solution path will modified then change name of your wsp package.For that find the $solutionNameCollection value and replace it with your existing wsp name.
   i.e.if your wsp name is like "Sharepointcustom.wsp" then the value of $solutionNameCollection is
   $solutionNameCollection = @("Sharepointcustom.wsp")
   Note: if tou want to install the multiple wsp to the sharepoint solution store then seperate the wsp with comaa(,)
i.e. $solutionNameCollection = @("Sharepointcustom1.wsp","Sharepointcustom2.wsp","Sharepointcustom3.wsp")

5. Now the time is to change your sharepoint WebApplication url on which you want to install the wsp.For that
   find the $SiteUrl and replace its value with your webapplication url.
   $SiteUrl="http://server:port"
 
6. Install-SPSolution –Identity $solutionName -WebApplication $SiteUrl –GACDeployment -Force:$true
   This line will deploy the wsp on specific web application.If you want to deploy the wsp Globally then folowing command will use.
   Install-SPSolution –Identity $solutionName –GACDeployment -Force:$true

7. Save all the changes and open the "SharePoint Management Shell"  as an administrator mode from
   All Program -> Microsoft Sharepoint 2010 Products -> SharePoint Management Shell
 
8. Change the direcory path with the existing wsp path that you have already set the value of $CurrentDir="D:\Solution Package" in the script.
   From the powershell command propmt type the following command and press enter.
   cd "D:\Solution Package"
 
9. Now type the following command and press enter.
   .\Install.ps1
 
10.Likewise powershell script is used to install the single or multiple wsp packages to the sharepoint solution store

Regards
Hiren Patel

Rendered SharePoint search result in xml format


Hello ,
using below xslt we get the sharepoint 2010 search result in xml format.
For that ,
1. Go to the search result page
2. Edit the page and Edit the core search result webpart property.
3. Go to the xslt section and first create the backup of the existing xslt for the search result and replace it wil below xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xmp><xsl:copy-of select="*"/></xmp>
</xsl:template>
</xsl:stylesheet>
4. Click ok and save and publish the page
5. Perform search again it will rendered the search result in xml format.

Regards
Hiren Patel

Wednesday, July 4, 2012

Create pages programatically in SharePoint 2010


Hello,
- In this post we will get specified the content types in the sites and using that content type we will create the page programatically
- Using window application we will do this stuff.
- So first create the window application and add the Microsoft.Sharepoint.dll reference from the 14 hives directory.
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi )
-Now put some control as shown below and also give the appropriate name already mention below.





Now add the following lines of code insite the button click event and also add the custon methods.


//This function will use to get the specified content type and add those to the combo box
private void btnContentType_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite(txtURL.Text))
{
using (SPWeb web = site.OpenWeb())
{
PublishingSite pSite = new PublishingSite(site);
SPContentType ctype = pSite.ContentTypes[comboBoxContentType.SelectedText];
foreach (PageLayout p in pSite.PageLayouts)
{
if (p.AssociatedContentType.ResourceFolder.Name.ToLower() == "Custom content type 1".Trim().ToLower() && p.Name.ToLower() == "CustomPageLayouts1.aspx".ToLower())
{
comboBoxContentType.Items.Add(p.AssociatedContentType.ResourceFolder.Name);
}
else if (p.AssociatedContentType.ResourceFolder.Name.ToLower() == "Custom content type 2".Trim().ToLower() && p.Name.ToLower() == "CustomPageLayouts2.aspx".ToLower())
{
comboBoxContentType.Items.Add(p.AssociatedContentType.ResourceFolder.Name);
}
}
}
}
}
//Add the following line of code to the selected index change event of the combo box
private void comboBoxContentType_SelectedIndexChanged(object sender, EventArgs e)
{
if (pageLayoutForCreatingThePage != null)
{
lblPageLayouts.Text = pageLayoutForCreatingThePage.Name;
}
}
//Add following line of code to the button click event of the Create button , this code will useful to create the pages
private void btnCreate_Click(object sender, EventArgs e)
{
try
{
using (SPSite site = new SPSite(txtURL.Text))
{
using (SPWeb web = site.OpenWeb())
{
PublishingSite pSite = new PublishingSite(site);
PageLayout pageLayout = null;
foreach (PageLayout p in pSite.PageLayouts)
{
if (comboBoxContentType.SelectedItem.ToString().ToLower() == "Custom content type 1".Trim().ToLower() && p.AssociatedContentType.ResourceFolder.Name.ToLower() == "Custom content type 1".Trim().ToLower() && p.Name.ToLower() == "CustomPageLayouts1.aspx".ToLower())
{
pageLayout = p;
break;
}
else if (comboBoxContentType.SelectedItem.ToString().ToLower() == "Custom content type 2".Trim().ToLower() && p.AssociatedContentType.ResourceFolder.Name.ToLower() == "Custom content type 2".Trim().ToLower() && p.Name.ToLower() == "CustomPageLayouts2.aspx".ToLower())
{
pageLayout = p;
break;
}
}
pageLayoutForCreatingThePage = pageLayout;
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
PublishingPageCollection pPages = pWeb.GetPublishingPages();
SPList list = pPages.PubWeb.PagesList;
SPQuery query = null;
string pageName = string.Empty;
string strQuery = string.Empty;
Hashtable hs = new Hashtable();


strQuery = @"<FieldRef Name='Title' />";
strQuery = string.Format(strQuery, pageName);
query = new SPQuery();
query.Query = strQuery;
if (list.GetItems(query).Count > 0)
{
DataTable dt = list.GetItems(query).GetDataTable();
foreach (DataRow row in dt.Rows)
{
hs.Add(row["Title"].ToString().ToLower(), row["Title"].ToString().ToLower());
}
}
for (int i = 0; i < Convert.ToInt32(textBoxPagesToCreate.Text); i++)
{


pageName = comboBoxContentType.SelectedItem.ToString().Trim().Replace(" ", "-") + "-" + System.DateTime.Now.AddDays(i + 1).AddHours(i + 1).ToShortDateString().Replace("/", "_").ToString();
if (!hs.ContainsKey(pageName.ToLower()))
{
string filename = comboBoxContentType.SelectedItem.ToString().Trim().Replace(" ", "-") + "-" + System.DateTime.Now.AddDays(i + 1).AddHours(i + 1).ToShortDateString().Replace("/", "_").ToString() + ".aspx";
PublishingPage pPage = pPages.Add(filename, pageLayout);
SPListItem newpage = pPage.ListItem;
//Here we are setting the "Title" field property of the page
newpage["Title"] = comboBoxContentType.SelectedItem.ToString().Trim().Replace(" ", "-") + "-" + System.DateTime.Now.AddDays(i + 1).AddHours(i + 1).ToShortDateString().Replace("/", "_").ToString();
if (pageLayout.AssociatedContentType.ResourceFolder.Name.ToLower() == "Custom content type 1".Trim().ToLower())
{
//Here we are setting the "PublishStartDate" field property of the page
newpage["PublishStartDate"] = System.DateTime.Now.AddDays(i + 1).AddHours(i + 1);
}
else if (pageLayout.AssociatedContentType.ResourceFolder.Name.ToLower() == "Custom content type 2".Trim().ToLower())
{
//Here we are setting the "ReleasePublihshedDate" field property of the page
newpage["ReleasePublihshedDate"] = System.DateTime.Now.AddDays(i + 1).AddHours(i + 1);
}
newpage.Update();
newpage.File.CheckIn("Checked in");
newpage.File.Publish("published");
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}


MessageBox.Show("Operation Completed......");
}


1. Once the code is added , run the window application ,
2. First add the Site Url of you Site , second click on get content type button ( This will fetch the specified content type form the site)
3. Second select the desired content type from the combo box and insert the number of amount of page to create.
4. Third click on the Create button.
5. So it will create the number of pages that you specified using the selected content type.


Regards
Hiren Patel

Add Sitetemplate progrmatically in SharePoint 2010


Hello,
Today we will add the site template programatically in sharepoint site to each and every subsites.
We will create the window application for that.
Next steps is to add the Microsoft.SharePoint.dll form the 14 hives
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi.
Now put one lable from the toolbox section and set the text property as "Site Url".
Now put one text box beside of label and name it as txtSiteUrl.
Now add one button and named it as btnStart and set the text property as "Start".
so Final look of the window form is like





now add following lines of code to the button click event


private void btnStart_Click(object sender, EventArgs e)
{
try
{
using(SPSite site = new SPSite(txtSiteUrl.Text))
{
SPWeb rootWeb = site.RootWeb;
ConfigureSiteTemplate(site, rootWeb);
MessageBox.Show("Operation Completed Successfully........");
}
}
catch (Exception ex)
{
throw ex;
}
}



Below are the custom functions


private void ConfigureSiteTemplate(SPSite site, SPWeb web)
{
try
{
using (SPSite CurrentSite = new SPSite(web.Url))
{
using (SPWeb CurrentWeb = CurrentSite.OpenWeb())
{
SetSiteTemplate(CurrentWeb);
foreach (SPWeb currentWebSite in CurrentWeb.Webs)
{
ConfigureSiteTemplate(site, currentWebSite);//we are calling recursive function for each and every sub site
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void SetSiteTemplate(SPWeb currentWeb)
{
bool SharePointCutomTemplateAvailable = false;
Collection<SPWebTemplate> Collection = new Collection<SPWebTemplate>();
try
{
using (SPWeb curWeb = currentWeb)
{
using (SPSite curSite = curWeb.Site)
{
SPWebTemplateCollection TemplateCollection = curWeb.GetAvailableWebTemplates(curWeb.Language);
foreach (SPWebTemplate Template in TemplateCollection)
{
if (Template.Title == "Custom Sharepoint Template")//This is custom sharepoint template
{
SharePointCutomTemplateAvailable = true;//Here we are checking that the custom template with name "Custom Sharepoint Template" is already added or not
}
if (Template.Name != "ENTERWIKI#0")//we are adding wiki template
{
Collection.Add(Template);
}


}
foreach (SPWebTemplate template in curSite.GetWebTemplates(curWeb.Language))
{
if (!SharePointCutomTemplateAvailable && template.Title == "Custom Sharepoint Template")//If the custom template is not available we will add it
{
Collection.Add(template);//Here custom template is added
}
}
curWeb.SetAvailableCrossLanguageWebTemplates(Collection);
curWeb.Update();
}
}
}
catch (Exception ex)
{
throw ex;
}
}



Now run the application , and give the site url ( http://server:port ) of you sharepoint site and click on the button , it will add the given site template to your sharepoint sites and subsites.


Regards
Hiren Patel



Site template not found in sharepoint 2010



Hello,
When we are creating site using custom template using webtemp.xml file you will get the error like
Site template not found.
This is because of the same template id in the different webtemp.xml file under the specified culture folder.


e.g. for english "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\1033\XML"




<?xml version="1.0" encoding="utf-8"?>
<Templates xmlns:ows="Microsoft SharePoint">
<!--Provision for Global site-->
<Template Name="SharepointCustomGlobal" ID="10051">
<Configuration ID="0" Title="SharepointCustom content management host site"
Hidden="FALSE" ImageUrl="/_layouts/1033/images/IPPT.gif"
Description="A SharepointCustom site."
ProvisionAssembly="Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
ProvisionClass="Microsoft.SharePoint.Publishing.PortalProvisioningProvider"
ProvisionData="xml\\SharepointCustomGlobalPortal.xml"
RootWebOnly="TRUE" DisplayCategory="SharepointCustom" VisibilityFeatureDependency="97A2485F-EF4B-401f-9167-FA4FE177C6F6">
</Configuration>
</Template>
</Templates>


So to resolve this error you need to change the Template ID of your existing webtemp.xml file
So  suppose previously it was like 10051 so change it some what else not used by any one like 20050 something..
so modified webtemp.xml with new id id like


<?xml version="1.0" encoding="utf-8"?>
<Templates xmlns:ows="Microsoft SharePoint">
<!--Provision for Global site-->
<Template Name="SharepointCustomGlobal" ID="10051">
<Configuration ID="0" Title="SharepointCustom content management host site"
Hidden="FALSE" ImageUrl="/_layouts/1033/images/IPPT.gif"
Description="A SharepointCustom site."
ProvisionAssembly="Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
ProvisionClass="Microsoft.SharePoint.Publishing.PortalProvisioningProvider"
ProvisionData="xml\\SharepointCustomGlobalPortal.xml"
RootWebOnly="TRUE" DisplayCategory="SharepointCustom" VisibilityFeatureDependency="97A2485F-EF4B-401f-9167-FA4FE177C6F6">
</Configuration>
</Template>
</Templates>


Regards
Hiren Patel