Showing posts with label Feature Event Receiver. Show all posts
Showing posts with label Feature Event Receiver. Show all posts

Thursday, May 29, 2014

Sharepoint 2010 - Solution to blog URL issue with site using Variations(Multilingual site).

Issue

Read this blog -> Sharepoint 2010 - Strange blog URL issue with site using Variations(Multilingual site). - REALLY WEIRD ISSUE!

Solution

  • Create a Feature Stapler.
  • Set the event scope as Scope="Site" as the feature.
  • Stapler > Element.xml.
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
        <FeatureSiteTemplateAssociation Id="edf698b1-30db-4d19-b46b-5efbb5dae9a5" TemplateName="Blog" />
    </Elements>
  • Please use the below given code as a solution for the problem.
#region System
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Administration;
using System.IO;
using System.Linq;
#endregion

namespace FeatureStapler.VariationBlogSiteEvent
{
    /// <summary>
    /// Web Events
    /// </summary>
    public class VariationBlogSiteEvent : SPWebEventReceiver
    {
        #region Properties

        /// <summary>
        /// The site templates
        /// </summary>
        enum EnmSiteTemplate
        {
            BLOG,    //Blog Site
        }

        /// <summary>
        /// English Language
        /// </summary>
        enum EnmLangugeCode
        {
            English = 1033
        }

        #endregion

        #region Events

        /// <summary>
        /// A site was provisioned.
        /// </summary>
        public override void WebProvisioned(SPWebEventProperties properties)
        {
            base.WebProvisioned(properties);

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    //Create a web object
                    SPWeb _web = properties.Web;

                    //Check and apply the settings
                    if (_web.WebTemplate == EnmSiteTemplate.BLOG.ToString() // If the site is a blog site
                        && _web.Language != (int)EnmLangugeCode.English) // Language Selected is not english
                    {
                        // Get the Library with correct folder
                        SPFolderCollection _folderInList = _web.Folders["Lists"].SubFolders;

                        //Find a folder with "post.aspx" & "newpost.aspx"
                        SPFolder _folderBlogNonEnglish = (from _folderX in _folderInList.Cast<SPFolder>()
                                                          let _fName = _folderX.Name
                                                          let _fCount = (from _fileX in _folderX.Files.Cast<SPFile>()
                                                                 where string.Compare( _fileX.Name , "post.aspx" , true ) == 0
                                                                select _fileX).Count()
                                                          where _fCount > 0
                                                          select _folderX).FirstOrDefault();

                        //So if any folder this properties exists
                        if (_folderBlogNonEnglish != null)
                        {
                            //The folder where file is going to come
                            SPFolder _folderBlogInEnglish = _folderBlogNonEnglish.ParentFolder.SubFolders.Add("Posts");
                            _folderBlogInEnglish.SubFolders.Add("Attachments");
                            _folderBlogInEnglish.SubFolders.Add("Post");

                            //Copy the files to new folder
                            foreach (SPFile _file in _folderBlogNonEnglish.Files)
                            {
                                _file.CopyTo(string.Format("{0}/{1}/{2}", _web.Url, _folderBlogInEnglish.Url, _file.Name), true);
                                ////Add a file
                                //_folderBlogInEnglish.Files.Add(_file.Name, File.OpenRead(_file), true);

                                // Commit 
                                _folderBlogInEnglish.Update();
                            }
                        }                       
                    }

                });
            }
            catch (Exception Exc)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("VariationBlogSiteEvent", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, Exc.Message, Exc.StackTrace);
            }
        }

        #endregion

    }
}



Hope this helps. If you have any questions or a better solution, I am all open for it. Thanks for reading the blog.

Thursday, September 20, 2012

Sharepoint 2010 Error Solution : The Visible property cannot be set on Web Part 'g_XXX'. It can only be set on a standalone Web Part.

Problem

There is an issue with OOTB SharePoint logic.

Scenario

  1. 2 types of Users
    • User1 is Site Administrator
    • User2 is a simple user with Read, Limited Access.
  2. Issue comes under blog site.


How to reproduce? Follow the below given test case.

  1. Create a site collection. In my case I have created it on "http://pc92".
  2. I create a blog site with name "TestBlog" using User1. In my case it is "http://pc92/TestBlog/".
  3. Navigate to default blog created on site and add 11 comments. Right now the URL will be "http://pc92/TestBlog/Lists/Posts/Post.aspx?ID=1". This will enable the paging at the comments webpart.
  4. Now login with User2(Read, Limited Access User) and navigate to the URL "http://pc92/TestBlog/Lists/Posts/Post.aspx?ID=1". The page will show normal. The only difference here is you won't see the "Add Comment" box at the bottom of the screen.
  5. Click the next button. You will see the error.


Cause

The cause of the whole act is when you login as a User2(Read, Limited Access) the Comment Box(ListFormWebPart) is not available for this users. On page load everything is fine. But when you do a postback like paging event it bombs out. This might have got out of the site of MicroSoft Team.

Solution

I created 2 features, one is a site based feature(BlogFixSite) and another one web based feature(BlogFixWeb). On the BlogFixSite activation we check all the web which doesnot have BlogFixWeb activated and the template is a Blog template. So if the feature is activated I assume that the site is already having a fix. In the BlogFixWeb I go to the "Posts" folder and copy "Post.aspx" content and create "Post1.aspx". In the "Post1.aspx" i will remove the "ListFormWebPart" programatically. In "Post.aspx" at the bottom i will place a jquery which will check if the "Add Comment" box is missing than take the user to "Post1.aspx". Repeat the above given test cases and you should be all good.

BlogFixSite - C#

#region System
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using System.Linq;
#endregion

namespace BlogFix.Features.BlogFixSite
{
    [Guid("63c859cc-77ff-436e-a79e-b4619a67c7c3")]
    public class BlogFixSiteEventReceiver : SPFeatureReceiver
    {
        #region Events

        /// <summary>
        /// Activating
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            base.FeatureActivated(properties);

            try
            {
                //Site object
                SPSite _site = (SPSite)properties.Feature.Parent;

                if (_site != null)
                {
                    //Feature ID - BlogFixWeb
                    Guid _featureWeGuid = new Guid("c7178a85-ed45-4f27-bd4a-db2ec3eed95b");

                    //Web List
                    IList<SPWeb> _webList = (from _web in _site.AllWebs.Cast<SPWeb>()
                                             where string.Compare(_web.WebTemplate, "Blog", true) == 0
                                                 && _web.Features[_featureWeGuid] == null
                                             select _web).ToList();

                    //Change the post page
                    foreach (SPWeb _web in _webList)
                    {
                        //Enables the feature - BlogFixWeb
                        if (_web.Features[_featureWeGuid] == null)
                        {
                            _web.Features.Add(_featureWeGuid);
                        }
                    }
                }
            }
            catch (Exception Exc)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BlogFixSiteEventReceiver - Activated", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, Exc.Message, Exc.StackTrace);
            }
        }

        #endregion
    }
}


BlogFixWeb - C#

#region System
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using System.Linq;
#endregion

namespace BlogFix.Features.BlogFixWeb
{
    [Guid("564b0ad9-90a0-45fc-a672-901ec1fd111b")]
    public class BlogFixWebEventReceiver : SPFeatureReceiver
    {
        #region Events

        /// <summary>
        /// Activate the web based feautre
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            base.FeatureActivated(properties);

            try
            {
                SPWeb _web = (SPWeb)properties.Feature.Parent;

                //All the subfolders
                SPFolderCollection _folderCollection = _web.Folders["Lists"].SubFolders;

                //Finds the folder containing Post.aspx
                IList<SPFolder> _folderPostList = (from _folderX in _folderCollection.Cast<SPFolder>()
                                                   let _fName = _folderX.Name
                                                   let _fCount = (from _fileX in _folderX.Files.Cast<SPFile>()
                                                                  where string.Compare(_fileX.Name, "post.aspx", true) == 0
                                                                  select _fileX).Count()
                                                   where _fCount > 0
                                                   select _folderX).ToList();


                //Loop it if there are more than one
                if (_folderPostList != null)
                {
                    foreach (SPFolder _folderPost in _folderPostList)
                    {
                        //Get the Post file
                        SPFile _filePost = (from _fileX in _folderPost.Files.Cast<SPFile>()
                                            where string.Compare(_fileX.Name, "post.aspx", true) == 0
                                            select _fileX).FirstOrDefault();

                        //The file post to be copied
                        if (_filePost != null)
                        {
                            //New Post1.aspx URL
                            string _newPostUrl = string.Format("{0}/{1}/{2}",
                                _web.Url,
                                _folderPost.Url,
                                "Post1.aspx");

                            //Copy the file
                            _filePost.CopyTo(_newPostUrl, true);
                            
                            //Update the folder
                            _folderPost.Update();

                            //Remove the control once the page is copied
                            Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager _webPartCollection = _web.GetLimitedWebPartManager(_newPostUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                            //Retrive the webpart and remove
                            Microsoft.SharePoint.WebPartPages.WebPart _listFormWebPart = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
                                                                                          where _wp.GetType().UnderlyingSystemType.Name == "ListFormWebPart"
                                                                                          select _wp).FirstOrDefault();


                            //Microsoft.SharePoint.WebPartPages.ListFormWebPart _XlistFormWebPart = (Microsoft.SharePoint.WebPartPages.ListFormWebPart)_listFormWebPart;
                            //string _webPartTitle = _XlistFormWebPart.Title
                            //return;

                            if (_listFormWebPart != null)
                            {
                                //Remove the webpart
                                _webPartCollection.DeleteWebPart(_listFormWebPart);

                                //Update
                                _web.Update();
                            }

                            //Modify Post1.aspx and add the javascript tag
                            if (_filePost.RequiresCheckout)
                            {
                                _filePost.CheckOut();
                            }

                            //Edit the file
                            byte[] _htmlByte = _filePost.OpenBinary();
                            string _html = System.Text.Encoding.ASCII.GetString(_htmlByte);
                            string _topHtml = _html.Substring(0, _html.LastIndexOf("</asp:Content>"));
                            string _stript = "\n<script language=\"javascript\" type=\"text/javascript\">!window.jQuery && document.write('<script src=\"http://code.jquery.com/jquery-1.4.2.min.js\"><\\/script>');</script>\n<script language='javascript'>\n\r$(document).ready(function(){\n\r\rif($(\"h3[class='ms-CommentHeader']\").length == 1){\n\r\r\r\rwindow.location.href =     window.location.href.replace(\".aspx?\" , \"1.aspx?\");\n\r\r}\n\r});</script>";
                                

                            _html = string.Format("{0}{1}</asp:Content>", _topHtml, _stript);
                            _filePost.SaveBinary(System.Text.Encoding.ASCII.GetBytes(_html));

                            //Check In
                            if (_filePost.RequiresCheckout)
                            {
                                _filePost.CheckIn(string.Empty);
                            }
                        }
                    }
                }

            }
            catch (Exception Exc)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BlogFixWebEventReceiver - Activated", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, Exc.Message, Exc.StackTrace);
            }
        }

        #endregion
    }
}



JavaScript added on Post.aspx

There are 2 "<h3></h3>" tags on the post.aspx page. (1) is "Comments" and (2) is "Add Comments". So if a user dont have access he/she wont see "Add Comment" box. If that box doesnot exists on the page I simply send the user to Post1.aspx.
<script>    !window.jQuery && document.write('<script src="http://code.jquery.com/jquery-1.4.2.min.js"><\/script>');</script>
<script language='javascript'>
    $(document).ready(function () {
        if ($("h3[class='ms-CommentHeader']").length == 1) {
            window.location.href = window.location.href.replace(".aspx?", "1.aspx?");
        }
    });</script>


Final Comments

To make this feature available for all the webs just create a feature stapler which activates the web based feature just like its done in "BlogFixSite".
I know many people wont agree with my solution but right now it is what it is. Happy Coding. Do let me know if this helped you.

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.

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.

Tuesday, August 30, 2011

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.