Tuesday, 3 November 2015

How to add Content Editor Web Part in a SharePoint page programmatically?


using MSWPP = Microsoft.SharePoint.WebPartPages;
using SWUWW = System.Web.UI.WebControls.WebParts;

public  string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
        {
            try
            {
                string iD;
                using (MSWPP.SPLimitedWebPartManager limitedWebPartManager = web.GetLimitedWebPartManager(pageUrl, SWUWW.PersonalizationScope.Shared))
                {
                    using (SWUWW.WebPart webPart = createContentWebPart())
                    {
                        limitedWebPartManager.AddWebPart(webPart, zoneID, zoneIndex);
                        iD = webPart.ID;
                    }
                }
                return iD;
            }
            catch (Exception ex)
            {
                using (StreamWriter streamWriter = File.AppendText("log.WebPart.txt"))
                {
                    Log("Error: " + "Add WebPart Exception: " + ex.Message, streamWriter);
                }
                return null;
            }
        }


public  MSWPP.ContentEditorWebPart createContentWebPart()
        {
            try
            {
                MSWPP.ContentEditorWebPart contentWebPart = new MSWPP.ContentEditorWebPart();
                //Set properties of new webpart object  
                contentWebPart.ZoneID = "TOP";
                contentWebPart.Title = "Migration Status";
                contentWebPart.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                contentWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;

                //Add content to CEWP
                XmlDocument xmlDoc = new XmlDocument();
                XmlElement xmlElement = xmlDoc.CreateElement("Root");
                xmlElement.InnerText = @"<div style=""border:dashed;border-width:1px;padding:4px;font-family:calibri;font-size:12px;"">" +
                    "<b>MIGRATED</b><br/>" +
                    "</div>";
                contentWebPart.Content = xmlElement;
                contentWebPart.Content.InnerText = xmlElement.InnerText;

                return contentWebPart;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Tuesday, 13 October 2015

How to add a web part zone in a SharePoint custom page layout?


Create a custom page layout using SharePoint designer.

Select the content type for the page layout as shown below:



How to add a web part zone in a SharePoint custom page layout?


How to add a web part zone in a SharePoint custom page layout?


Then, create the web part zones like this:

<WebPartPages:WebPartZone runat="server"
      AllowPersonalization="true"
      ID="SomeID"
      FrameType="TitleBarOnly"
      Title="SomeTitle"
      Orientation="Horizontal">
</WebPartPages:WebPartZone>


How to hide SharePoint top bar (header) and left navigation from SharePoint custom master page using CSS?

You can either create a blank master page using SharePoint designer or

use the following styles:

#s4-ribbonrow, .ms-cui-topBar2, .s4-notdlg, .s4-pr s4-ribbonrowhidetitle,
.s4-notdlg noindex, #ms-cui-ribbonTopBars, #s4-titlerow,
#s4-pr s4-notdlg s4-titlerowhidetitle, #s4-leftpanel-content,#sideNavBox
{
    display:none !important;
}


.s4-ca
{
    margin-left:0px !important; margin-right:0px !important;
}


#contentBox
{
    margin-left:0px;
    margin-right:0px;
    min-width:auto;
}


#contentRow
{
padding-top:0px !important;
}


#s4-workspace
{
 width:auto !important;
}


#s4-bodyContainer
{
 padding:0px;
}

How to create SharePoint App (App-Part or Client WebPart) to embed Yammer feed in SharePoint 2013/Online?


Step 1. Create an App for SharePoint 2013 in Visual Studio.

Step 2. Add an App-Part or Client Web-Part in your App.

Step 3. Go to the Element.xml of your App Part (Client Web Part) and prepare it like this:


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ClientWebPart Name="YammerFeed" Title="Yammer Feed by CompanyName" Description="Yammer Feed is an app-part by CompanyName to display yammer feeds. This app-part can be used to embed group, topic and user feeds." DefaultWidth="500" DefaultHeight="500">

    <!-- Content element identifies the location of the page that will render inside the client web part
         Properties are referenced on the query string using the pattern _propertyName_
         Example: Src="~appWebUrl/Pages/ClientWebPart1.aspx?Property1=_property1_" -->

    <Content Type="html" Src="~appWebUrl/Pages/YammerFeed.aspx?network=_network_&amp;feedId=_feedId_&amp;feedType=_feedType_&amp;header=_header_&amp;footer=_footer_&amp;hideNetworkName=_hideNetworkName_&amp;{StandardTokens}" />

    <!-- Define properties in the Properties element.
         Remember to put Property Name on the Src attribute of the Content element above. -->

    <Properties>
      <Property
        Type="string"
        Name="network"
        WebBrowsable="true"
        WebDisplayName="Network"
        WebCategory="Yammer Settings"
        RequiresDesignerPermission="true"
        DefaultValue="CompanyName.com">
     </Property>

     <Property
        Type="string"
        Name="feedId"
        WebBrowsable="true"
        WebDisplayName="Feed ID"
        WebCategory="Yammer Settings"
        RequiresDesignerPermission="true"
        DefaultValue="5512843">
      </Property>

     <Property
        Name="feedType"
        Type="enum"
        RequiresDesignerPermission="true"
        DefaultValue="group"
        WebCategory="Yammer Settings"
        WebDisplayName="Feed Type">
        <EnumItems>
        <EnumItem WebDisplayName="Group" Value="group"/>
         <EnumItem WebDisplayName="Topic" Value="topic"/>
         <EnumItem WebDisplayName="User" Value="user"/>
        </EnumItems>
      </Property>


     <Property
        Name="header"
        Type="boolean"
        RequiresDesignerPermission="true"
        DefaultValue="false"
        WebCategory="Yammer Settings"
        WebDisplayName="Header">
      </Property>
 

      <Property
        Name="footer"
        Type="boolean"
        RequiresDesignerPermission="true"
        DefaultValue="true"
        WebCategory="Yammer Settings"
        WebDisplayName="Footer">
      </Property>

         <Property
            Name="hideNetworkName"
            Type="boolean"
            RequiresDesignerPermission="true"
            DefaultValue="false"
            WebCategory="Yammer Settings"
            WebDisplayName="Hide Network Name">
            </Property>

    </Properties>

  </ClientWebPart>
</Elements>
 



Step 4. Add an ASPX page under 'Pages' module and add the following HTML


<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<html>
<head>
    <title></title>
    <link href="../Content/App.css" rel="stylesheet" />
    <script src="../Scripts/App.js"></script>
    <script type="text/javascript" src="../Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript" data-app-id="xxxxxxxxxxxxxxxxxxxxx" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
    <script type="text/javascript" src="https://c64.assets-yammer.com/assets/platform_embed.js"></script>
    <script src="../Scripts/Yammer/YammerFeed.js"></script>
    <script type="text/javascript">
        yamLogin();
    </script>

</head>
<body style="border:solid;border-width:1px;border-color:#8f8c8c;">
    <table id="tblWait" class="fullWidth" style="display: none">
        <tr>
            <td align="center">
                <br /><br /><br />

                <img src="../Images/wait_SP.gif" />
                <img src="../Images/workingonItTextSmall.png" />

                <br /><br /><br /><br />

            </td>
        </tr>
    </table>

    <table class="loginStyle" id="tblBeforeLogin">
       <tr>
            <td align="center">
                <br /><br />

                <img id="imgSmallLogo" src="../Images/yammer-logo-final.png" />

               <br /><br />

               <input id="yammer-login" value="Login" type="button" class="loginButtonYam" />
                <br /> <br /><br /><br />

           </td>
       </tr>

    </table>  
    <div id="embedded-feed" style="height:480px;width:100%;display: none;"></div>
          
<%--Script to adjust Height and Width of the App Part--%>
    <script type="text/javascript">
        "use strict";
        window.Communica = window.Communica || {};
 
        $(document).ready(function () {
            Communica.Part.init();

        });

        Communica.Part = {
            senderId: '',

            init: function () {
               var params = document.URL.split("?")[1].split("&");

                for (var i = 0; i < params.length; i = i + 1) {
                    var param = params[i].split("=");

                    if (param[0].toLowerCase() == "senderid")
                        this.senderId = decodeURIComponent(param[1]);

                }

                this.adjustSize();

            },

            adjustSize: function () {
                var step = 30,

                newHeight,
                    contentHeight = $('#userDataContent').height(),

                    resizeMessage = '<message senderId={Sender_ID}>resize({Width}, {Height})</message>';
               resizeMessage = resizeMessage.replace("{Sender_ID}", this.senderId);
                resizeMessage = resizeMessage.replace("{Height}", "500px");
                resizeMessage = resizeMessage.replace("{Width}", "100%");
                window.parent.postMessage(resizeMessage, "*");          
            }
        };
</script>
</body>
</html>



Step 5. YammerFeed.js


// Login to yammer
function yamLogin() {
    try {
        yam.getLoginStatus(
      function (response) {
          if (response.authResponse) {
              yamGroupFeeed();
          }
          else {
              yam.connect.loginButton('#yammer-login', function (resp) {
                  if (resp.authResponse) {
                      yamGroupFeeed();

                 }
             });
          }
      }

    );
    }
   catch (err) {
        //alert(err.message);
    }
 
}

//Fetch yammer feed
function yamGroupFeeed() {
    try {
        //fetch app configurations
        var yamNetwork = decodeURIComponent(getQueryStringParameter('network'));
        var yamFeedId = decodeURIComponent(getQueryStringParameter('feedId'));
        var yamFeedType = decodeURIComponent(getQueryStringParameter('feedType'));
        var yamHeader = decodeURIComponent(getQueryStringParameter('header'));
        var yamFooter = decodeURIComponent(getQueryStringParameter('footer'));
        var yamHideNetworkName = decodeURIComponent(getQueryStringParameter('hideNetworkName'));

        //request feed
        yam.connect.embedFeed(
            {
                container: '#embedded-feed',
                network: yamNetwork,
                feedType: yamFeedType,                // can be 'group', 'topic', or 'user'         
                feedId: yamFeedId,                 // feed ID from the instructions above
                config: {
                use_sso: true
                //defaultGroupId: XXXXXXX      // specify default group id to post to

                    , header: yamHeader
                    , footer: yamFooter
                    ////, showOpenGraphPreview: false
                    ////, defaultToCanonical: false
                    , hideNetworkName: yamHideNetworkName
                }
            });
   
       document.getElementById('tblBeforeLogin').style.display = "none";
       document.getElementById('embedded-feed').style.display = "block";
    }
    catch (err) {
        //alert(err.message);
    }
}

How to link a custom CSS file from SharePoint custom master page?


A custom style sheet can be referred like this from a custom SharePoint master page :

<SharePoint:CssRegistration ID="CSSRegistration1"
Name="/sites/customteamsite/Style%20Library"/folderName/customStyles.css"
After="Theameable/corev15.css" runat="server" EnableCssTheaing="false" />



How to link a custom CSS  file from SharePoint custom master page?

Friday, 3 July 2015

How to create custom Web Service for SharePoint 2007-2013?


SharePoint 2013: http://blogs.msmvps.com/windsor/2011/11/04/walkthrough-creating-a-custom-asp-net-asmx-web-service-in-sharepoint-2010/

SharePoint 2007: Create ASP.NET Web Service Application
and follow the following blogs in case of this issue: https://dhondiyals.wordpress.com/2011/02/10/resolved-could-not-load-file-or-assembly-microsoft-sharepoint-search-version12-0-0-0-cultureneutral-publickeytoken71e9bce111e9429c-or-one-of-its-dependencies/

Wednesday, 18 February 2015

How to create a provider hosted (high trust) app for sharepoint ?

A Provider Hosted App is a high-trust app for SharePoint. A high trust app uses a digital certificate to establish a trust between remote web application and SharePoint 2013.
You’ll create a .pfx certificate file first, and then a corresponding .cer file.

To create a self-signed .pfx certificate file
1.     Goto the IIS manager, select the ServerName Node in tree view on the left.
Select the Server Certificates option in IIS.
How to create a provider hosted (high trust) app for sharepoint ?
1.      Select the Create Self-Signed Certificate link from the set of links on the right side.
2.      Name the certificate HighTrustSampleCert, and then click Ok.
3.      Right-click the certificate, and then select Export,
4.      Create a folder called C:\Certs.
5.      Back in IIS Manager, export the file to C:\Certs and give it a password.

To create a corresponding .cer file

1.      On the SharePoint server, be sure that the app pool identity for the following IIS app pools have Read rights to the C:\Certs folder:
o    SecurityTokenServiceApplicationPool
o    The app pool that serves the IIS web site that hosts the parent SharePoint web application for your test SharePoint website. For the SharePoint – 80 IIS website, the pool is called OServerPortalAppPool.

2.      In IIS manager, select the ServerName node in the tree view on the left.
3.      Double-click Server Certificates.
4.      In Server Certificates view, double-click HighTrustSampleCert to display the certificate details.
5.      On the Details tab, choose Copy to File to launch the Certificate Export Wizard, and then choose Next.
6.      Use the default value No, do not export the private key, and then choose Next.
7.      Use the default values. Choose Next.
8.      Choose Browse, browse to C:\Certs, name the certificate HighTrustSampleCert, and then choose Save. The certificate is saved as a .cer file.
9.      Choose Next.
10.  Choose Finish.


You have all the required the permissions now. Now you can start the project .
1.      Start Visual Studio 2012 by using the Run as administrator option.

2.      In Visual Studio 2012, on the File menu, choose New, and then choose New Project

3.   In the New Project dialog box, expand the Visual C# node, expand the Office/SharePoint node,           and then choose the Apps node. Choose App for SharePoint 2013.
How to create a provider hosted (high trust) app for sharepoint ?

4.      Name the project, and then choose the OK button.

5.      In the first Specify the App for SharePoint Settings dialog box, name your app and provide the URL of the SharePoint 2013 site that you want to use to debug your app. Under How do you want to host your app for SharePoint, choose Provider-Hosted Choose Finish.

       6. On Selection of provider Hosted, Click Next. The below Screen will be asking the Certificates.  Give the          User certificates, password and Issuer ID and click Finish.The Certificate needs to be created on the                    SharePoint machine and pfx file needs to be exported and shared with the Visual Studio Machine.
How to create a provider hosted (high trust) app for sharepoint ?

1         7.  Now, the Solution has been created.
How to create a provider hosted (high trust) app for sharepoint ?
8.      Solution has 2 projects,
a.      SharepointApp2
b.      SharepointApp2Web
9.      Go to the property of AppWeb project and make the .NET FRAMEWORK4.5 and create a virtual directory will be helpful to host our AppWeb on local IIS .

How to create a provider hosted (high trust) app for sharepoint ?

10.   By clicking Virtual Directory button, Virtual Directory will be created on local IIS.
11.   After property configuration, we are ready with our provided Hosted Application. Rebuild the solution.
12.  Go to the AppManifest.xml in  SharePointApp2 project and set the start page attribute to IIS Directory.

How to create a provider hosted (high trust) app for sharepoint ?
13.      Go to the permission tab. Add the corresponding permission and full control.
14.       Now we will  registered our Client ID with SharePoint, before deploying App. Client ID is nothing but GUID. You can generate the client ID by reaching the APPregnew.aspx inside the 15 hive.
15.       Go to the APPmanifest.xml of SharePointApp2 project and give the client ID.
            <AppPrincipal>
                  <RemoteWebApplication ClientId="*" /
             </AppPrincipal>
4          16. Go to the WebConfig file and add the client ID with below key.

<appSettings>
<add key="ClientId" value="1de402c2-911a-47f5-8b51-fd8b57144c41"/>
<add key="ClientSecret" value="7Q1y02pvvWMBW7fzlAEnHsSGGATFWra1YEFCIo117sg="/>
<add key="ClientSigningCertificatePath" value="C:\MyCertificate.pfx"/>
   <add key="ClientSigningCertificatePassword" value="****"/>
  <add key="IssuerId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"/>
 </appSettings>

17.Now deploy the Solution. So after successful deployment it will show like a page.

How to create a provider hosted (high trust) app for sharepoint ?
Click the Trust it. The App will get installed. We can lunch the app from our SharePoint Portal. 


Monday, 16 February 2015

How to create SharePoint list picker control using Javascript (pickertreedialog.js) ?

Reference:

<script type="text/javascript" src="/_layouts/1033/pickertreedialog.js"></script>

HTML Controls:

<div id="tralert" style="display: none">
   <div class="informationBar">
      <span id="lblMessage"></span>
   </div>
</div>

<div>
<input type="text" id="txtListPicker" readonly="readonly" />
<input type="button" id="btnListPicker" onclick="listPickerScript();" value="..." />
</div>

JavaScript:


//Global variables

var strListGuid, strListUrl;

//Launch list picker
function listPickerScript() {
try {
var callback = function (arr) {
if (arr == null || arr == undefined)
return;

strListUrl = arr[3];

strListGuid = getListGUID(arr[0]);

document.getElementById('txtListPicker').value = arr[2];
 
try {
if (arr[2] == "") {
document.getElementById('tralert').style.display = "block";
document.getElementById('lblMessage').innerHTML = "Don't select a site. Select a list.";

}
 
else {
document.getElementById('tralert').style.display = "none";
}

}
 
catch (exp) { }

}
 
SP.SOD.executeFunc('pickertreedialog.js', 'LaunchPickerTreeDialog', function () {
LaunchPickerTreeDialog("RouterPickerSelectListTitle", "RouterPickerSelectListText", "websListsFolders", "", appweburl, "", "", "", "/_layouts/images/Copy.gif", 0, callback, '', '');

});

}
 
catch (exp) { }

}

 
//Get GUID of List
function getListGUID(strGUID) {
try{
var strSplit = strGUID.split("?");
strSplit = strSplit[0].split(":");
return strSplit[1];

}
 
catch (exp) { }

}