Pages

Search This Blog

Tuesday, February 21, 2012

Create custom page layouts using Custom content type using CAML

Requirement:
At times, we come across a requirement to have custom page layouts and use those page layouts to create pages in the site. This needs to be done using CAML.

Scenario:
Lets take an example where you are creating a site definition for a customer, and the site should have a home page and some internal pages. Admin can create more internal pages with same layout as of the existing internal pages. In this scenario, we can create 2 custom page layouts within the site definition say Home Page & Inner Page, and then create new pages based on these page layouts.

Solution:
Here is how we achieve this:
Open Visual Studio 2010 and create a new project (Empty SharePoint project)

Step 1:
Create Custom content type derived from Article page content type.
  •    Right click the project and click Add -> New Item
  • Select Content Type from the list.
  • Give a suitable name for the content type.
  • Click Add.
  • Then it will ask, which base content type should your custom content type be inherited from. Select Article page from the list (In our case, it is article page. This can be inherited from any other type based on requirements)
  • Click Finish.
 
  • A feature with a content type is created in your solution. Open the Elements.xml file and you can update the properties of the content type like Name, Group, Description.
  • Notice the Content type ID generated by Visual Studio. This is a unique ID and will be used when we create page layouts using this content type.
 <?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Article Page (0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D) -->
  <ContentType ID="0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00f2f3fc2629204643b44911a79fa95814"
               Name="MyCustomContentType"
               Group="Custom Content Types"
               Description="My Custom Content Type"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
    </FieldRefs>
  </ContentType>
</Elements>
  • Now the content type is created and on deploying this, we can see out custom content type in the content type gallery on the site.
 
 
Step 2:
Create custom page layouts based on the custom content type:
  • Add a new module to the solution, and name it PageLayouts. 
  • Delete the Sample.txt file created automatically within the module.
  • Add 2 aspx pages (page layouts) with the name HomePage & InnerPage. The way to do this is by Clicking Add -> New Item -> Text File and then put the name as Home.aspx
 
  • Similarly add InnerPage.aspx.
  • Register the required namespaces and assemblies and then add web part zones on this page accordingly.
  • You can download these pages here.
  • Update the elements.xml file accordingly as shown below:
<!--[if gte mso 9]> <![endif][if gte mso 9]> Normal 0 false false false EN-US X-NONE X-NONE <![endif][if gte mso 9]> <![endif][if gte mso 10]> <!--><?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="PageLayouts" Url="_catalogs/masterpage">
    <File Path="PageLayouts\HomePage.aspx" Url="HomePage.aspx" Type="GhostableInLibrary" >
      <Property Name="Title" Value="Home Page" />
      <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" />
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/PublishingImages/HomePage.png" />
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00f2f3fc2629204643b44911a79fa95814;#" />
    </File>
    <File Path="PageLayouts\InnerPage.aspx" Url="InnerPage.aspx" Type="GhostableInLibrary" >
      <Property Name="Title" Value="Inner Page" />
      <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" />
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/PublishingImages/InnerPage.png" />
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D00f2f3fc2629204643b44911a79fa95814;#" />
    </File>
</Module>
</Elements>
  •  Deploy the solution. Activate the feature. Go to Master page and page layouts gallery. You can see HomePage and InnerPage Page layouts deployed there.

  • These custom page layouts can now be used to create new pages.

Sunday, February 19, 2012

How to retrieve trusted login provider information : claims based authentication : sharepoint 2010

Sharepoint 2010 supports claims based authentication wherein an external identity provider (like ADFS) issues SAML tokens which are used by sharepoint to authenticate users in the sharepoint web application.

Many a times, we need to programmatically retrieve the login provider's information in the sharepoint web application. This can be done using the following code:

using (SPSite theSite = new SPSite(http://siteurl/))
{
// Get the web application.
    SPWebApplication wa = theSite.WebApplication;
    // Get the zone for the site.
    SPUrlZone theZone = theSite.Zone;
    // Get the settings that are associated with the zone.
    SPIisSettings theSettings = wa.GetIisSettingsWithFallback(theZone);

    // Get the token service manager so that we can retrieve the appropriate
    // trusted login provider.
    SPSecurityTokenServiceManager sptMgr = SPSecurityTokenServiceManager.Local;
    // Get the list of authentication providers that are associated with the zone.
    foreach (SPAuthenticationProvider prov in
        theSettings.ClaimsAuthenticationProviders)
    {
        // Ensure that the provider we are looking at is a SAML claims provider.
        if (prov.GetType() ==
    typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
        {
            // Get the SPTrustedLoginProvider object by using the DisplayName property.
            var lp =
                from SPTrustedLoginProvider spt in
                sptMgr.TrustedLoginProviders
                where spt.DisplayName == prov.DisplayName
                select spt;
            // There should be only one match, so retrieve that value.
            if ((lp != null) && (lp.Count() > 0))
            {
                // Get the login provider.
                SPTrustedLoginProvider loginProv = lp.First();
                // Get the logon information.provinfo contains the display name of the trusted login provider
                // as well as the provider url
                string provInfo = prov.DisplayName + " - " +
                    loginProv.ProviderUri.ToString();
              
            }
        }
    }
}


Friday, February 17, 2012

SharePoint 15


Now you can download 

SharePoint 15 Technical Preview Interoperability API Documentation here 

Office 15 Technical preview from here



Monday, February 6, 2012

SharePoint Twitter 3.0


What is SharePoint Twitter?



Are you looking to show the twitter updates of your organization on your sharepoint portal ? If yes, then this project is what you might need.
We are providing five !webparts for SharePoint 2007 & SharePoint 2010.
  1. First, that can be used to show the tweets of any user on the SharePoint portal.
  2. Second webpart can be used to post tweet to twitter directly from your sharepoint portal.
  3. Third webpart can be used to show the friends of any user on the SharePoint portal.
  4. Fourth webpart can be used to show the followers of any user on the SharePoint portal.
  5. Fifth webpart can be used to show the 'follow us' link, which lets the user follow with a single click.
Just download and install, and you are all set.
All you need is to configure the twitter settings for each of the WebParts after installation.
These web parts use out of the box SharePoint CSS elements that match automatically with your current site theme.

Features

  1. Posting / Reading tweets from / to your twitter page
  2. 'follow Us' button webpart included.
  3. Paging support
  4. Show user images
  5. Show Header and footer
  6. Support for rich media content like images, links etc 

SharePoint Facebook Kit 4.0


What is SharePoint Facebook?




Have you ever needed to show the facebook updates of your organization on your sharepoint portal ? If yes, this project is for you.
What we provide is four webparts for SharePoint 2007 & SharePoint 2010.
  1. First that can be used to show the facebook wall of any user on the SharePoint portal.
  2. Second webpart can be used to post updates to facebook directly from your sharepoint portal.
  3. Third webpart, the Like Box, is a social plugin that enables Facebook Page owners to attract and gain Likes from their own website. The Like Box enables users to see how many users already like this Page, and which of their friends like it too.
  4. Fourth webpart, the Like button, lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user's friends' News Feed with a link back to your website.

Just download, install and configure, and you are all set. Follow our step by step guides for the configuration and installation sections provided below.

Features

  1. Posting / Reading feeds from wall/page/Group
  2. Like Box and Like Button webparts included.
  3. Paging support
  4. Show my or all feeds
  5. Show user images
  6. Support for rich media content like videos, images, links etc
  7. stsadm,powershell installers included 

SharePoint Project Template for Visual Studio 2010 (c#, VB)


What is SharePoint Project Template?

SharePoint Project Template is a predefined solution template for C# and VB with general classes and API's which is used in SharePoint projects which can save developer's effort to create solutions, writing base functionality and common methods

Who benefits from using SharePoint Project Template?

Using SharePoint Project Template benefits all of the following:
SharePoint Application Developers – Application developers can create predefined SharePoint solution in seconds. They will get already implemented exception class, logging, error capturing control, common method etc.

http://code.google.com/p/visual-studio-sharepoint-project-template/

Working on large lists in SharePoint


For working with large lists it’s good to use PortalSiteMapProvider class. This approach works especially well when you are retrieving list data that does not change significantly over time. When data sets change frequently, the class incurs the performance cost. PortalSiteMapProvider provides an automatic caching infrastructure for retrieving list data. The GetCachedListItemsByQuery method of PortalSiteMapProvider takes a SPQuery object as a parameter, and then checks its cache to determine whether the items already exist. If they do, the method returns the cached results. If not, it queries the list and stores the results in a cache.  When data sets change frequently, the class incurs the performance cost of continually writing to the cache in addition to the costs of reading from the database. Consider that the PortalSiteMapProvider class uses the site collection object cache to store data. This cache has a default size of 100 MB. You can increase the size of this cache for each site collection on the object cache settings page for the site collection. But this memory is taken from the shared memory available to the application pool and can therefore affect the performance of other applications. Another significant limitation is that you cannot use the PortalSiteMapProvider class in applications based on Windows Forms. The following code example shows how to use this method.

Code Snippet

SPSite objsite = new SPSite("URL")
SPWeb objWeb = objsite.OpenWeb())
               
// Create the query.
SPQuery curQry = new SPQuery();
curQry.Query = "<Where><Eq><FieldRef Name='Category'/><Value Type='Text'>Hotel</Value></Eq></Where>";

// Create an instance of PortalSiteMapProvider.
PortalSiteMapProvider ps = PortalSiteMapProvider.WebSiteMapProvider;
PortalWebSiteMapNode pNode = ps.FindSiteMapNode(curWeb.ServerRelativeUrl) as PortalWebSiteMapNode;

 // Retrieve the items.

SiteMapNodeCollection pItems = ps.GetCachedListItemsByQuery(pNode, "myListName_NotID", curQry, curWeb);

 // Enumerate through all of the matches.
 foreach (PortalListItemSiteMapNode pItem in pItems)
 {
      // Do something with each match.
  }


Powershell script to retrieve a deployed wsp from configuration database : SharePoint 2010

Many a times, we find ourselves in a situation wherein we want to find out what are the contents of a deployed wsp so as to debug issues, compare releases etc.

This is not such a trivial task as the sharepoint central administration pages do not provide us with any option to retrieve a deployed wsp from the sharepoint configuration database.

This task can be done through a powershell script. The powershell script given below takes 2 parameters:

- The display name of the solution to retrieve (.wsp file)
- A path on the local machine where the retrieved wsp will be saved.

If no name of the solution is given , it displays the list of deployed solutions to the user and lets the user choose the solution to retrieve. Many more such scripts can be seen at the source project for this script available at http://sharepointpsscripts.codeplex.com/


param ([string] $name, [string] $localpath)
#Load the required SharePoint assemblies containing the classes used in the script
#The Out-Null cmdlet instructs the interpreter to not output anything to the interactive shell
#Otherwise information about each assembly being loaded would be displayed
[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0 , Culture=Neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null

function Get-SolutionName()
{
    # Initialize an empty hashtable to store solution names and indexes
    $solHash = @{};
   
    # Bind to the collections of all solutions in the local farm and process them one by one, storing names in a hashtable
    # under automatically incremented indexes
    # The Foreach-Object cmdlet uses the begin/process/end structure to initialize the $i index counter
    ([Microsoft.SharePoint.Administration.SPFarm]::Local).Solutions |
        Foreach-Object {$i=1;} {$solHash.$i = $_.displayname; $i++} { }
   
    Write-Host;
   
    # If solutions were found, present the user with selection
    if ($solHash.Count -gt 0)
    {
        Write-Host -Object "The following solutions were found in the farm:" -ForegroundColor Green -BackgroundColor DarkMagenta;
        Write-Host;
       
        # Hashtables are not sortable, so in order to sort solutions by index keys have to be sorted separately first
        $solHash.Keys | Sort-Object | Foreach-Object {Write-Host -Object $("`t[{0}] {1}" -f $_, $solHash[$_]) -ForegroundColor Yellow -BackgroundColor DarkMagenta;}
        Write-Host;
        Write-Host -Object "Enter the index number of the solution you wish to retrieve, or 0 (zero) to exit: " -NoNewLine -ForegroundColor Green -BackgroundColor DarkMagenta;
       
        # Obtain input from user and return the matching value from the hashtable
        return $solHash[[int](Read-Host)];
    }
   
    # No solutions found in the configuration database
    else
    {
        Write-Host -Object "The local farm's solution store contains no solutions." -ForegroundColor Green -BackgroundColor DarkMagenta;
        Write-Host;
    }
}
# Check if name of target solution was specified as a parameter
if (-not $name)
{
    # Name of solution was not specifed, so call the Get-SolutionName function to obtain the name
    $name = Get-SolutionName;
   
    # If after calling the function the name is still unknown, stop execution
    if (-not $name)
    { break; }
}
# Check if local path to save the file to was specified as a parameter
if (-not $localpath)
{
    Write-Host;
    # Prompt and obtain local path value from user
    Write-Host -Object "Enter the local path to the folder you want the solution file to be saved to: " -ForegroundColor Green -BackgroundColor DarkMagenta;
    $localpath = Read-Host;
}
# Check if the path specified is valid and throw an exception if it's not
if (-not $(Test-Path -Path $localpath -PathType Container))
{
    throw "`"$localpath`" is not a valid path! If the path contains spaces, it must be enclosed in SINGLE quotes."
}
# Try to bind to the target solution
$solution = ([Microsoft.SharePoint.Administration.SPFarm]::Local).Solutions | Where-Object {$_.Name -eq $name}
Write-Host;
# Check if solution was found
if ($solution -ne $null)
{
    # Constitute the full local path (including file name)
    $solPath = Join-Path -Path $localpath -ChildPath $solution.SolutionFile.Name;
   
    # Try and save solution file locally
 $solution.SolutionFile.SaveAs($solPath);
   
    # If no errors occurred, display a success message
    if ($?)
    {
    Write-Host "Solution file saved successfully to $solPath" -ForegroundColor Green -BackgroundColor DarkMagenta;
       Write-Host;
    }
}
# Solution not found in the store; display a warning message
else
{
 Write-Host -Object "Solution `"$name`" could not be found!" -ForegroundColor Red -BackgroundColor DarkMagenta;
    Write-Host;
}

Tuesday, January 31, 2012

SharePoint 2010 Controls

To provide many of the rich new features for SharePoint 2010, a number of new controls have been
added for use in master pages. The following table highlights most of the new controls:

CONTROLS DESCRIPTION
SharePoint:SPShortcutIcon Sets the favicon in the top left of the browser
URL bar
SharePoint:CssRegistration
After=”corev4.css”
Tells SharePoint what to load after Corev4 css
SharePoint:SPRibbon Adds the Fluent UI (the ribbon) to the page
SharePoint:PopoutMenu Adds the breadcrumb that, when clicked, shows
the pop-out that displays your current location in
the site in a hierarchical tree structure
SharePoint:SPRibbonPeripheralContent Adds various items that are attached to the ribbon
SharePoint:PageStateActionButton Loads the page edit and save icon button near
the top left of the page
SharePoint:LanguageSpecificContent Displays content specifi c to the selected language
Sharepoint:DeveloperDashboardLauncher Launches the developer dashboard (which is hidden
by default but can be enabled with STSADM
or PowerShell)
SharePoint:ClusteredDirectionalSepar
atorArrow
Loads the arrow near the site icon after the
page title
SharePoint:AspMenu Renders tableless navigation
SharePoint:VisualUpgradePreviewStatus Displays the Visual Upgrade status in the status bar
SharePoint:VersionedPlaceHolder
UIVersion=”3”
Enables the capability to target page elements to
v3 or v4 capabilities
SharePoint:ClusteredSPLinkButton This is how SharePoint 2010 makes use of CSS
sprites
SharePoint:DeveloperDashboard Loads the actual developer dashboard at the bottom
of the master page This is hidden until the
launcher is clicked
SharePoint:WarnOnUnsupportedBrowsers Displays a warning to users who are trying to
access the site with an unsupported browser (e g ,
Internet Explorer 6)
wssuc:MUISelector Sets the MUI language selected that shows up in
the welcome menu if language packs are installed
SPSWC:MySiteCssRegistration Allows the use of specific CSS