Friday, May 13, 2016

How to get SharePoint field type, title, internal name using rest api



var queryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listName + "')/fields/getbyinternalnameortitle('" + fieldName + "')?@target='" + hostweburl + "'&$select=Title,TypeAsString,InternalName,Hidden";

Thursday, May 12, 2016

SharePoint 2013 Site Field Details, type names, internal names, title

SharePoint 2013 Field Type As String Details


Boolean Lower values are better LowerValuesAreBetter
Lookup Comments Lookup
AbuseReportsCommentsLookup
Text Other Address Country/Region
OtherAddressCountry
TaxonomyFieldTypeMulti Enterprise Keywords TaxKeyword
RatingCount Number of Ratings RatingCount
DateTime Date Modified _DCDateModified
Guid UID UID
Computed Link to Report ReportLink
UserMulti Previously Assigned To PreviouslyAssignedTo
User Checked out User CheckoutUser
Integer Aggregated Rating Count DescendantRatingsCount
Note Description Description
URL Icon URL XSLStyleIconUrl
Counter ID ID
Number Reputation Score ReputationScore
OutcomeChoice Task Outcome TaskOutcome
ExemptField Exempt from Policy _dlc_Exempt
CallTo Recipients V4CallTo
LookupMulti Related Issues RelatedIssues
Likes Number of Likes LikesCount
Calculated Completed Checkmark
Choice UDC Purpose Purpose
MediaFieldType test test
MultiChoice Compatible UI Version(s) UIVersion
Recurrence Recurrence fRecurrence
File Name FileLeafRef
ContactInfo Contact Information ContactInfo
ContentTypeId Content Type ID ContentTypeId
Whereabout Location Whereabout
AverageRating Rating (0-5) AverageRating
Overbook Check Double Booking Overbook
Facilities Resources Facilities
ModStat Approval Status _ModerationStatus
ThreadIndex Thread Index ThreadIndex
Attachments Attachments Attachments
AllDayEvent All Day Event fAllDayEvent
FreeBusy Free/Busy FreeBusy
CrossProjectLink Workspace WorkspaceLink
RelatedItems Related Items RelatedItems
ChannelAliasFieldType Alias ChannelAlias
Image Page Image PublishingPageImage
SummaryLinks Summary Links 2 SummaryLinks2
PublishingScheduleStartDateFieldType Scheduling Start Date PublishingStartDate
UserAgentSubstringsFieldType Device Inclusion Rules UserAgentSubstrings
HTML Acronym Description AcronymDescription
PublishingScheduleEndDateFieldType Scheduling End Date PublishingExpirationDate
LayoutVariationsField Variations PublishingAssociatedVariations
TargetTo Target Audiences Audience
PublishingCatalogSourceFieldType Catalog-Item URL CatalogSource
ContentTypeIdFieldType Associated Content Type PublishingAssociatedContentType

Sunday, May 8, 2016

Change SharePoint App Master Page

Problem
Accessing referenced file  is not allowed because the reference is outside of the App Web.

Solution

The below script is used to change the app web master page

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

$siteCollection = Get-SPSite "site collection url"
$allWebs = $siteCollection.AllWebs;

$allWebs | foreach-object {
if($_.IsAppWeb -eq $true){
if($_.Url -eq "app url")
{
$_.CustomMasterUrl = $_.ServerRelativeUrl+"/_catalogs/masterpage/app.master"
$_.MasterUrl = $_.ServerRelativeUrl+"/_catalogs/masterpage/app.master"
$_.Update()
write-host "App at "+$_.ServerRelativeUrl+"updated!"
}
}

}

Monday, May 11, 2015

Get all the web parts id of particular page using REST API.

The below code used to get the all the web parts id for the particular page.

function GetWebParts() {
    var executor = new SP.RequestExecutor(appweburl);
    var urltest = appweburl + "/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/sites/test017/Pages/default.aspx')/getlimitedwebpartmanager(scope=0)/WebParts?@target='" + hostweburl + "'";
    $.ajax({
        url: urltest,
        method: "GET",
        async: false,
        headers: {
            Accept: "application/json; odata=verbose"
        },
        success: function (data) {
            var d = "";
            if (data.d.results.length > 0) {
                for (var i = 0; i < data.d.results.length; i++) {
                    d += "<div>" + data.d.results[i].Id + "</div>"
                }
                $("#appWebLists").html(d);
            }
        },
        error: function (n) {
            SP.UI.Notify.addNotification("<span>Request failed. " + n.status + "\n" + n.statusText + "<\/span>");
        }
    });
}

Saturday, May 9, 2015

Add or Replace Existing Publishing Page Web Parts with SharePoint App Parts using App Model Approach (Provider Hosted)

The below code is tested and i am able to add app parts to the existing publishing page.

In Publishing Page the web parts can also be added in "PublishingPageContent" and "RichHTMLField"

if you are migrating from SharePoint 2010 custom web parts to App Parts which has lot of work around. especially in the case of existing publishing page which has lot of custom web parts, we cant get the zone id properly.  

Use the below code to add app part to the existing publishing page. However we could replace the existing web part with app part using web part id. 

protected void ReplaceWebPartsWithAppParts_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, clientContext.Web);
                // Get a few properties from the web
                clientContext.Load(publishingWeb);
                clientContext.ExecuteQuery();
                //Read the pages library name from the web properties
                //var pagesListName = web.AllProperties["Pages"] as string;
                var list = publishingWeb.Web.Lists.GetByTitle("Pages");
                var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
                //make sure to include the File on each Item fetched
                clientContext.Load(items,
                                   i => i.Include(item => item.File, item => item["PublishingPageContent"]));
                clientContext.ExecuteQuery();
                // Iterate through all available pages in the pages list
                foreach (var item in items)
                {
                    FindWebPartForReplacement(item, clientContext, clientContext.Web);
                }
            }
        }




 private static void FindWebPartForReplacement(ListItem item, ClientContext clientContext, Web web)
        {
            PublishingPage publishingPage = PublishingPage.GetPublishingPage(clientContext, item);

            clientContext.Load(publishingPage);
            clientContext.ExecuteQuery();

            File page = publishingPage.ListItem.File;

            // Requires Full Control permissions on the Web
            LimitedWebPartManager webPartManager = publishingPage.ListItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
            clientContext.Load(webPartManager,
                                wpm => wpm.WebParts,
                                wpm => wpm.WebParts.Include(wp => wp.WebPart.Title));
            clientContext.ExecuteQuery();

            foreach (var oldWebPartDefinition in webPartManager.WebParts)
            {
                var oldWebPart = oldWebPartDefinition.WebPart;
                // only modify if we find the old web part
                if (oldWebPart.Title != oldWebPartTitle) continue;

                // Check out the page for editing
                PublishingHelper.CheckOutFile(web, publishingPage.ListItem);

                // transform the xml into a web part definition
                WebPartDefinition definition = webPartManager.ImportWebPart(appPartXml);
                webPartManager.AddWebPart(definition.WebPart, "wpz", 0);

                clientContext.Load(webPartManager,
                                  wpm => wpm.WebParts,
                                  wpm => wpm.WebParts.Include(wp => wp.WebPart.TitleUrl, wp => wp.Id, wp => wp.WebPart.Title));
                clientContext.ExecuteQuery();

                string marker = string.Empty;
                int i = 0;
                foreach (WebPartDefinition wpd in webPartManager.WebParts)
                {
                    Guid storageKey = webPartManager.WebParts[i].Id;

                    if (wpd.WebPart.Title == "WelcomeAppPart Title")
                    {
                        clientContext.Load(publishingPage, p => p.ListItem, p => p.ListItem["PublishingPageContent"]);
                        clientContext.ExecuteQuery();

                        marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-notify ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style=\"display:none\" id=\"vid_{0}\"></div></div>", new object[] { storageKey.ToString("D") });
                        publishingPage.ListItem["PublishingPageContent"] += marker;
                        publishingPage.ListItem.Update();
                    }
                    i++;
                }

                clientContext.Load(page, p => p.CheckOutType, p => p.Level);
                clientContext.ExecuteQuery();
                PublishingHelper.CheckInPublishAndApproveFile(page);
                break;
            }
        }

Tuesday, January 6, 2015

SharePoint Workflow Association to SharePoint List

The below code is used to associate the workflow to the list as well as the update the workflow association to the sharepoint list

 // Add workflow association to my list
                        if (hasWorkflowAssociation == null)
                        {
                            sharePointSitesList.WorkflowAssociations.Add(workflowAssociation);
                            // Enable workflow
                            workflowAssociation.Enabled = true;
                        }
                        else
                        {
                            hasWorkflowAssociation.Enabled = true;
                            sharePointSitesList.UpdateWorkflowAssociation(hasWorkflowAssociation);
                            sharePointSitesList.Update();
                        }

Monday, December 15, 2014

Office 365/ SharePoint Online / SharePoint hosted App - Custom Action ScriptLink

Step1: Added button in Default.aspx page
    <input type="button" value="Add Custom Ribbon" title="Add" onclick="AddCustomAction();" />

Step2: Written the below script for "AddCustomAction" method
This method performs 2 operations
1) Add script link ie," test.js "
2) Add custom ribbon tab only for template type 10000

function AddCustomAction() {
    var context = new SP.ClientContext.get_current;
    this.oWebsite = context.get_web();
    var collUserCustomAction = this.oWebsite.get_userCustomActions();
    var scriptLink = collUserCustomAction.add();
    scriptLink.set_name('Welcomescriptlink');
    scriptLink.set_title('Welcome');
    scriptLink.set_description('Welcome to new custom script Link');
    scriptLink.set_location('ScriptLink');
    scriptLink.set_scriptSrc('~Site/Scripts/test.js');
    scriptLink.set_group('');
    scriptLink.update();

    var oUserCustomAction = collUserCustomAction.add();
    oUserCustomAction.set_name('Welcome');
    oUserCustomAction.set_title('Welcome Title');
    oUserCustomAction.set_description('Welcome to new custom Action');
    oUserCustomAction.set_location('CommandUI.Ribbon');
    oUserCustomAction.set_registrationId('10000');
    oUserCustomAction.set_registrationType(1);
    oUserCustomAction.set_group('');
    var ca = '<CommandUIExtension xmlns="http://schemas.microsoft.com/sharepoint/">' +
  '<CommandUIDefinitions>' +
    '<CommandUIDefinition Location="Ribbon.Tabs._children">' +
      '<Tab Id="Demo.Tab" Title="SLK Utilities" Description="SLK Utilities" Sequence="10000">' +
        '<Scaling Id="Demo.Tab.Scaling">' +
          '<MaxSize Id="Demo.Tab.Group.Scaling.MaxSize" GroupId="Demo.Tab.Group" Size="LargeLarge" />' +
          '<Scale Id="Demo.Tab.Group.Scaling.Scale" GroupId="Demo.Tab.Group" Size="LargeLarge" />' +
        '</Scaling>' +
        '<Groups Id="Demo.Tab.Groups">' +
          '<Group Id="Demo.Tab.Group" Title="Print" Description="Print the selected items" Template="Ribbon.Templates.Flexible2">' +
            '<Controls Id="Demo.Tab.Group.Controls">' +
              '<Button Id="DemoControlID" LabelText="" ToolTipTitle="Print" ToolTipDescription="Print the selected items" Command="DemoControlID.Command" TemplateAlias="o1" Image32by32="~site/images/printer.png" />' +
            '</Controls>' +
          '</Group>' +
        '</Groups>' +
      '</Tab>' +
    '</CommandUIDefinition>' +
    '<CommandUIDefinition Location="Ribbon.Templates._children">' +
      '<GroupTemplate Id="Ribbon.Templates.Flexible2">' +
       '<Layout Title="LargeLarge">' +
              '<OverflowSection Type="OneRow" TemplateAlias="o1" DisplayMode="Large"/>' +
              '<OverflowSection Type="OneRow" TemplateAlias="o2" DisplayMode="Large"/>' +
        '</Layout>' +
      '</GroupTemplate>' +
    '</CommandUIDefinition>' +
  '</CommandUIDefinitions>' +
  '<CommandUIHandlers>' +
    '<CommandUIHandler Command="DemoControlID.Command" CommandAction="javascript:SP.UI.ModalDialog.showModalDialog({url:\'{SiteUrl}/Pages/Demo.aspx?{StandardTokens}&amp;SPListItemId={ItemId}&amp;SPListId={ListId}\', title:\'Page Title\'});"/>' +
  '</CommandUIHandlers>' +
'</CommandUIExtension>';
    oUserCustomAction.set_commandUIExtension(ca)
    oUserCustomAction.update();
    context.load(this.oWebsite, 'Title', 'UserCustomActions');
    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert('Custom action created for ' + this.oWebsite.get_title());
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Step3: The below script i have written for " test.js " file.

var url = window.location.pathname;

if (url.toString().toLowerCase().indexOf("lists") > -1) {
    var path = url.substring(url.toString().toLowerCase().indexOf("lists"), url.length);
    var pathArray = path.split('/');
    var listName = pathArray[1];

    ExecuteOrDelayUntilScriptLoaded(retrieveWebSite, "sp.js");

    var oWebsite;
    var list;
    var viewCollection;

    function retrieveWebSite() {
        var clientContext = new SP.ClientContext.get_current();
        oWebsite = clientContext.get_web();
        list = oWebsite.get_lists().getByTitle(listName);
        viewCollection = list.get_views();
        clientContext.load(list);
        clientContext.load(viewCollection);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededs), Function.createDelegate(this, this.onQueryFaileds));
    }

    function onQuerySucceededs() {
        if (list.get_baseTemplate() == "10000") {
            var viewEnumerator = viewCollection.getEnumerator();
            while (viewEnumerator.moveNext()) {
                var currentView = viewEnumerator.get_current();
                if (currentView.get_serverRelativeUrl().toString().toLowerCase() == url.toString().toLowerCase()) {
                    SP.UI.Notify.addNotification("<span>List Title " + list.get_title() + "<\/span>");
                    var selection = SP.ListOperation.Selection.getSelectedItems(list.get_context());
                }
            }
        }
    }

    function onQueryFaileds(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}

Question:

My question is, how i can optimize the above test.js script such a way that it will execute only for template type 10000 instead of doing so many if , while checks here and executing for other lists. I would like to know if there is any other way to implement this.

Basically my task is, onclick of button i have to register and enable the custom ribbon tab ( in app web )