Sunday, 1 June 2014

Power shell command to check event receivers associated to a list/library

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the web
$Web = Get-SPWeb "<website>"

#Get the Target List
$List = $Web.Lists["Document"]

#Retrieve all event receivers associated with the list
$List.EventReceivers | Select Id, Type, Assembly, Class | FL

Tuesday, 6 May 2014

Things to keep in mind while developing apps for SharePoint which expects anonymous user access

Things to keep in mind while developing apps for SharePoint which expects anonymous user access

A very common discussion topic in the SharePoint app world is , what are the points that we need to keep in mind when designing an app for anonymous users in a public site.

This issue comes up as there are many restrictions for anonymous users to access resources in a SharePoint world.

This MSDN documentation gives a clear documentation on the dos and don'ts while designing an app.
This link also guides developers, users and admins on the different considerations we need to keep in mind.

Saturday, 25 January 2014

Friday, 24 January 2014

Using before, after properties and properties.listItem in SharePoint event receivers

While handling business requirements in event receivers, we often need to handle common scenarios with before and after properties.

The behavior of these properties is different for a list and a library. Below is a summary of the behavior.

List:

List
BeforeProperties
AfterProperties
properties.ListItem
ItemAdding
No value
New value
Null
ItemAdded
No value
New value
New value
ItemUpdating
No value
Changed value
Original value
ItemUpdated
No value
Changed value
Changed value
ItemDeleting
No value
No value
Original value
ItemDeleted
No value
No value
Null

Library:

Library
BeforeProperties
AfterProperties
properties.ListItem
ItemAdding
No value
No value
Null
ItemAdded
No value
No value
New value
ItemUpdating
Original value
Changed value
Original value
ItemUpdated
Original value
Changed value
Changed value
ItemDeleting
No value
No value
Original value
ItemDeleted
No value
No value
Null



Thursday, 5 December 2013

Adding content editor web part with default content through Visual Studio

Content editor web parts are very handy in many purposes and it is used a lot nowadays. A typical requirement that I have come across, is to add a content editor web part, with some default content to a page through visual studio. The requirement looks quite simple. But there are few areas which we need to keep in mind to get this working as expected.
One aspect being the HTML content within the CEWP does not render as HTML rather it renders as plain text. This is explained int the last step.

The steps which we need to follow are :

  • add a page to through visual studio ( for our example we will add a page to the site pages gallery)
  • add a web part zone to the page

<asp:Content id="Content5" ContentPlaceHolderId="PlaceHolderMain" runat="server">         <table class="ms-core-tableNoSpace ms-webpartPage-root" width="100%"> <tr> <WebPartPages:WebPartZone runat="server" Title="CETestWebPart" ID="CETestWebPart" FrameType="TitleBarOnly"><ZoneTemplate> </ZoneTemplate></WebPartPages:WebPartZone> </tr> </table></asp:Content>

  • modify the elements.xml to add the content editor web part properties. An easy workaround to get all the properties correct is to create a CEWP on a page using UI and then exporting it. Then open it in a notepad. 
    • Add an allUsersWebPart , add a guid. Under <![CDATA[ put all the code copied from the notepad, till <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor"> 
  • within the content area add the default html in encoded format for the Content editor web part content. There are many HTML encoding decoding tool available online.
The final elements.xml will look like this :

 <File Path="SitePages\CEWebPart.aspx" Url="CEWebPart.aspx" Type="GhostableInLibrary" >
      <AllUsersWebPart WebPartOrder="1" WebPartZoneID="TestCEWP" ID="g_33268769_B61B_4665_8FF3_1BE038F0AB58">
        <![CDATA[
        
        <?xml version="1.0" encoding="utf-8"?>
<WebPart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/WebPart/v2">
  <Title>Content Editor</Title>
  <FrameType>Default</FrameType>
  <Description>Allows authors to enter rich text content.</Description>
  <IsIncluded>true</IsIncluded>
  <ZoneID>wpz</ZoneID>
  <PartOrder>0</PartOrder>
  <FrameState>Normal</FrameState>
  <Height />
  <Width />
  <AllowRemove>true</AllowRemove>
  <AllowZoneChange>true</AllowZoneChange>
  <AllowMinimize>true</AllowMinimize>
  <AllowConnect>true</AllowConnect>
  <AllowEdit>true</AllowEdit>
  <AllowHide>true</AllowHide>
  <IsVisible>true</IsVisible>
  <DetailLink />
  <HelpLink />
  <HelpMode>Modeless</HelpMode>
  <Dir>Default</Dir>
  <PartImageSmall />
  <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
  <PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge>
  <IsIncludedFilter />
  <Assembly>Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
  <ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
  <Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor">
  
     &lt;div&gt;test content for the CEWP &lt;/div&gt;       
             
  </Content>
        <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
        </WebPart>
        
        ]]>
      </AllUsersWebPart>
    </File>

To make the content within CEWP render as HTML we need to encode the content. If we put direct HTML SharePoint will remove all HTML elements and everything will be put under a single DIV. Hence the HTML will be rendered as plain text.


You can find the whole project at this location
https://github.com/debopamb/SPGithub/tree/master/CEWebpartProj

Thursday, 14 November 2013

Creating SharePoint site collections using powershell

We come across this scenario very often. We need to create a SharePoint site collection using an existing site template using power shell script.
To find the available templates you can use the below command :

Add-PSSnapin Microsoft.SharePoint.PowerShell
Get-SPWebTemplate | Sort-Object "Title"

Some of the widely used templates are

SRCHCENTERLITE#1     Basic Search Center
BLOG#0                            Blog
BICenterSite#0                   Business Intelligence Center
SRCHCEN#0                     Enterprise Search Center
CMSPUBLISHING#0        Publishing Site
WIKI#0                              Wiki Site


The below script will create a site collection using Enterprise Search Center

try
{
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue
 
## create the prerequisite

$webApplicationUrl = "http://server"
$siteCollectionUrl = "http://server/sites/SearchCenter"
$siteCollectionName = "Search Center"
$siteCollectionOwner1 = "DOMAIN\user1"
$siteCollectionOwner2 = "DOMAIN\user2"
$siteCollectionTemplate = "SRCHCEN#0"

 ## Check if the site collection exists or not
$SiteCollection = Get-SPSite $siteCollectionUrl -ErrorAction SilentlyContinue if ($SiteCollection -ne $null) { Write-Host "Search center already exists at " $siteCollectionUrl } else { ## Create the site collection New-SPSite -URL $siteCollectionUrl -OwnerAlias $siteCollectionOwner1 -SecondaryOwnerAlias $siteCollectionOwner2 -Name $siteCollectionName -Template $siteCollectionTemplate Write-Host "Search center created successfully" }
}
 
catch { Write-Host -ForegroundColor red "There were some problem in creating the search center" }





You can use any template as per availablilty .

Tuesday, 29 October 2013

Configure forms based authentication in SharePoint 2013

How to configure forms based authentication in 2013

·        This is a step by step approach on how to configure claim/form based authentication in SharePoint 2013. If you have configured Forms based authentication in earlier versions of SharePoint like 2010, the process to configure OOB forms based authentication in SharePoint 2013 is not much different. One major difference between SharePoint 2010 and the 2013 beta is that Claims Authentication is the only authentication method available in the User Interface (UI) within Central Administration. If necessary, we can still use PowerShell to create a Web App in “classic” mode. We are using the SharePoint 2013 beta version to show the configuration process here. Similar to earlier versions of SharePoint we need to perform the following steps :
1.       Create the Asp.net DB user/role repository
2.       Create a web application that uses Forms based authentication
3.       Update web.config file of Central Admin.      
4.       Update web.config file of the web application
5.       Update web.config file of the STS (Secure Token Service) Application
6.       Add some users in the database (can use ASP.net configuration wizard).
7.       Create a site collection
8.       Test the connection to the site collection with SQL users using FBA.

Step 1: Create the Asp.net DB user/role repository using SQL database
·        Go to the location: C:\Windows\Microsoft.NET\Framework\v4.0.30319 and find aspnet_regsql.exe and double click on it.

As an alternative you can go to visual studio tools -> developer command prompt for VS -> and type aspnet_regdsql.exe
·        The Asp.Net SQL server setup wizard will open up. Click next and then select “Configure SQL server for application services” as shown below.

·       Provide the server name, select Widows authentication and keep database as default.

·       Click next in the following screens to finish configuration.
·       Make sure that aspnetdb is created in SQL Management Studio on the SQL server and the login user has dbo rights in the aspnetdb database. On server explorer expand security -> logins -> double click on the user -> Select user mapping -> ckeck db_owner rights for the user.


·        Also perform the same steps for the SharePoint service account that you will use to create your web application.
·        Now we are done with our SQL database for Forms users. We will add users to this database in step 6.
Step 2: Create a web application that uses Forms based authentication
      
·        Go to central administration website -> click on application management -> Click new on the top ribbon -> fill all the details as expected.  For Forms based authentication under Claims Authentication Types select “Enable Forms Based Authentication (FBA)”. In our case as we have chosen default configuration, in the “ASP.NET membership provider name” enter “AspNetSqlMembers” and in the “ASP.NET Role manager name” enter “AspSqlRoles”.


Step3: Update web.config file of Central Admin.     
·        Easy way to locate the web.config file is to use IIS Manager and choose Explore after selecting the web site.
·        Before modifying the file please keep a backup of the original file.
·       We will need to update the central admin web.config to add our key to PeoplePicker entry
o   Find the </SafeControls> tag and add the following entry below it :

<PeoplePickerWildcards>
      <clear />
      <add key="AspNetSqlMembers" value="%" />
 </PeoplePickerWildcards>

Refer to the below image


Step 4: Update web.config file of the web application
·        Locate the web.config in a similar way as mentioned in step 3 and please keep a backup of the file before modifying
·        Find the <PeoplePickerWildcards> entry and add our key. It should look like
<PeoplePickerWildcards>
      <clear />
      <add key="AspNetSqlMembers" value="%" />
      <add key="AspNetSqlMembershipProvider" value="%" />
    </PeoplePickerWildcards>
·        Refer to the image below:


·        Next find the “<machineKey validationKey” entry and add the below entry after “<machineKey>” tag ends

<membership defaultProvider="i">
      <providers>
        <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <add connectionStringName="sqlconn" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" passwordAttemptWindow="10" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" name="AspNetSqlMembers" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </membership>
    <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
        <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
        <add connectionStringName="sqlconn" applicationName="/" name="AspNetSqlRoles" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>

Please refer to the image below:

·        Next find the tag “</microsoft.identityModel>” and add the below connection string entry :
<connectionStrings>
    <add name="sqlconn" connectionString="data source=INSPS02;User Id=sa;Password=pass@word1;Initial Catalog=aspnetdb" providerName="System.Data.SqlClient" />
  </connectionStrings>

Please refer to the image below:


Step 5: Update web.config file of the STS (Secure Token Service) Application

·        Here we will add the membership and role provider entries and the connection string entry
·        Find the web.config file same way as done in previous steps and keep a backup of the same.
·        Find <system.web> entry and add the below entry within it. If the system.web entry is not there, please create one.
<membership defaultProvider="AspNetSqlMembers">
      <providers>
        <add connectionStringName="sqlconn" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" passwordAttemptWindow="10" requiresUniqueEmail="false" passwordFormat="Hashed" applicationName="/" name="AspNetSqlMembers" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

      </providers>
    </membership>
    <roleManager defaultProvider="AspNetSqlRoles" enabled="true">
      <providers>
        <add connectionStringName="sqlconn" applicationName="/" name="AspNetSqlRoles" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>

·        Please refer to the image below


·        Below the <stsyem.web> entry add the connection string entry as mentioned below:
<connectionStrings>
    <add name="sqlconn"
   connectionString="data source=INSPS02;User Id=sa;Password=pass@word1;Initial Catalog=aspnetdb"
   providerName="System.Data.SqlClient" />
  </connectionStrings>

·        Please refer to the image below:



Step 6: Add some users to the database:

We will use aspnet configuration wizard to add users the SQL database
·        Create an empty asp.net website in visual studio
·        Modify the web.config by adding the following connection string entry (modify the datasource with your datasource name):
<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="Data Source=INSPS02;Initial Catalog=aspnetdb;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
·        Please refer to the image below:

·        Build the application
·        Navigate to website-> asp.net configuration


·        Navigate to security -> create user and create the desired users.

Step 7: Create a site collection to test the FBA configuration

·        Go to central admin and create a site collection using the web application configured above.

Step 8:  Test the connection to the site collection with SQL users using FBA

·        Navigate to the website url -> choose windows authentication
·        Navigate to users and groups and add the user created in step 6 to the read only user group, then logout from the website.
·        Login the application using forms authentication -> provide the user details of the user created in step 6.
·        Navigate the website as a forms user.