Tuesday, October 2, 2012

Configure the Form Based Authentication (FBA) In SharePoint 2010

1) Today we are going to configure the Form Based Authentication in SharePoint Site.

2) First open the SQL Server management studio.

3) Create your new database named it as "TMP_FBA".

4) Now locate the below path to create a new sql membership tables. 

   ("C:\Windows\Microsoft.NET\Framework64\v2.0.50727")

5) Find the aspnet_regsql.exe and run it to create new tables to store the FBA Users.

6) So when this exe will run the number of tables will created as shown in screen shots.


7) Now to insert the users into the table , first create a new asp.net website using visual studio.

8) Open the web.config file for the new asp.net website.

9) Find the "connectionStrings" tag and replace it with the below line of tags.It will add the connection string        path and the configuration of the Membership provider and role provider as shown in Screen Shot.


10) I have added my customized tag inside the

<!--Customized Web.Config Start-->
  My Customiztion....
<!--Customized Web.Config Start-->


So new tags in asp.net websites are

<!--Customized Web.Config Start-->
<connectionStrings>
<add name="SQLConnectionString_TMP_FBA" connectionString="SERVER=YourServer\SharePoint; database=TMP_FBA; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<authentication mode="Forms" />
<membership defaultProvider="TMP_FBAMembershipProvider">
<providers>
<add connectionStringName="SQLConnectionString_TMP_FBA" passwordAttemptWindow="5"
enablePasswordRetrieval="false" enablePasswordReset="false"
requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true"
passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server"
name="TMP_FBAMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
<roleManager defaultProvider="TMP_FBARoleManager">
<providers>
<add connectionStringName="SQLConnectionString_TMP_FBA" applicationName="/"
description="Stores and retrieves roles from SQL Server" name="TMP_FBARoleManager"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
<!--Customized Web.Config End-->


11) Check the duplicate tag entries should not be exist.

12) Now open the Asp.net Administration site by click from the solution explorer for configure the membership provider and role provider as shown in screen shot.



13) Go to the Provider tag and Select the membership provider configured by the above config entry modification and select the second link named "Select a different provider for each feature (advanced)" for the Provider settings as shown in screen shot.


14) So select the membership provider as "TMP_FBAMembershipProvider" and role provider as "TMP_FBARoleManager".




15) Now go to the security tab of the asp.net administration site.Click on Create User link. 



16) Create one user named fbatest1 and fillup the other details and Click the Button Create User.



17) Now check the user is added inside the newly created database by go to the sqlserver and select the Database "TMP_FBA" and select the table "dbo.aspnet_Users".




18) Once the User is added then create a new webapplication from the Central Admininstation site.
Go to the Appllication Management -> select Manage Web Appplication -> From the Ribbon click New.

19) Now One popup window will open then select the "Claim Based Authentication".


20) Now Enabled the FBA by check the box and add the provider details and click OK to create web new application



21) Now we need to change total three web.config files To enable the Form Bases Authentication, 
a) In the  the newly created web applications , 
b) In the Central Administration and
c) In the Security token site located at "%programfiles%\common files\Microsoft Shared\web server extensions\14\WebServices\SecurityToken"

22) First we will modify the web application web.config file
Open the web.config file of the Web Application and add the connection string as after the </SharePoint> tag as Shown in screen shot.




<!--Customized Web.Config Start-->
  <connectionStrings>
<add name="SQLConnectionString_TMP_FBA" connectionString="SERVER=YourServer\SharePoint; database=TMP_FBA; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
   </connectionStrings>
  <!--Customized Web.Config Start-->

23) Now we will add the Membership and Role Provider tag in web.config file as shown in the screen shot  



 <membership defaultProvider="i">
      <providers>
        <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<!--Customized Web.Config Start-->
<add connectionStringName="SQLConnectionString_TMP_FBA" passwordAttemptWindow="5"
            enablePasswordRetrieval="false" enablePasswordReset="false"
            requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true"
            passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server"
            name="TMP_FBAMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--Customized Web.Config Start-->
      </providers>
    </membership>
    <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
        <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<!--Customized Web.Config Start-->
<add connectionStringName="SQLConnectionString_TMP_FBA" applicationName="/"
            description="Stores and retrieves roles from SQL Server" name="TMP_FBARoleManager"
            type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--Customized Web.Config Start-->
      </providers>
    </roleManager>

24) Second we will modify the Central Administration web.config file
Open the web.config file of the Central Administration and add the connection string as after the </SharePoint> tag as Shown in screen shot.




<connectionStrings>
<add name="SQLConnectionString" connectionString="SERVER=YourServer\SharePoint; database=MukeshFBA; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
<!--Customized Web.Config Start-->
<add name="SQLConnectionString_TMP_FBA" connectionString="SERVER=YourServer\SharePoint; database=TMP_FBA; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
<!--Customized Web.Config End-->
</connectionStrings>

25) Now we will add the Membership and Role Provider tag in web.config file as shown in the screen shot  




<membership>
      <providers>
 <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<!--Customized Web.Config Start-->
<add connectionStringName="SQLConnectionString_TMP_FBA" passwordAttemptWindow="5"
            enablePasswordRetrieval="false" enablePasswordReset="false"
            requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true"
            passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server"
            name="SQLConnectionString_TMP_FBA" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--Customized Web.Config End-->
      </providers>
    </membership>
    <roleManager>
      <providers>
 <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<!--Customized Web.Config Start-->
<add connectionStringName="SQLConnectionString_TMP_FBA" applicationName="/"
            description="Stores and retrieves roles from SQL Server" name="TMP_FBARoleManager"
            type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--Customized Web.Config End-->
 </providers>
    </roleManager>

26) Third we will modify the Security Token web.config file from "%programfiles%\common files\Microsoft Shared\web server extensions\14\WebServices\SecurityToken" location
Open the web.config file of the Central Administration and add the connection string as after the </system.net> tag as Shown in screen shot.


<connectionStrings>
    <add name="SQLConnectionString" connectionString="SERVER=YourServer\SharePoint; database=MukeshFBA; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
<!--Customized Web.Config Start-->
<add name="SQLConnectionString_TMP_FBA" connectionString="SERVER=YourServer\SharePoint; database=TMP_FBA; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
<!--Customized Web.Config End-->
</connectionStrings>

27) Now we will add the Membership and Role Provider tag in web.config file as shown in the screen shot 


<system.web>
  <membership defaultProvider="i">
      <providers>
        <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<!--Customized Web.Config Start-->
<add connectionStringName="SQLConnectionString_TMP_FBA" passwordAttemptWindow="5"
            enablePasswordRetrieval="false" enablePasswordReset="false"
            requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true"
            passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server"
            name="TMP_FBAMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--Customized Web.Config End-->
      </providers>
    </membership>
    <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
        <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<!--Customized Web.Config Start-->
<add connectionStringName="SQLConnectionString_TMP_FBA" applicationName="/"
            description="Stores and retrieves roles from SQL Server" name="TMP_FBARoleManager"
            type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--Customized Web.Config End-->
      </providers>
    </roleManager>
  </system.web>

28) Now once the modification in all the web.config file , Create one site collection
Open the newly created Site Collection then the below screen will appear


29) Now select the window Authentication , logged in with window credential to Add the FBA user to the Site Collection.

30) Now from the "Site Permissions" select the appropriate site collection group and add the FBA user.




31) Once the FBA user is added , sign out as a window authentication and from the sign in page select the "Form Authentication" from the dropdown and add the FBA user's credential.




32) That's it , You have configured the Form based authentication...

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