Tuesday, May 17, 2016

Custom site page, add to pages library & set as default SharePoint2013 Home/Welcome page


Step1: Add module to the Project, Rename sample.txt as myPage.aspx.

aspx code goes here... change CodeBehind and Inherits once you add Code behind file in step2...

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>

<%@ Page Language="C#" CodeBehind="PageName.aspx.cs" Inherits="ProjectName.ModuleName.PageName, $SharePoint.Project.AssemblyFullName$" MasterPageFile="~masterurl/default.master"      MainContentID="PlaceHolderMain" meta:webpartpageexpansion="full" meta:progid="SharePoint.WebPartPage.Document" %>

<%@ Import Namespace="Microsoft.SharePoint.WebPartPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>






<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
       <SharePoint:ProjectProperty Property="Title" runat="server"/> - <SharePoint:ListItemProperty runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server"><SharePoint:AlphaImage ID=onetidtpweb1 Src="/_layouts/15/images/wiki.png?rev=23" Width=145 Height=54 Alt="" Runat="server"/></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
       <meta name="CollaborationServer" content="SharePoint Team Web Site" />
       <SharePoint:ScriptBlock runat="server">
       var navBarHelpOverrideKey = "WSSEndUser";
       </SharePoint:ScriptBlock>
       <SharePoint:RssLink runat="server"/>
       </asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMiniConsole" runat="server">
       <SharePoint:FormComponent TemplateName="WikiMiniConsole" ControlMode="Display" runat="server" id="WikiMiniConsole"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftActions" runat="server">
       <SharePoint:RecentChangesMenu runat="server" id="RecentChanges"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

    <asp:Label ID="lblmsg" runat="server" ForeColor="Blue"></asp:Label>



       <span id="wikiPageNameDisplay" style="display: none;" runat="server">
              <SharePoint:ListItemProperty runat="server"/>
       </span>
       <span style="display:none;" id="wikiPageNameEdit" runat="server">
              <asp:TextBox id="wikiPageNameEditTextBox" runat="server"/>
       </span>

       <SharePoint:VersionedPlaceHolder UIVersion="4" runat="server">
              <SharePoint:SPRibbonButton
                     id="btnWikiEdit"
                     RibbonCommand="Ribbon.WikiPageTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.Edit"
                     runat="server"
                     Text="edit"/>
              <SharePoint:SPRibbonButton
                     id="btnWikiSave"
                     RibbonCommand="Ribbon.WikiPageTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.SaveAndStop"
                     runat="server"
                     Text="edit"/>
              <SharePoint:SPRibbonButton
                     id="btnWikiRevert"
                     RibbonCommand="Ribbon.WikiPageTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.Revert"
                     runat="server"
                     Text="Revert"/>
       </SharePoint:VersionedPlaceHolder>
      
       <WebPartPages:WebPartZone runat="server" ID="Bottom" CssClass="ms-hide" Title="loc:Bottom"><ZoneTemplate></ZoneTemplate></WebPartPages:WebPartZone>
</asp:Content>

Step2: select the module and add new Item and add a code file.


ð  Add System.web dll
Make a class as a public and inherit from Webpartpage
Ex:  public class MyPage : WebPartPage
Add page load method if you want and to create any control then create a global object.
Ex:           protected Label lblmsg;
        private void Page_Load()
        {
     }

Open the elemnts.aspx


<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="TestModule"  Url="Pages">
    <File Path="ModuleName\MyPage.aspx" Url="MyPage.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" ReplaceContent="TRUE"/>
  </Module>
</Elements>

Add Feature Receiver to set myPage as HomePage.


public static void setMyPageAsWelcomePage(SPWeb webElevated)
        {
            SPFolder pagesFolder = null;

            webElevated.AllowUnsafeUpdates = true;
            if (PublishingWeb.IsPublishingWeb(webElevated))
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(webElevated);
                if (publishingWeb != null)
                {
                    SPFolder rootFolder = webElevated.RootFolder;
                    try
                    {
                        pagesFolder = publishingWeb.PagesList.RootFolder;
                    }
                    catch (Exception ex1) { }

                    try
                    {
                        if (rootFolder != null)
                        {
                            if (pagesFolder != null)
                            {
                                string newWelcomePageUrl = publishingWeb.PagesList.Title + "/" + "MyPage.aspx";
                                rootFolder.WelcomePage = newWelcomePageUrl;

                                if (newWelcomePageUrl.StartsWith(pagesFolder.Url, StringComparison.OrdinalIgnoreCase))
                                {
                                    pagesFolder.WelcomePage = newWelcomePageUrl.Substring(publishingWeb.PagesList.RootFolder.Url.Length + 1);
                                    pagesFolder.Update();
                                }
                                rootFolder.Update();
                                webElevated.Update();
                                publishingWeb.Update();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (publishingWeb != null)
                        {
                            publishingWeb.Close();
                        }
                    }

                }

            }

            webElevated.AllowUnsafeUpdates = false;
        }


Feature De Activating:

SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPWeb spWeb = (properties.Feature.Parent as SPWeb))
                    {
                        SPFolder rootFolder = spWeb.RootFolder;
                        rootFolder.WelcomePage = "sitepages/Home.aspx";
                        rootFolder.Update();
                    }
                }
                catch (Exception ex) { }
            });












Thursday, May 12, 2016

Basic Powershell scripts for SharePoint Developer

Basic Powershell scripts for SharePoint Developer


//Get error Log, with correlationID
get-splogevent | ?{$_.Correlation -eq "correlationIDhere"} | select Area, Category, Level, EventID,Message | Format-List > C:\myError.log


//Add Solution
Add-SPSolution  -LiteralPath "C:\RKU\test.wsp"

//install solution
Install-SPSolution –Identity test.wsp –GACDeployment

//Update Solution
Update-SPSolution -Identity test.wsp -LiteralPath C:\RKU\test.wsp -GACDeployment

//Uninstall solution
Uninstall-SPSolution -Identity test.wsp

//Remove solution
Remove-SPSolution -Identity test.wsp

Tuesday, May 10, 2016

Create Headers in SharePoint

Create Headers in SharePoint


        public void CreateMyHeaderNLink(String SelectedLibrary, bool newLinkUnderHeader)
        {            
            SPNavigationNode newHeading = null;
            SPList listname = null;
            SPNavigationNodeCollection nodeColl = null;
            SPNavigationNode myDATNode = null;
            webElevated.AllowUnsafeUpdates = true;
            bool availMyDataRoomHeading = false;
            try
            {
                listname = webElevated.Lists.TryGetList(SelectedLibrary);
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(webElevated);
                nodeColl = publishingWeb.Navigation.CurrentNavigationNodes;
            }
            catch (Exception ex)
            {
                try
                {
                    activateWebPublishingFeature();
                }
                catch (Exception ex1)
                {
                    CreateMyHeaderNLink(SelectedLibrary, true);
                }
            }
            // Create or Delete heading and link
            if (nodeColl != null)
                foreach (SPNavigationNode myNode in nodeColl)
                {
                    if (myNode.Title == "My Headers")
                    {
                        availMyDataRoomHeading = true;
                        myDATNode = myNode;
                        break;
                    }
                }
            if (listname != null)
            {
                if (!availMyDataRoomHeading)
                {
                    // create
                    string DTROwnerUrl = listname.ParentWeb.Url.ToString() + "/_layouts/15/xxx/yyy.aspx";
                    newHeading = SPNavigationSiteMapNode.CreateSPNavigationNode("My Headers", DTROwnerUrl, NodeTypes.Heading, nodeColl);
                    webElevated.Update();
                    myDATNode = newHeading;
                }
                if (newLinkUnderHeader)
                {  // add to link existing header
                    try
                    {
                        bool isNodelinkExist = false;
                        if (myDATNode != null)
                        {
                            int lnkCount = myDATNode.Children.Count;
                            while (lnkCount != 0)
                            {
                                if (myDATNode.Children[lnkCount - 1].Title == listname.Title.ToString())
                                {
                                    isNodelinkExist = true; //Node exist
                                    break;
                                }
                                lnkCount--;
                            }

                            if (!isNodelinkExist)
                            {
                                SPNavigationNode listNode = new SPNavigationNode(listname.Title, listname.DefaultViewUrl);
                                if (myDATNode != null)
                                    myDATNode.Children.AddAsFirst(listNode);
                                webElevated.Update();
                            }
                        }
                    }

                    catch (Exception ex) { }
                }
            }
            webElevated.AllowUnsafeUpdates = false;

        }
        public void activateWebPublishingFeature()
        {           
            try
            {
                webElevated.AllowUnsafeUpdates = true;
                //Activate the publishing feature at the web level
                SPFeatureCollection wFeatureCollect = webElevated.Features;
                wFeatureCollect.Add(new Guid("94C94CA6-B32F-4da9-A9E1F3D343D7ECB"), true);
                webElevated.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
                try
                {
                    SPWeb webRoot = webElevated.Site.RootWeb;
                    webRoot.Site.AllowUnsafeUpdates = true;
                    //Activate the publishing feature at the site collection level
                    SPFeatureCollection sFeatureCollect = webRoot.Features;
                    sFeatureCollect.Add(new Guid("F6924D36-2FA8-4f0b-B16D-06B7250180FA"), true);
                    webRoot.AllowUnsafeUpdates = false;
                }

                catch (Exception ex1)
                {
                   // ("Error Occured! : Publishing feature activation" + ex1.Message);
                }
            }
        }



--------------------------------------------------------------
   public void clearnavBar(string siteUrl)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                    SPNavigationNodeCollection nodeColl = publishingWeb.Navigation.CurrentNavigationNodes;              
                  

                  int lnkCount = nodeColl.Count;
                  while (lnkCount != 0)
                  {
                      if (nodeColl[lnkCount - 1].Title != "My Headers")
                      {
                          nodeColl[lnkCount - 1].Delete();
                      }
                      lnkCount--;
                  }                 
                    web.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
        }

------------------------------------------------

  public static void NavigationOderBy()
        {
            //Structural Navigation: Sorting  
            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(webElevated);
            publishingWeb.Navigation.OrderingMethod = OrderingMethod.Automatic;
            publishingWeb.Navigation.AutomaticSortingMethod = AutomaticSortingMethod.Title;

        }