Thursday, May 28, 2015

Sharepoint 2010 Create a Custome Master Page using Visual Studio

First of all, you need to get SharePoint 2010 installed and Visual Studio 2010.

Next open Visual Studio 2010 and create a new Project.
I choose the language Visual C# on the left, then selected SharePoint –> 2010 and then create an Empty SharePoint Project.
I named the project: MasterPageWithCodeBehind.



After clicking the OK button, you will be asked how and where you want to deploy it, I choose to Deploy it as a farm solution.


Module


Right-click on the SharePoint Project in your Solution Explorer on the right then –> Add –> New Item.


You’ll get a new window where you can choose multiple items. I created a module and called it MasterPageModule.


You’ll see that the module is added to your project with a sample file called Sample.txt. There’s also an Elements.xml file in the module, in this file the other files will be registered. I deleted the Sample.txt in my Solution Explorer and Visual Studio automatically removed it from the Elements.xml file.

The next step I did was copying my custom masterpage into the module. This can be done by copying the file from Windows Explorer en then right-click on your Module in the Solution Explorer. You can get his minimal masterpage here: Starter Master Page.

After I paste it into my Module my Elements.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule">
  <File Path="MasterPageModule\_starter.master" Url="MasterPageModule/_starter.master" />
</Module>
</Elements>
In Module this attribute needs to be added: Url="_catalogs/sharepoint".
In File the Url attribute needs to be changed as follows: "_starter.master"
In File also this attribute needs to be added: Type="GhostableInLibrary".
This will make sure that the file will be cached. More info here.


My Element.xml looks like this now:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule" Url="_catalogs/masterpage">
    <File Path="MasterPageModule\_starter.master" Url="_starter.master" Type="GhostableInLibrary"/>
  </Module>
</Elements>


Feature

In this beta of Visual Studio 2010 a feature is automatically created when I added a Module into the solution. If not you have to create a feature yourself, here’s how you do it: (if there’s automatically added a feature you can skip it and move to the next part)
———-
The final step to do is creating a feature that will configure the masterpage.
Right-click on Features in your Solution Explorer and click Add Feature.



Now a new Feature is created, and the properties window of that Feature has popped up. Underneath the Title, Description and Scope there are 2 large fields. On the left you’ll see the created Module, add this to the left and it should look like this:



———–

Next I right-clicked on the Feature1 and then –> Add Event Receiver.



A new window will be open with the content of Feature1.EventReceiver.cs.
Uncomment these methods:
  • FeatureActivated
  • FeatureDeactivating
The code underneath will overwrite the MasterPage variables.
When it is deactivated it will restore the values back to a default SharePoint masterpage.
The code:
—————–
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb currentWeb = (SPWeb)properties.Feature.Parent;

    currentWeb.MasterUrl = "/_catalogs/masterpage/_starter.master";
    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/_starter.master";
    currentWeb.Update();
}

// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    SPWeb currentWeb = (SPWeb)properties.Feature.Parent;

    currentWeb.MasterUrl = "/_catalogs/masterpage/nightandday.master";
    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/nightandday.master";
    currentWeb.Update();
}
——————-

End of part 1


When this will be deployed, the custom masterpage is loaded instead of the default without uploading/publishing a masterpage trough the web interface, pretty neat huh.
Your SharePoint 2010 site should look something like this now (if you used the same masterpage as I did):


This is the first part of how to create a code-behind file and this part is focused on how getting the fundamentals right. The result of following part 1 is a alternative manner to deploy a masterpage.




Start of Part 2
In part 2 I will tell how I eventually got a code-behind file working on the custom master-page that I deployed trough Visual Studio. To be clear I don’t use SharePoint Designer to customize my master pages so I cannot guarantee that those pages will work.
To completely understand this information I recommend you to read Part 1 first.
The story continues….

 

Add Reference…

The next thing to do is adding a Reference to the SharePoint 2010 project.
This can be done by right-click on References in the Solution Explorer and then –> Add Reference



A new Window will popup arise that look like this:

As far as I know there 2 References that there need to be added:
  • Microsoft.SharePoint.Publishing
    • First select the Browse tab
    • then go to following directory: C:\Program Files\Microsoft Office Servers\14.0\Bin
    • Select Microsoft.SharePoint.Publishing.dll
    • Press the OK button
  • System.Web
    • Repeat the Add reference step
    • Now select the .NET tab
    • Find the System.Web
    • Select it and press the OK button














Add object(s) for the code-behind file

In this how-to I will add 2 objects that I will manipulate with the code-behind file.
asp:LabelFirst I added an asp:Label to the masterpage. I put this above the ribbon section so it will be noticed when it works.
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
div
I put a simple div around the ribbon so that I can disable the complete ribbon.

<div id="divRibbonContainer" runat="server">
<!-- =====  Begin Ribbon ============================================================ -->

<!-- =====  End Ribbon and other Top Content ============================================================ -->
</div>
The id’s of these objects will be needed for the code-behind file.

The code-behind file

To create a code behind file right-click on the Module in the solution, –> Add –> New Item…


In the following window select on the left Code –> Class and I called the file _starter.master.cs, just like a normal code-behind file.



There are some things that need to be added
  • Add using statements of:
    • System.Web;
    • System.Web.UI;
    • System.Web.UI.WebControls;
  • Make the class public and let it inherit from Masterpage
  • Declare protected objects from the masterpage
  • Add a page_load method
If you’ve done all that your class should look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MasterPageWithCodeBehind.MasterPageModule
{
    public class _starter : MasterPage
    {
        protected System.Web.UI.HtmlControls.HtmlGenericControl divRibbonContainer;
        protected Label Label1;

        protected void Page_Load(object sender, EventArgs e)
        {
            divRibbonContainer.Visible = false;
            Label1.Text = "Hello World!";
        }
    }
}

Retrieving Public Key Token/PublicKeyToken

This is a little bit tricky, this token is needed in the next step when we need to apply the Inherits attribute.
  • First build the project
  • Right-click on the SharePoint 2010 project in the Solution Explorer
    • Click –> Open Folder in Windows Explorer
    • Next open: bin
    • Open: Debug
    • Copy the directory path and paste it into a text editor or something like that
    • Next copy the filename of the <Projectname>.dll file en past it behind the path you just pasted in the text editor
    • The result should be something like this:
      D:\administrator\documents\visual studio 2010\Projects\MasterPageWithCodeBehind\MasterPageWithCodeBehind\bin\Debug\MasterPageWithCodeBehind.dll
  • Next go to Start (Windows start menu)
    • Programs/All programs
      • Microsoft Visual Studio 2010
        • Visual Studio Tools
          • Visual Studio Command Prompt (2010)
You’ll get a dos prompt.
Do the following things:

  • Enter the following command: cd\
  • Next copy your complete directory path including the *.dll from your texteditor
  • Type the following:
    – sn.exe –Tp “<paste your directory + filename in here>”Don’t forget the quotes around the directory and filename
    It should look something like this:
    sn.exe -Tp "D:\administrator\documents\visual studio 2010\Projects\MasterPageWithCodeBehind\MasterPageWithCodeBehind\bin\Debug\MasterPageWithCodeBehind.dll"
The output should be something like this:

Copy the Public key token.

Inherits

To combine the code-behind file with the masterpage there need to be an attribute added to the masterpage directive.
The following data is needed:

  • Namespace of the class & Type/Class name (these need to be seperated by a dot) (MasterPageWithCodeBehind.MasterPageModule._starter)
  • Strongname/Assembly in my case was this the same as the projectname (MasterPageWithCodeBehind)
  • Version (Version=1.0.0.0)
  • Culture (Culture=neutral)
  • PublicKeyToken (PublicKeyToken=f8a88530fbc7b81b)In the masterpage navigate to the following:
    <%@ Master language="C#" %>
Add the following Inherits attribute:
<%@ Master language="C#" Inherits="" %>

Now the 5 dots above need to be combined, in my situation it looks like this:
MasterPageWithCodeBehind.MasterPageModule._starter, MasterPageWithCodeBehind, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f8a88530fbc7b81b

Place this as value from the Inherits attribute.

Result

Deploy your SharePoint 2010 project and load the default site.
Your ribbon should be gone and a text like Hello World! should be visible.

The left top corner of my SharePoint 2010 looks like this now:


Wednesday, May 27, 2015

Sharepoint 2013 Create a Custome Master Page based on Seattle.master

Create a new project:



Configure as a Sandbox or Farm  Solution:

https://raquelalineblog.files.wordpress.com/2013/04/branding11.png

Add a new Module to your project:

https://raquelalineblog.files.wordpress.com/2013/04/branding21.png

Download a copy of Seattle.master:
https://raquelalineblog.files.wordpress.com/2013/04/branding3.png

Add the copy to your module, rename to CustomMaster.master, and Change your elements.xml file to point to _catalogs\masterpage folder:

https://raquelalineblog.files.wordpress.com/2013/04/branding4.png

Change your masterpage, to include a welcome message:

https://raquelalineblog.files.wordpress.com/2013/04/branding7.png

Deploy your solution and change your Site master page:

https://raquelalineblog.files.wordpress.com/2013/04/branding5.png

Verify that it shows your welcome message:

https://raquelalineblog.files.wordpress.com/2013/04/branding6.png

Thursday, May 21, 2015

Show Multiple Columns like table in Content Query Web Part in SharePoint 2013

Showing multiple columns in content query web part was what I was working on this week in our SharePoint 2013 environment.
This post is a quick summery of what I learned through the whole work.
  1. My platform is SharePoint 2013
  2. I’m using content type syndication, so the hub is another site collection and in a second site collection I’m going to use CQWP based on a specific content type with its own site columns
  3. Step1, to know what itemstyle.xsl is and how it works. then customize it
  4. step2, to know what ContentQueryMain.xsl is and how it works, then customize it
  5. A trick to insert CQWP on your SharePoint web page
For this search for the following lines



<xsl:call-template name="OuterTemplate.CallItemTemplate">
   <xsl:with-param name="CurPosition" select="$CurPosition" />
</xsl:call-template>
And change it to:




<xsl:call-template name="OuterTemplate.CallItemTemplate">
    <xsl:with-param name="CurPosition" select="$CurPosition" />
    <xsl:with-param name="LastRow" select="$LastRow" />
</xsl:call-template>
Now that we pass the parameter we also have to change the template to accept the parameter.
Go to lines and you see the “CallItemTemplate”. Copy the second line and past it directly beneath it and make it look like this:



<xsl:template name="OuterTemplate.CallItemTemplate">
<xsl:param name="CurPosition" />
<xsl:param name="LastRow" />
Because we want to use this within our custom item template we also have give the parameter through to the template by adding a when statement just before the <xsl:otherwise> within the CallItemTemplate:






<xsl:when test="@Style='ProjectsReport'">
 <xsl:apply-templates select="." mode="itemstyle">
  <xsl:with-param name="CurPos" select="$CurPosition" />
  <xsl:with-param name="Last" select="$LastRow" />
 </xsl:apply-templates>
</xsl:when>
In this statement we specify that it only has to pass-through the parameter when the item template is ProjectsReport. So our custom template is going to be called “ProjectsReport”.

and my final custom code is like this. I tried to use SharePoint light banded rows style to have a better view. Don’t forget there’s a little customize for ContentMainQuery.xsl as mentioned above.




































































<xsl:template name="ProjectsReport" match="Row[@Style='ProjectsReport']" mode="itemstyle">
    <xsl:param name="CurPos" />
    <xsl:param name="Last" />   
<xsl:variable name="tableStart">
      <xsl:if test="$CurPos = 1">
       <![CDATA[
        <table width="100%" class="ms-rteTable-6" cellpadding="1" cellspacing="0">
         
<tr class="">
            <th class="">Name</th>
            <th class="">Client</th>
            <th class="">Status Summary</th>
            <th class="">Project Phase</th>
            <th class="">This Reporting Period</th>
            <th class="">Next Reporting Period</th>
            <th class="">Key Issues and Risks</th>
          </tr>]]>  
      </xsl:if>
    </xsl:variable>
  
    <xsl:variable name="tableEnd">
      <xsl:if test="$CurPos = $Last">
        <![CDATA[ </table> ]]>
      </xsl:if>
    </xsl:variable>
    <xsl:variable name="rowStart">
        <xsl:if test="$CurPos mod 2 = 0">
            <![CDATA[
              <tr class="ms-rteTableEvenRow-6">
            ]]>
        </xsl:if>
        <xsl:if test="$CurPos mod 2 != 0">
            <![CDATA[
              <tr class="ms-rteTableOddRow-6">
            ]]>
        </xsl:if>
    </xsl:variable>
    <xsl:variable name="rowEnd">
               <![CDATA[
              </tr>
            ]]>
    </xsl:variable>
    <xsl:value-of select="$tableStart" disable-output-escaping="yes"/>
    <xsl:value-of select="$rowStart" disable-output-escaping="yes"/>
        <td>
            <xsl:value-of select="@ProjectName" />
        </td>
        <td>
            <xsl:value-of select="@ProjectClient" />
        </td>
        <td>
            <xsl:value-of select="@StatusSummary" disable-output-escaping="yes" />
        </td>
        <td>
            <xsl:value-of select="@ProjectPhase" />
        </td>
        <td>
            <xsl:value-of select="@ThisReportingPeriod" disable-output-escaping="yes" />
        </td>
        <td>
        <xsl:value-of select="@NextReportingPeriod" disable-output-escaping="yes" />
        </td>
        <td>
            <xsl:value-of select="@KeyIssuesRisks" disable-output-escaping="yes" />
        </td>
    <xsl:value-of select="rowEnd"/>
    <xsl:value-of select="$tableEnd" disable-output-escaping="yes"/>
</xsl:template>


Use PowerShell to Reset to Site Definition in SharePoint Server 2013

  1. Browse to the Site Settings page for the site (e.g. http://cyclops/sites/Demo/_layouts/settings.aspx).
  2. On the Site Settings page, in the Site Actions section, click Reset to site definition.
  3. On the Reset Page to Site Definition Version page, click the option to Reset all pages in this site to site definition version, and then click Reset.
Today, I was about to perform this process manually on several sites, but then I decided to spend a few minutes exploring the Reset Page to Site Definition Version page (e.g.http://cyclops/sites/Demo/_layouts/reghost.aspx).
That's when I discovered the SPWeb.RevertAllDocumentContentStreams method. [I'm actually a little embarrassed that I wasn't aware of this little gem before. A few years ago, while working on the Agilent Technologies project, I'd used some custom C# to reghost specific pages (to resolve deployment issues), but I clearly recall some general "wonkiness" with it. If I'd known about the RevertAllDocumentContentStreamsmethod a few years ago, I probably would have just run that as part of each and every deployment ;-) ]
Anyway, once you know about the method, it's very easy to call it from PowerShell.
Here's a little script to reset all pages in a list of sites to the site definition version:
$sitesToReset =
    @(
        "http://cyclops/sites/AdventureWorks",
        "http://cyclops/sites/Demo",
        "http://cyclops/sites/Toolbox"
    )

$sitesToReset |
    ForEach-Object {
        $DebugPreference = "SilentlyContinue"
        $web = Get-SPWeb $_

        $DebugPreference = "Continue"
        
        Write-Debug "Reghosting all pages in site ($($web.Url))..."
        $web.RevertAllDocumentContentStreams()
        $web.Dispose()
    }

Perform a SharePoint 2013 site collection upgrade with PowerShell

I gave a talk about PowerShell in SharePoint 2013.  In that talk I upgraded a SharePoint 2010 site collection to SharePoint 2013.  I wanted to follow-up with a blog post showing the steps involved.  To begin the process, I have restored a copy of my content database from my SharePoint 2010 environment on the SQL Server for my SharePoint 2013 environment.  The first thing we need to do is mount the content database with Mount-SPContentDatabase. In SharePoint 2010, this process would actually update the database and perform the upgrade.  Now, it actually just attaches the database but leaves the site running in SharePoint 2010 mode.  Effectively you are running a full copy of SharePoint 2010 inside SharePoint 2013.  You can do this and upgrade each site collection one at a time to make the transition process a bit easier. 
Typically, when you are doing this, you’ll execute Test-SPContentDatabase first and resolve any reported issues.  Just like in SharePoint 2010, you need to install all of your customizations via solution package prior to mounting.  Test-SPContentDatabase can help you find some of these customizations if they are missing.  For simplicity, I am going to leave that out of my example today.  Mount-SPContentDatabase typically takes two parameters:  the name of the database and the URL of the Web Application to bind it to.  Here is what the command looks like.

Mount-SPContentDatabase –Name DatabaseName –WebApplication http://server
When it runs, you’ll see a progress indicator.
MountSPContentDatabaseProgress
When it finishes, you’ll likely have errors.  You can track them down and re-mount.  More than likely you’ll always have some kind of error regardless of how hard you try.
MountSPContentDatabaseCompleteWithErrors

Now you can go to the site in your web browser.  You’ll see your existing site running in SharePoint 2010 mode along with a banner prompting to start the site collection upgrade process.

UpgradeSharePoint2010Mode

You can start the upgrade process right there in the browser, but we want to use PowerShell.   We can see the upgrade status of our site collections using Get-SPSite.  This cmdlet has been updated to show you the current version (ComaptibilityLevel) of the site collection.  A value of 14 represents SharePoint 2010 while a value of 15 represents SharePoint 2013.

Get-SPSite
PowerShellGetSPSite
To upgrade a site collection, test it out first using Test-SPSite.  Like Test-SPContentDatabase, this command can help you identify any particular issues.  In my case, I am going to upgrade my root site collection.

Test-SPSite http://server/sitecollection
PowerShellTestSPSite

SharePoint 2013 has a new concept for the upgrade evaluation site collection.  Effectively this process schedules a job to copy your site collection, upgrade it, and then optionally notify you (if you add the –email parameter).  You don’t have to use this, but it’s a good way to test things out if you have a tricky site with a lot of customizations.

Request-SPUpgradeEvaluationSite http://server/sitecollection
Executing the command simply returns you to a command prompt.  Later a job will fire off and create the upgrade evaluation site collection.  This appears to be controlled by the Create Upgrade Evaluation Site Collections job.  It only executes once a day so if you want to get your upgrade evaluation site faster, you can go manually run it.  After it completes, you can visit your site by appending –eval to your site collection name (i.e.: http://server/sitecollection-eval).  When you visit the site you’ll notice the warning bar at the top telling users that this is only temporary.  After 30 days or so the site will get deleted automatically.

UpgradeEvaluationSiteCollection

As you see I have an error in a web part that I need to correct.  This is why upgrade site collections can be useful in finding issues before cutting over.
Let’s upgrade out site collection directly now.  I only received warnings from Test-SPSite so I am going to proceed with the upgrade and assume everything is going to work fine. :)  We use Upgrade-SPSite to make this happen.  Pass the URL to the site collection and be sure and include –VersionUpgrade.  It won’t upgrade to the new version if you leave off that parameter.

Upgrade-SPSite http://server/sitecollection –VersionUpgrade
PowerShellUpgradeSPSiteInProgress

Depending on the size of your site collection, it may take some time.  When it finishes, you’ll see something similar to the screen below.

PowerShellUpgradeSPSiteComplete

Now, we can visit our upgraded site in the browser.
UpgradedSiteCollection

Site Collections Upgrades are a powerful new feature in SharePoint 2013 which I believe will really make the process smoother.  Keep in mind, you can also use the new Copy-SPSite cmdlet to make a copy of your site collection and perform some tests there.

Wednesday, May 20, 2015

Error in Sharepoint 2013 ,To follow documents or sites, we need to get a couple of things set up. This can take a few minutes to complete, and once it's done, you'll need to come back to this site and try following again

I have faced error when i tried to follow document by using AD Account

"To follow documents or sites, we need to get a couple of things set up. This can take a few minutes to complete, and once it's done, you'll need to come back to this site and try following again"

I have investigated about this issue and resolved by following steps

The first thing in ULS Log I noted was:
<date/time> w3wp.exe (0x2668)    0x1A80    SharePoint Portal Server    Personal Site Instantiation    af1lc    High    Skipping creation of personal site from MySitePersonalSiteUpgradeOnNavigationWebPart::CreatePersonalSite() because one or more of the creation criteria has not been met. [SPWeb Url=http://my/Person.aspx?accountname=CONTOSO\user5]  http://my/Person.aspx?accountname=CONTOSO\user5]Self-Service Site Creation == False  Can Create Personal Site == True  Is user licensed == True  Storage&Social UPA Permission == True  Site or Page or Web Part is in design mode == False      c7d7de9b-bf6b-1084-5706-a8b8f278e6c3

So I have enabled Self-Service Site Creation ==True   in Web Application level click Self Service Site Creation and enabled the property Self Site Creation property
Second issue happens for the user whose value personal site capabilities shows “0” and in order to have feeds and other featured working we need the value as “14” by doing i am able to solve issue.


 

Newsfeed Error - A Required SharePoint Feature is not enabled in SharePoint 2013

There was a recent issue when a User clicks on the newsfeed there is nothing there, when they switch from following to everyone they following error is displayed and also when user click on about me
"SharePoint returned the following error: A required SharePoint feature is not enabled. Internal type name: Microsoft.Office.Server.Microfeed.MicrofeedException. Internal error code: 46. Contact your system administrator for help in resolving this problem."
When I go to "about me" it still states "We're almost ready" underneath my Bio, and if I goto tasks "something went wrong" when it tries to load the page
The errors I still see are as follows
in the Application Log:
This appears intermitantly
"The Execute method of job definition Microsoft.Office.Server.UserProfiles.LMTRepopulationJob (ID 8e2b6939-813f-4798-b473-37b891a4ad2d) threw an exception. More information is included below.
Unexpected exception in FeedCacheService.IsRepopulationNeeded: Connection to the server terminated,check if the cache host(s) is running ."

Resolution:
Issue happens for the user whose value personal site capabilities shows “0” and in order to have feeds and other featured working we need the value as “14”
To fix the issue we need to follow either of  below action plan.
1) This can be done - user profile service application - mange user profiles -> search for the user -> look for personal site capabilities and update the value to 14 and save it.
or
2) I have a PowerShell which can help us to update affected users values form 0 to 14.
#Set up default variables
#My Site URL
$mySiteUrl = "http://spf1/my/"
#The part of the picture URL you are trying to find
$currentValue = "0"
#The value that will replace the above
$newValue = "14"
#The internal name for Property
$upAttribute = "SPS-PersonalSiteCapabilities"
#Get site objects and connect to User Profile Manager service
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$profiles = $profileManager.GetEnumerator()
foreach ($userProfile in $profiles)
{
if ($userProfile[$upAttribute].toString() -ne 14 )
{
if ($userProfile.AccountName -like "i:0#.f|ldapmember|achavda")
    {
                         $newvalue = $userProfile[$upAttribute].toString()
             $newvalue = $newvalue.Replace($currentURLValue, $newURLValue)
              $userProfile[$upAttribute].Value = $newvalue
             $userProfile.Commit()
            }
}
}