Thursday, December 22, 2011

PowerShell - Set-SPCustomLayoutsPage to change the custom error page.

Goal

SharePoint site contains many out of the box Page layouts doing some important tasks. The list is mentioned below. Our goal is to change the Error page and point it to our custom ones. There are many help available on internet for this task but they are missing one thing in most of the blogs. The most important task is to recycle to IIS Application Pool after running the Set-SPCustomLayoutsPage. In this blog I have tried and kept a whole working example for the new comers to change the path and recycle IIS Application Pool using PowerShell.

  • AccessDenied (/_layouts/AccessDenied.aspx)
  • Confirmation (/_layouts/Confirmation.aspx)
  • Error (/_layouts/Error.aspx)
  • Login (/_layouts/Login.aspx)
  • RequestAccess (/_layouts/ReqAcc.aspx)
  • Signout (/_layouts/SignOut.aspx)
  • WebDeleted (/_layouts/WebDeleted.aspx)

Custom Error Page

Create a page "MySiteCustomError.aspx" on "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\" location. Paste the below given code.Use the below given body.
<html>
    <head>Error</head>
    <body>Page Not found</body>
</html>

Powershell

Create a PowerShell script with any "MySiteCustomError.ps1".
#MySiteCustomError.aspx - Custom error Page
#Error.aspx - Default error Page

write-host "Setup the custom Error Page"
Set-SPCustomLayoutsPage -Identity "Error" -RelativePath "/_layouts/MySiteCustomError.aspx" -WebApplication "http://sp2010:50000/"

# Function for recycling
[void][Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration")
function RecycleAppPools()
{
        $serv = new-object Microsoft.Web.Administration.ServerManager
 
        $serv.ApplicationPools | ? { $_.Name -like "SharePoint - 50000" } | % { $_.Recycle() }
}

write-host "Recycle the IIS"
RecycleAppPools

write-host "Script Completed!"


Test Case

  1. My Site > My Content > Blog
  2. I went to a blog and just changed an ID in querystring to a blog which was not there "http://sp2010:50000/personal/administrator/Blog/Lists/Posts/Post.aspx?ID=3". You can see the error which will pop up. This is the default error page in layouts.
  3. Run my "MySiteCustomError.ps1" in "Sharepoint 2010 Management Shell".(Note : Please change the URL and the Application Pool Name before running the script.)
  4. Refresh the "http://sp2010:50000/personal/administrator/Blog/Lists/Posts/Post.aspx?ID=3" and you can see the picture given below.

Hope this was much simpler and easier. Please leave me a message if you need any help.

Monday, November 21, 2011

Sharepoint 2010 - Get Current User's sharepoint group information using javascript.

Goal

To retrieve the SharePoint Group information of Current User logged in using Javascript.

Solution

  1. Dowload the "jquery.SPServices-0.6.2.js" file from CodePlex. Save the file somewhere. I save it in "Style Library".
  2. Use the below given script to get the list of SharePoint Group using javascript.
<!--http://www.jquery.com-->
<script>    !window.jQuery && document.write('<script src="http://code.jquery.com/jquery-1.4.2.min.js"><\/script>');</script>
<!--http://spservices.codeplex.com/releases/view/64390-->
<script language="javascript" tye="text/javascript" src="/style library/jquery.SPServices-0.6.2.js"></script>
<!--Custom Script-->
<script language="javascript" tye="text/javascript">
    $(document).ready(function () {

        $().SPServices({
            operation: "GetGroupCollectionFromUser",
            userLoginName: $().SPServices.SPGetCurrentUser(),
            async: false,
            completefunc: function (xData, Status) {
                //Shows the XML returned from the server
                alert(xData.responseXML.xml);
                //Replace the "<<SHAREPOINT GROUP NAME>>" with your group name will tell that user is on a particular group or not.
                if ($(xData.responseXML).find("Group[Name='<<SHAREPOINT GROUP NAME>>']").length == 1) {
                    alert('User in a group');
                }
            }

        });

    });
</script>
This should be it. Happy Coding.

Saturday, November 12, 2011

JQuery - Destroy the cookies on browser close.

Challenge

Trying to destroy the cookies once the browser is closed. I tried a lot to find on internet doing that same thing using C# but finally i figured out using JQuery.



Solution

Please try the below given block to make this work. I found this on internet somewhere i forgot the place so using this same block.
<html>
<head>
    <title>Starting Cookie Page</title>
    <script type="text/javascript">
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }
    </script>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body onload="
$(document).ready(function() {alert('loaded');});">
    <p>
        <button onclick='createCookie("ccSiteVisited", "1", "");'>
            Create Cookie</button>
        <button onclick='alert(readCookie("ccSiteVisited"));'>
            Read Cookie</button>
        <button onclick='eraseCookie("ccSiteVisited");'>
            Erase Cookie</button>
    </p>
    <p>
        Please note that once you set the cookie, that the cookie is maintained in all further
        browser instances you start.</p>
    <p>
        However, if you close all IE browsers and revisit page, you will see that cookie
        is NOT maintained.</p>
</body>
</html>

Friday, November 4, 2011

SharePoint 2010 - Get My Personal Site URL and all other settings programmatically.

Summary

Guys, I found out a good way to retrieve the My Site > My Content(Personal Site) url using C#.

Solution

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    //Trying to get the Personal Site link or Url
    //SPContext.Current.Site = http://sp2010/
    //_url = http://sp2010:50000/personal/administrator/
                
    //The main site.
    SPSite _site = SPContext.Current.Site;
                
    //Gets the service context of the site.
    SPServiceContext _serviceContext = SPServiceContext.GetContext(_site);
                
    //On the basis of Service Manager 
    UserProfileManager _userProfileManager = new UserProfileManager(_serviceContext);
               
    //Get the User profile from User Profile Manager
    //True is passed in the constructor to create a My Site User Profile if it doesnot exists.
    UserProfile _userProfile = _userProfileManager.GetUserProfile(true);

    //Check if the Personal Site exists
    if (_userProfile.PersonalSite != null)
    {
        //This should give the link in the my site                   
        string _url = _userProfile.PersonalUrl.OriginalString;
    }
    else
    {
        //My Content(Personal Site) Does Exists
    }
});

Hope this helps someone facing issue to find a piece of code to get the url. The same way we can use _userProfile to get all the many other My Site Settings.

Tuesday, November 1, 2011

SharePoint 2010 - Use custom ItemStyle settings in Content Query Web Part.

Friends, I know many might find it easy to use the Custom Item Style for a Content Query Web Part. But, still I will try and explain a small process in a simplified way. Let's see if this is helpful for the starters.

Goal

The main goal is to use a Custom List name "Sample" and use a Content Query Web Part to show it with custom design style.

Process

  1. Create a custom list with name "Sample". The should just have 3 fields.
    1. Title - This is the main text to be shown for the picture.
    2. Picture - This is the hyperlink column for the picture of the item.
    3. Skills - This is a simple multiple line comment for the item.
  2. Go to any page. Add a web part. Drop a Content Query Web Part(CQWP) on the page from "Content Rollup".
  3. Click "Open tool pane".
  4. Content Query Tool Part > Query > Source > Show items from the following list: > Select "SAMPLE"
  5. Content Query Tool Part > Query > Presentation > Please see the picture as a default setting. I am going to leave it as it is.
  6. Click "Save" and the view of the web part will be a default text one which is going to look like picture below.
  7. On Clicking the picture it goes to the display record screen.

But now moving back to our goal. We need to show the data in a custom design layout. So follow the below given steps.
  1. Open a SharePoint 2010 designer.
  2. All Files > Style Library > XSL Style Sheets > ItemStyle.xsl(Edit it in advance mode)
  3. Find this element, copy it and paste it at the bottom of the XSL.
    <xsl:template name="Default" match="*" mode="itemstyle">...</xsl:template>
  4. Change the name and match to Sample.
    <xsl:template name="Sample" match="Row[@Style='Sample']" mode="itemstyle">...</xsl:template>
  5. Also if you edit the web part you can now see the item in the ItemStyle list. Make changes to map the correct fields too.

  6. Make the changes to the xsl(As you want the view of the list) or can copy the whole block and paste it at the bottom of the ItemStyle.xsl.
    <xsl:template name="Sample" match="Row[@Style='Sample']" mode="itemstyle">
            <xsl:variable name="SafeLinkUrl">
                <xsl:call-template name="OuterTemplate.GetSafeLink">
                    <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <xsl:variable name="SafeImageUrl">
                <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
                    <xsl:with-param name="UrlColumnName" select="'ImageUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <xsl:variable name="DisplayTitle">
                <xsl:call-template name="OuterTemplate.GetTitle">
                    <xsl:with-param name="Title" select="@Title"/>
                    <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <table cellpadding="0" cellspacing="5" border="0" style="border:1px Solid #efefef;width:400px;">
                <tr>
                    <td style="width:100px" align="center">
                        <a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
                            <img class="image" src="{$SafeImageUrl}" title="{@ImageUrlAltText}" />
                        </a>
                    </td>
                    <td valign="top" align="left"><a href="{$SafeLinkUrl}" title="{@LinkToolTip}">
                      <xsl:if test="$ItemsHaveStreams = 'True'">
                        <xsl:attribute name="onclick">
                          <xsl:value-of select="@OnClickForWebRendering"/>
                        </xsl:attribute>
                      </xsl:if>
                      <xsl:if test="$ItemsHaveStreams != 'True' and @OpenInNewWindow = 'True'">
                        <xsl:attribute name="onclick">
                          <xsl:value-of disable-output-escaping="yes" select="$OnClickTargetAttribute"/>
                        </xsl:attribute>
                      </xsl:if>
                      <xsl:value-of select="$DisplayTitle"/>
                    </a><br /><xsl:value-of select="@Description" disable-output-escaping="yes" /></td>
                </tr>
            </table> 
        </xsl:template>
    
  7. Once you are done with that you can see the below given view on the screen.
  8. Thats it.


I have tried my best to keep this as simple as possible for freshers who are learning SharePoint.

Thursday, October 13, 2011

SharePoint 2010 - SharePoint Page unable to save the "Publishing Content" changes in Version History.

Problem
I was facing a strange issue with custom "Page". Each and every page layout i was using having a "Page Content" control to enter some text. Here is visual as well as HTML of the control I am talking about.

HTML
<PublishingWebControls:RichHtmlField FieldName="PublishingPageContent" runat="server"/>
Visual
  • I added a new page to my SharePoint Site.
  • Assigned a custom "Page Layout".
  • My Page Layout contains the "Page Content" control. I made some changes to the text "Test".
  • Check In the page.
  • I want to edit the page again, changed the text to "Test - This is a change".
  • Check In the page.
  • Now in the "Page" tab on the top click "Page History".
  • You can find out the versions on the left side. 0.1 and 0.2. Please have a look at the image below.
  • There is no history shown. If you try the same thing with a "Out Of the Box" Page Layouts like Article Page, Enterprise wiki page it will work.


Catch
The publishing content type "Page" was missing column "Page Content". Because if you see in the properties above FieldName="PublishingPageContent"(This is a static name of "Page Content" column) was there in the HTML, but was not as columns in "Page", so history was not getting saved.


Manual Solution
  • Site Actions
  • Site Settings
  • Site Content Types
  • Publishing Content Types
  • Click "Page"
  • Add from existing site columns
  • Select and Add a "Page Content"
  • Save
Programmatic Solution
Create a Visual Studio Project. Create a "Site level Feature". Add a feature receiver. Use below given code. Call the function from Feature_Activation. It will add the "Page Content" if missing.
/// <summary>
/// Add Page Content To Content Type Page for a Publishing Site.
/// </summary>
/// <param name="_properties"></param>
private void AddPageContentToContentTypPage(SPFeatureReceiverProperties _properties)
{
    using (SPWeb _web = ((SPSite)_properties.Feature.Parent).RootWeb)
    {

        //Retrieve the content type
        SPContentType _contentType = _web.ContentTypes["Page"];

        if (_contentType != null)
        {
            if (!_contentType.Fields.ContainsFieldWithStaticName("PublishingPageContent"))
            {
                SPField _field = _web.AvailableFields["Page Content"];
                SPFieldLink _fieldText = new SPFieldLink(_field);

                if (_contentType.FieldLinks[_fieldText.Id] == null)
                {
                    _contentType.FieldLinks.Add(_fieldText);
                }
                _contentType.Update(true);
            }
        }
    }
}

Final Result
Once you are done with this. Please follow the steps mentioned above and you can see the result below.



Hope this helps.

Saturday, October 8, 2011

SharePoint 2010 - Set the default Page Layout programmatically.

Goal - To set "CustomDefaultPageLayout.aspx" as the default page layout, so the next time when some one creates a "New Page" our custom page layout is applied to the page and not system's.


Follow the below given steps to achieve the goal.

  • First of all make sure that the site we have to apply the page layout is a "Publishing Site."
  • Create a Visual Studio Empty Project.
  • Add a Feature Receiver
  • Add new reference of "Microsoft.SharePoint.Publishing".
  • Apply this on the top of the class.
    using Microsoft.SharePoint.Publishing;
    using System.Linq;
  • On feature activation use the below given code.
    private void SetDefaultPageLayout(SPWeb _web)
    {
        PublishingWeb _pubWeb = PublishingWeb.GetPublishingWeb(_web);
        if (_pubWeb != null)
        {
            PageLayout _pageLayout = (from _pl in _pubWeb.GetAvailablePageLayouts()
                                        where _pl.Name == "CustomDefaultPageLayout.aspx"
                                        select _pl).FirstOrDefault();
            _pubWeb.SetDefaultPageLayout(_pageLayout, true);
            _pubWeb.Update();
        }
    }
  • Call the function "SetDefaultPageLayout" from the Feature Activation event.

SharePoint 2010 - Apply a Page Layout to an ASPX page using ELEMENT.xml

Goal
To deploy an ASPX page using Module in Visual Studio project. The web part should be deployed with a PageLayout applied to it. Else a page is going to be created without a page layout attached. The name of the page is "Sample.aspx" and PageLayout is "DefaultPageLayout.aspx". "GSM" is the name of our module.

  • Open Visual Studio 2010.
  • File > New > Sharepoint > Empty Sharepoint Project > Name it "Sample"
  • Right click project > Add a Module > Name "Something".
  • Remove Sample.txt. Add a file(Sample.aspx) to the module.
  • Make the below given changes to the "Element.xml".
  • Right click project and deploy.
  • Visit your website.
  • Site Actions > Edit Site
  • Click "Add a Web Part". On the top ribbon.

You should now be able to see the page with page layout applied to it.

Change in Element.xml


<?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Module Name="GSM" Url="Pages">
        <File Path="GSM\Sample.aspx" Url="Sample.aspx" Type="GhostableInLibrary">
            <Property Name="Title" Value="Sample Title"/>
            <Property Name="PublishingPageLayout" Value="~SiteCollection/_catalogs/masterpage/DefaultPageLayout.aspx, Default Page Layout"/>
        </File>
      </Module>
    </Elements>


Hope this is helpfull for you!

Sharepoint - Troubleshooting a page with "?contents=1"

Guys, I found out something which is really cool. I was working on a custom web part. I added that web part on a page "Test.aspx". One of the web part was having an error "Object Reference...". There was no SharePoint Designer installed in my machine and now i was confused, how can i remove that web part so that at least the page show up? I found out that from a friend that if we just use "?contents=1" in the querystring we can get the list of web parts and can remove the web part directly.


This "?contents=1" also show the web parts which were added to page in past. Go through the below given images to have an idea what i am trying to explain.


  • Here you can see a page with 4 web parts added to it.
    1. Quick Clicks - This is my custom webpart. This webpart contains an error which blocks the whole page to load.
    2. Image Viewer - OOTB web part.
    3. XML Viewer - OOTB web part.
    4. Content Query - OOTB web part.
  • When I clicked "Save & Close" from the top ribbon. The page bombs out giving the error mentioned below.
  • Now as i mentioned above i used "?contents=1" and it showed me the list of all the web parts for this page.
  • In the above image "Custom Web Part" was added to the page but was deleted, still it shows up in the history.
Please let me know if there are any queries.

Tuesday, September 27, 2011

Sharepoint 2010 Adding a "Publishing Image" to a Sharepoint List programmatically.

What is "Publishing Image" content type?

"Publishing Image" is a content type which will bind the image with all its properties and will show it on the screen with those properties applied. The properties like height width etc.


What my task was?

My task was to add a "Publishing Image" content type with Display Name as "Rollup Image" in the content type list "Post". This was a site level feature, once i activate this feature all the blog type site with SharePoint List "Post" will have an extra field "Rollup Image". Please have a look at the 2 pictures which can give you a clear idea.


The 1st from the above one is new post screen. and the 2nd one comes when you click to add a new image reference.


Solution

  1. Open a visual studio 2010
  2. Add new project
  3. Empty Sharepoint Project > Deploy as Farm Solution > Finish.
  4. In the visual studio solution project select "Features > Feature1 > Feature1.feature".
  5. Right click "Add event receiver".
  6. I used this code to achieve it.

    /// <summary>
    /// Add a field name "Rollup Image" to a content type "Post".
    /// "Post" is the content type used in the Site Template blog.
    /// </summary>
    /// <param name="properties"></param>
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (SPWeb _web = ((SPSite)properties.Feature.Parent).RootWeb)
            {
                //Post is the content type list which is on the blogs.
                SPContentType _contentType = _web.ContentTypes["Post"];
    
                if (_contentType != null)
                {
                    //PublishingRollupImage is the static name for the "Publishing Image "
                    if (!_contentType.Fields.ContainsFieldWithStaticName("PublishingRollupImage"))
                    {
                        //Name of the column to be added to the list content type post
                        SPField _field = _web.AvailableFields["Rollup Image"];
                        SPFieldLink _fieldText = new SPFieldLink(_field);
    
                        if (_contentType.FieldLinks[_fieldText.Id] == null)
                        {
                            _contentType.FieldLinks.Add(_fieldText);
                        }
                        _contentType.Update(true);
                    }
                }
            }
        });
    }
  7. Deploy the solution.




How to verify this?

  1. Open the Sharepoint Site.
  2. Site Actions > Site Settings > Site Content Types
  3. Click "Post" in "List Content Type".
  4. You can see the newly added column in the image below. For checking the above 2 images you should go to the "Post" sharepoint list in the blog site.



Please feel free to ask question, I will be more glad to answer your question.

Sharepoint 2010 Enabling "Target Audience" programmatically for Sharepoint List

In this blog i have tried and explained how enable the "Target Audience" using C# for a list. But first I will show you how to enable manually.


Why do we have to enable "Target Audience" field?

To filter the data using audience in Content Query Web Part we have to enable this feature.



Manually

  1. Go to Sharepoint Site
  2. Site Actions > View All Site Content
  3. Select the SharePoint List you want to enable target audience.
  4. List Settings > Audience targeting settings
  5. Select the check box and save.
  6. This will add a field name "Target Audience" in the list.
  7. You can now give Item level target audience.

Programmatically

  1. In the event receiver where you are creating a Sharepoint List.
  2. Just use the code given below.
    #region Enable Target Audience
    
    XmlElement _fldElement = new XmlDocument().CreateElement("Field");
    _fldElement.SetAttribute("ID", "{61cbb965-1e04-4273-b658-eedaa662f48d}");
    _fldElement.SetAttribute("Type", "TargetTo");
    _fldElement.SetAttribute("Name", "Target_x0020_Audiences");
    _fldElement.SetAttribute("StaticName", "Target_x0020_Audiences");
    _fldElement.SetAttribute("DisplayName", "Target Audiences");
    _fldElement.SetAttribute("Required", "FALSE");
    _list.Fields.AddFieldAsXml(_fldElement.OuterXml);
    
    _list.Update();
    
    #endregion
  3. That should be it. See to the list if that column is there!

Thank you and hoping the blog helped you.

Monday, September 26, 2011

Sharepoint 2010 Master page issue with re-deployment with new changes from Visual Studio solution

PROBLEM :- There is a problem with the current process. For the first time this will work but if you make any changes to the master page and re-deploy the same solution will not deploy this new master page with the changes on the server.


In my last post "SharePoint 2010 Deploy Master Page using Visual Studio Solution Project and Set it as Default Master Page.", i explained how to add a master page and set it as a default. I suggest to read the last blog first.


What causes the issue?

Answer: When a file is deployed to the server using a Visual Studio Solution, the file gets deleted first and than added back to server. But when we assign a file as a Default Master Page it "CANNOT" be deleted. So just follow the below given steps to make it a fix.

Solution

Just write a deactivating event in the feature receiver setting V4.master as a master page. Please checkout the code below.


/// <summary>
/// Set the v4.master as default master for site.
/// </summary>
/// <param name="properties"></param>
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
        using (SPWeb _web = ((SPSite)properties.Feature.Parent).RootWeb)
        {
            Uri _siteMaster = new Uri(string.Format("{0}/_catalogs/masterpage/v4.master", _web.Url));
            _web.MasterUrl = _siteMaster.AbsolutePath;
            _web.CustomMasterUrl = _siteMaster.AbsolutePath;
            _web.Update();
        }
    });
}
Hope this was helpful to you. Thanks for reading the blog.

SharePoint 2010 Deploy Master Page using Visual Studio Solution Project and Set it as Default Master Page.

This blog will give an understanding of how to add a master page using a Visual Studio solution project. Also setting the same master as a default for site.


STEP 1 : Adding a Master Page using Module

  1. Open a visual studio 2010
  2. Add new project
  3. Empty Sharepoint Project > Deploy as Farm Solution > Finish.
  4. Add New Item > Select "Module" > I named it as "MasterPage".
  5. Delete the "Sample.txt" which gets added in the module by default.
  6. Add new MainMasterPage.master. Do whatever change you want to it.
  7. Open the elements.xml file of "MasterPage" module. You will have to make some modification shown below.


    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
        <Module Name="MasterPage" List="116" Url="_catalogs/masterpage">
            <File Path="MasterPage\MainMasterPage.master" Url="MainMasterPage.master" Type="GhostableInLibrary">
                <Property Type="string" Name="Title" Value="My Main Master Page"/>
            </File>
      </Module>
    </Elements>
  8. Please verify the below given text i made change in the original one. This is MOST IMPORTANT!!!.
    List="116" Url="_catalogs/masterpage"
    Url="MainMasterPage.master" Type="GhostableInLibrary"
  9. Once this is set just deploy the project.

STEP 1.1 : Verify the file got uploaded

  1. Open the site in SharePoint Designer 2010.
  2. All Files > _catalogs > MasterPage
  3. The file should be at this location because if you see the element.xml above in the url we have given the path of "_catalogs/masterpage". That's it we now achieved the first step of adding a master file to the site.


STEP 2 : Apply the page as a default master page

  1. In the visual studio solution project select "Features > Feature1 > Feature1.feature".
  2. Right click "Add event receiver".
  3. Put this code.

    /// <summary>
    /// Set the MainMasterPage.master as default master for site.
    /// </summary>
    /// <param name="properties"></param>
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (SPWeb _web = ((SPSite)properties.Feature.Parent).RootWeb)
            {
                Uri _siteMaster = new Uri(string.Format("{0}/_catalogs/masterpage/MainMasterPage.master", _web.Url));
                _web.MasterUrl = _siteMaster.AbsolutePath;
                _web.CustomMasterUrl = _siteMaster.AbsolutePath;
                _web.Update();                   
            }
        });
    }
  4. Right click the project and deploy the solution.

I hope this helps you with the deployment of master page and setting it as a default.

PROBLEM :- There is a problem with the current process. For the first time this will work but if you make any changes to the master page and re-deploy the same solution will not deploy this new master page with the changes on the server. Please read my next blog "Sharepoint 2010 Master page issue with re-deployment with new changes from Visual Studio solution" for the solution.

Wednesday, August 31, 2011

"User Information List" instead of "UserProfileManager"

For all those friends who were trying to find out an option for "UserProfileManger" to get the information of user, I found "User Information List" on the root. I am still not sure if it gets sync directly to the active directory or any other user list. But will write a blog on this in future once i find it.

Tuesday, August 30, 2011

Sharepoint 2010 deploy .webpart file Custom Group instead of Miscellaneous.

Goal
To deploy a web part using Module in Visual Studio project. The webpart should be deployed in group custom name "MBD Web Parts" and not in "Miscellaneous".

  • Open Visual Studio 2010.

  • File > New > Sharepoint > Empty Sharepoint Project > Name it "Sample"

  • Right click project > Add a Module > Name "Something".

  • Remove Sample.txt. Add a file(DemoWebPart.webpart) to the module.

  • Make the below given changes to the "Element.xml".

  • Right click project and deploy.

  • Visit your website.

  • Site Actions > Edit Site

  • Click "Add a Web Part". On the top ribbon.


You should now be able to see webpart in "MBD Web Parts" and not in "Miscellaneous".

Change in Element.xml



<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module List="113" Name="Something" Url="_catalogs/wp">
<File Path="Something\DemoWebPart.webpart" Url="DemoWebPart.webpart" Type="GhostableInLibrary">
<Property Name="Group" Value="MBD Web Parts" />
</File>
</Module>
</Elements>


Hope this is helpfull for you!

Sharepoint 2010 Deploy visual web part to "MBD Web Parts" instead of "Custom".

Goal
To deploy our custom visual webpart to a custom group name "MBD Web Parts" instead of getting deployed to "Custom". Please follow below given steps to see how to reproduce.

  • Open Visual Studio 2010.

  • File > New > Sharepoint > Visual Web Part > Name it "Sample"

  • Delete the "VisualWebPart1"(Default) and add a new Visual Web Part file "DemoWebPart".

  • Complete writing code.

  • Right click project and deploy.

  • Visit your website.

  • Site Actions > Edit Site

  • Click "Add a Web Part". On the top ribbon.


This will show up our web part in the Group name "Custom", but we need to the web part in a group name "MBD Web Parts".

Simple Solution


  • Expand "DemoWebPart" and open "Element.xml".

  • Modify an attribute value in the xml from "Custom" to "MBD Web Parts".

  • Right click project and deploy.

  • Visit your website.

  • Site Actions > Edit Site

  • Click "Add a Web Part". On the top ribbon.


You should now be able to see our custom category of "MBD Web Parts" and not in "Custom".

Change in Element.xml


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
<Module Name="DemoWebPart" List="113" Url="_catalogs/wp" RootWebOnly="TRUE">
<File Path="DemoWebPart\DemoWebPart.webpart" Url="DemoWebPart.webpart" Type="GhostableInLibrary" >
<Property Name="Group" Value="MBD Web Parts" />
</File>
</Module>
</Elements>



Hope this is helpfull for you!

Problem creating or deleting Sharepoint List in Visual Web Part's Feature Receiver when called from stsadm or powershell.

Summary of Issue.

Working Process
In a Visual Studio Web Part, I was trying to create a Sharepoint List using a Feature Receiver Event. Every thing works fine when I deployed the solution using Visual Studio 2010.

Problem
I tried deploying the solution using STSADM Command or Powershell scripts. The deployment went fine but the Sharepoint List was not getting created. After research I found out the issue was in the activation code. I was using SPContext.Current.Web.Url. Now the correct way to do this is mentioned below.


If the Feature Scope="Web"


public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPWeb _web = (SPWeb)properties.Feature.Parent;
});
}



If the Feature Scope="Site"


public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPSite _site = (SPSite)properties.Feature.Parent;
});
}



Hope you find this helpfull. Please comment if you have any queries.

Wednesday, June 15, 2011

Sharepoint LookUp field issue when created using List Template


Usually when we create a list using a "List Template". The lookup field doesnot take the reference. The blog will show you how to reproduce the issue and resolve it.


How to produce this issue.



  • We have created 2 lists "Gender" and "Actors". Gender is going to be a lookup field in actors. After filling some data both the list will look like shown below.



  • Save both list as a template with the content included. In this current example, i have given the names as "Template Gender" and "Tempate Actors".

  • Download the stp files from the Site Settings > List Templates.

    • Create another site. Upload the tempates Site Settings > List Templates.

    • If you don't want to create another site than delete both list from current site.



  • Once the template gets added. Use the template to create a list. In the below given images "Gender" List comes up fine but "Actors" List is not having anything in the "Gender" column field.


Solution



  • Download the "Template-Actors.stp" file from "List Templates".

  • Rename the file and change the extension of the file from ".stp" to ".cab".

  • Once you have the extension as ".cab", extract the "Manifast.xml" file.

  • Get the List ID of newly created "Gender".

  • Replace the old value List Id in Lookup of Gender to New List ID

    • Old

    • New



  • After making the changes save the xml file.

  • To recreate a CAB file open "Microsoft Visual Studio". Create a "CAB Project". In this case i have created "Template-Actors".(We can also use makecab.exe instead of visual studio.)

  • Add the file Manifast.xml to the project.

  • Build the cab project. Go to debug\bin folder you will find "Template-Actors.cab".

  • Rename the file to "Template-Actors.stp".

  • Upload the file to "List Template".

  • Create a list using new template.

  • The gender selections will now show up.


Monday, June 13, 2011

Sharepoint 2010 Customize Paging in XSLTListViewWebPart

The blog explains to add paging to our XSLTListViewWebPart in Sharepoint 2010.

  1. Create a customized html by going through one of my last blog. Click here to read my last blog.
  2. Once you have the html. There are few small things you need to keep in mind.
    1. Control your page size from the tag given below.
      <RowLimit Paged="TRUE">2</RowLimit>
    2. There are 3 major templates which you need to take care of for the paging. There will be an attribute "ddwrt:ghost="hide"" in all 3 of them. Remove them from it as it wont allow your template to get into shape.
      <xsl:template name="pagingButtons">
      <xsl:template name="CommandFooter">
      <xsl:template name="Navigation">
      
    3. In the template name Naviagtion, You can delete everything for customization, but not "id="bottomPagingCell{$WPQ}"". You will have to assign that to any element.
  3. Call the template from main row.
    <xsl:call-template name="pagingButtons" />
  4. Here are the images with myself customizing the paging.
  5. Have a look at the view what i have created for the custom paging. Below given xsl style is the complete working example for the screenshots above.
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
    version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
    xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:sharepoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal"
    xmlns:o="urn:schemas-microsoft-com:office:office" ddwrt:ghost="show_all">
  <xsl:include href="/_layouts/xsl/main.xsl" />
  <xsl:include href="/_layouts/xsl/internal.xsl" />
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
  <xsl:output method='html' indent='yes' />
  <xsl:template match="/" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
       xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
       xmlns:sharepoint="Microsoft.SharePoint.WebControls" xmlns:o="urn:schemas-microsoft-com:office:office"
       ddwrt:ghost="" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime">
    <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row[$EntityName = '' or (position() &gt;= $FirstRow and position() &lt;= $LastRow)]" />
    <table cellpadding="10" cellspacing="0" border="1" style="padding:25px;">
      <tr>
        <td colspan='2'>
          <b style="font-size:25px;">Friend's List</b>
        </td>
      </tr>
      <xsl:for-each select="$Rows">
        <xsl:call-template name="RowView">
        </xsl:call-template>
      </xsl:for-each>
      <tr>
          <td colspan="2"><xsl:call-template name="pagingButtons" /></td>
      </tr>
    </table>    
  </xsl:template>

  <xsl:template name="RowView">
   <xsl:variable name="thisNode" select="." />
    <tr>
      <td align="center">
        <img style="height:100px;border:5px solid #888;">
          <xsl:attribute name="src">
            <xsl:value-of select="@Picture"></xsl:value-of>
          </xsl:attribute>
          
          <xsl:attribute name="alt">
            <xsl:value-of select="@Title"></xsl:value-of>
          </xsl:attribute>
        
        </img>
      </td>
      <td valign="top">
        <b>Name : </b>
        <xsl:value-of select="@Title"></xsl:value-of>
        <br></br>
        <b>Email : </b>
        <xsl:value-of select="@Email" disable-output-escaping="yes"></xsl:value-of>
        <br></br>
        <b>Address :</b>
        <br></br>
        <blockquote>
          <xsl:value-of select="@Address" disable-output-escaping="yes"></xsl:value-of>
        </blockquote>
      </td>
    </tr>
  </xsl:template>
  
  <xsl:template name="pagingButtons">
    <xsl:choose>
          <xsl:when test="$XmlDefinition/List/@TemplateType = 106 and $XmlDefinition/@RecurrenceRowset='TRUE'">
            <xsl:if test="$dvt_nextpagedata or $dvt_prevpagedata">
                  <xsl:call-template name="CalendarExpandedRecurrenceFooter"/>
        </xsl:if>
      </xsl:when>
          <xsl:otherwise>
              <xsl:if test="$XmlDefinition/RowLimit[@Paged='TRUE']">
                <xsl:call-template name="CommandFooter">
                      <xsl:with-param name="FirstRow" select="$FirstRow" />
                      <xsl:with-param name="LastRow" select="$LastRow" />
                      <xsl:with-param name="dvt_RowCount" select="$dvt_RowCount" />
                </xsl:call-template>
      </xsl:if>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <xsl:template name="CommandFooter">
    <xsl:param name="FirstRow" select="1"/>
    <xsl:param name="LastRow" select="1"/>
    <xsl:param name="dvt_RowCount" select="1"/>
    <xsl:if test="$FirstRow &gt; 1 or $dvt_nextpagedata">
          <xsl:call-template name="Navigation">
            <xsl:with-param name="FirstRow" select="$FirstRow" />
            <xsl:with-param name="LastRow" select="$LastRow" />
            <xsl:with-param name="dvt_RowCount" select="$dvt_RowCount" />
          </xsl:call-template>
    </xsl:if>
  </xsl:template><xsl:template name="Navigation">
    <xsl:param name="FirstRow" select="1"/>
    <xsl:param name="LastRow" select="1"/>
    <xsl:param name="dvt_RowCount" select="1"/>
    <xsl:variable name="LastRowValue">
        <xsl:choose>
            <xsl:when test="$EntityName = '' or $LastRow &lt; $RowTotalCount">
              <xsl:value-of select="$LastRow"/>    
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$RowTotalCount"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:variable name="NextRow">
      <xsl:value-of select="$LastRowValue + 1"/>
    </xsl:variable>
        <table id="bottomPagingCell{$WPQ}" style="font-size:25px;width:100%;padding:5px;" border="0">
            <tr>
                            <td style="width:50%">
                <xsl:if test="$dvt_firstrow &gt; 1">
                  <a>
                    <xsl:choose>
                          <xsl:when test="$dvt_RowCount = 0 and not($NoAJAX)">
                            <xsl:attribute name="onclick">javascript:RefreshPageTo(event, "<xsl:value-of select="$PagePath"/>?<xsl:value-of select="$ShowWebPart"/>\u0026<xsl:value-of select='$FieldSortParam'/><xsl:value-of select='$SortQueryString'/>\u0026View=<xsl:value-of select="$View"/>");javascript:return false;</xsl:attribute>
                            <xsl:attribute name="href">javascript:</xsl:attribute>
                        <img src="/_layouts/{$LCID}/images/prev.gif" border="0" alt="{$Rows/@idRewind}" />
                        <img src="/_layouts/{$LCID}/images/prev.gif" border="0" alt="{$Rows/@idRewind}" />
                      </xsl:when>
                          <xsl:otherwise>
                            <xsl:variable name="RealRowLimit">
                                  <xsl:choose>
                                    <xsl:when test="$XmlDefinition/Query/GroupBy[@Collapse='TRUE']/@GroupLimit">
                              <xsl:value-of select ="$XmlDefinition/Query/GroupBy[@Collapse='TRUE']/@GroupLimit"/>
                            </xsl:when>
                                    <xsl:otherwise>
                              <xsl:value-of select = "$XmlDefinition/RowLimit"/>
                            </xsl:otherwise>
                                  </xsl:choose>
                        </xsl:variable>
                            <xsl:choose>
                                  <xsl:when test="not($NoAJAX)">
                                    <xsl:attribute name="onclick">javascript:RefreshPageTo(event, "<xsl:value-of select="$PagePath"/>?<xsl:value-of select="$dvt_prevpagedata"/><xsl:value-of select="$ShowWebPart"/>\u0026PageFirstRow=<xsl:value-of select="$FirstRow - $RealRowLimit"/>\u0026<xsl:value-of select='$FieldSortParam'/><xsl:value-of select='$SortQueryString'/>\u0026View=<xsl:value-of select="$View"/>");javascript:return false;</xsl:attribute>
                                    <xsl:attribute name="href">javascript:</xsl:attribute>
                          </xsl:when>
                                  <xsl:otherwise>
                                    <xsl:attribute name="href">
                              javascript: <xsl:call-template name="GenFireServerEvent">
                                            <xsl:with-param name="param" select="concat('dvt_firstrow={',$FirstRow - $XmlDefinition/RowLimit,'};dvt_startposition={',$dvt_prevpagedata,'}')"/>
                                          </xsl:call-template>
                            </xsl:attribute>
                          </xsl:otherwise>
                            </xsl:choose>
                        <img src="/_layouts/{$LCID}/images/prev.gif" border="0" alt="{$Rows/@idPrevious}" />Pre
                      </xsl:otherwise>
                    </xsl:choose>
                  </a>
              </xsl:if>
            </td>
            
                 <td style="width:50%" align="right">
                  <xsl:if test="$LastRowValue &lt; $dvt_RowCount or string-length($dvt_nextpagedata)!=0">

                  <a>
                    <xsl:choose>
                          <xsl:when test="not($NoAJAX)">
                            <xsl:attribute name="onclick">javascript:RefreshPageTo(event, "<xsl:value-of select="$PagePath"/>?<xsl:value-of select="$dvt_nextpagedata"/><xsl:value-of select="$ShowWebPart"/>\u0026PageFirstRow=<xsl:value-of select="$NextRow"/>\u0026<xsl:value-of select='$FieldSortParam'/><xsl:value-of select='$SortQueryString'/>\u0026View=<xsl:value-of select="$View"/>");javascript:return false;</xsl:attribute>
                            <xsl:attribute name="href">javascript:</xsl:attribute>
                      </xsl:when>
                          <xsl:otherwise>
                            <xsl:attribute name="href">javascript: <xsl:call-template name="GenFireServerEvent">
                                <xsl:with-param name="param" select="concat('dvt_firstrow={',$NextRow,'};dvt_startposition={',$dvt_nextpagedata,'}')"/>
                                  </xsl:call-template>
                        </xsl:attribute>
                      </xsl:otherwise>
                    </xsl:choose>
                    Next<img src="/_layouts/{$LCID}/images/next.gif" border="0" alt="{$Rows/@tb_nextpage}" />
                  </a>
              </xsl:if>
              </td>
            </tr>            
        </table>
    
    <xsl:if test="not($GroupingRender)">
    <script>
      var topPagingCell = document.getElementById(&quot;topPagingCell<xsl:value-of select="$WPQ" />&quot;);
      var bottomPagingCell = document.getElementById(&quot;bottomPagingCell<xsl:value-of select="$WPQ" />&quot;);
      if (topPagingCell != null &amp;&amp; bottomPagingCell != null)
      {
      topPagingCell.innerHTML = bottomPagingCell.innerHTML;
      }
    </script>
    </xsl:if>
  </xsl:template>
  </xsl:stylesheet>