Friday, August 2, 2019

SharePoint Online Add-in SharePoint-Host with Rest API


SharePoint Online Add-in SharePoint-Host with Rest API


App.JS

'use strict';

$(document).ready(function () {

    var hostweburl;
    var appweburl;
    var listTitle = "MyTestList";
    //The SharePoint site where an App is installed
    hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
    //The location within the site where an App will be deployed
    appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));

    // resource URLs in the form: web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

    // Use cross-domain library to interact with more than one domain
    //Your remote add-in page through a proxy
    function execCrossDomainRequest() {
        var executor = new SP.RequestExecutor(appweburl);
    }

    $("#btnGet").click(function () {

        var executor = new SP.RequestExecutor(appweburl);
        // Url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/Items?@target='"+hostweburl + "'"
        //      appweburl: ...rkco-b00770cf5fd946.sharepoint.com/sites/dev/REST/      
       
        executor.executeAsync(
            {
                url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/Items?@target='"
                    + hostweburl + "'",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: successFun,
                error: errorFun
            }
        );

    });

});

function successFun(data) {
    $("#message").hide();
    var jsonObject = JSON.parse(data.body);
    var moviesHTML = "";
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++) {
        moviesHTML = moviesHTML + "<p><h3>" + results[i].Title + "</p><hr>";
    }

    document.getElementById("resultDiv").innerHTML = moviesHTML;
}

function errorFun(error) {
    $("#resultDiv").append(error.statusText)
}

//function to get a Host and App Url
function getQueryStringParameter(urlParameterKey) {
    var params = document.URL.split('?')[1].split('&');
    var strParams = '';
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split('=');
        if (singleParam[0] == urlParameterKey)
            return decodeURIComponent(singleParam[1]);
    }
}
Note: Provide permissions to the list is Read at AppManifest.xml (Based on your need)

Default.Aspx:
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
  

    <div>
        <input id="btnGet" type="button" value="Show MyList Titles" />
    </div>

    <div id="resultDiv">
    </div>

    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>

</asp:Content>


Saturday, July 13, 2019

SharePoint Add-in with REST API call Visual Studio 2017 with SharePoint Online

SharePoint Add-in with REST API call - SharePoint Online
-Visual Studio 2017.

To connect Rest API- App should needed the permission- try add app permissions in AppManifest.xml  (I have added Site Collection with Full rights).



var appUrl;
    var hostWebUrl;
    // Reading the query string from the URL
    function getQueryStringParameter(param) {
        var params = document.URL.split("?")[1].split("&");
        var strParams = "";
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == param) {
                return singleParam[1];
            }
        }
    }

    $(document).ready(function () {
        appUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

        hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        //cross domain library
        $.getScript(hostWebUrl + "/_layouts/15/SP.RequestExecutor.js", connectREST);
    });


    function connectREST() {
        var url = appUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Change Request')/items?@target='" + hostWebUrl + "'";
        var executor = new SP.RequestExecutor(appUrl);
        executor.executeAsync({
            url: url,
            method: "GET",
            headers: { "Accept": "application/json;odata=verbose" },
            success: function (data) {
                $("#message").html("REST call connected/success");
            },
            error: function (data) {
                $("#message").html("Error while REST API");
            }
        });
    }


Friday, April 20, 2018

Update custom alert template - SharePoint 2013

I am not able to update custom alert template on SharePoint list,Converts all subscribed or existing alerts of the list to the custom alert template.Update Existing/change custom alert template for SharePoint list.


below STSADM command works for SP2010 but not for 2013.
stsadm -o updatealerttemplates -url http://webapp/sitecol/ -filename "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\XML\custom_alerttemplates.xml"


Here is the solution:
Server side:


public static void AlertTemplate(SPWeb webElevated, SPList oList )
        {           
            SPAlertTemplateCollection col = new SPAlertTemplateCollection(SPWebService.ContentService);
            foreach (SPAlertTemplate spAlert in col)
            {
              //<AlertTemplate Type="List" Default="True" Name ="My Template">
                //above is based on your custom template called custom_alerttemplates.xml
                if (spAlert.Name == "My Template")
                {
                try
                    {
                        webElevated.AllowUnsafeUpdates = true;                     
                        oList.AlertTemplate = spAlert;
                        oList.Update();
                        webElevated.AllowUnsafeUpdates = false;
                    }
                    catch (Exception ex)
                    {
                        webElevated.AllowUnsafeUpdates = false;
                    }
                break;
                }
            }        
         

        }


PowerShell:
add-pssnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$AlertsTemplateCollection = new-object Microsoft.SharePoint.SPAlertTemplateCollection($contentService)
$spWeb = Get-SPWeb -Identity 'http://site/webUrL/'
$splists = $spWeb.lists
$alertslist = $splists["YourList"]
Write-Host  $alertslist

$alertslist.AlertTemplate
$alertslist.AlertTemplate = $AlertsTemplateCollection["MyTemplate name based on .xml file"]
$alertslist.Update()
Write-Host  $alertslist.AlertTemplate
$alertslist.AlertTemplate
$spWeb.Dispose()

Note: Once you execute above code, you should unsubscribe and subscribe alerts is mandatory - see the program below.


Complete Documented Notes:

Verify the “MyOrg_alerts.xml”

Go to the location of file system: C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\XML and verify the file name “MyOrg_alerts.xml” is available.

Register/add the “MyOrg_alerts” template into SharePoint environment

 STSADM command below:
stsadm -o updatealerttemplates -url "http://yourSiteUrl/" -filename "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\XML\MyOrg_alerts.xml"
Note: The URL yellow in color may vary based on the server, please change accordingly.

Update template to the library

Note: The URL yellow in color may vary based on the server, please change accordingly.
add-pssnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$AlertsTemplateCollection = new-object Microsoft.SharePoint.SPAlertTemplateCollection($contentService)
$spWeb = Get-SPWeb -Identity 'http://yourSiteUrl/'
$splists = $spWeb.lists
$alertslist = $splists["MyOrg Events"]
Write-Host $alertslist

Write-Host $alertslist.AlertTemplate
$alertslist.AlertTemplate = $AlertsTemplateCollection["MyOrg Template"]
$alertslist.Update()
Write-Host $alertslist.AlertTemplate
$spWeb.Dispose()

End User /Subscriber Action:

If already subscribed: please do un-subscribe and subscribe the alerts.

Update If Already Existing users:


add-pssnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$AlertsTemplateCollection =  new-object Microsoft.SharePoint.SPAlertTemplateCollection($contentService)
$spWeb = Get-SPWeb -Identity http://yourSiteUrl/
$splists = $spWeb.lists
$alertslist = $splists["MyOrg Events"]

$alerts = $spWeb.Alerts

if ($alerts.Count -gt 0)
{
       $myalerts = @()
       foreach ($alert in $alerts)
       {       
         if( $alert.ListID -eq $alertslist.ID)
         {
             # echo "Updating" + $alert.AlertTemplateName
                       $alert.AlertTemplate = $AlertsTemplateCollection["MyOrg Template"]
                       $alert.Update()
                     #      echo "Updated $alert.AlertTemplateName"
         }
         
             
       }
}

$spWeb.Dispose()



Server Side- C#
  public static void ConvertsAllSubscribedUsersToNewlyAddedTemplate(SPWeb webElevated)
        { // Converts all subscribed or existing alerts of the list to the custom alert template //
                        
       SPList lstCorporate = webElevated.Lists.TryGetList("MyOrg Events"); 
       foreach (SPAlert alert in webElevated.Alerts)
        {                   
           if (alert.ListID == lstCorporate.ID)
              {                        
                 alert.AlertTemplate = lstCorporate.AlertTemplate;
                 alert.Update();
              }
        }           
         

     }





Monday, April 9, 2018

DOM7011: The code on this page disabled back and forward caching


I have a JQueary function responsible to call the image carousel (binding to events and triggering),when I load the page the images are not displayed. If I refresh the page then its working as expected.


Solution: Add the below to load along with page:

try {
        $(document.body).on('click', '#user', function (e) {
            e.preventDefault();
            router.navigate('/user');
        });
    }
    catch (ex) {
       // alert(ex.message);
    }


Thursday, February 22, 2018

Powershell- SharePoint Error Log by Correlation ID



#Error Log by Correlation ID:
get-splogevent | ?{$_.Correlation -eq "GUID"} | select Area, Category, Level, EventID, Message | Format-List > "C:\ErrorByCorrelationID.log"

Powershell - Add property bag to WebApplication or Site level


# Web Application Level
$webAppUrl ="http://devvWebApp.com";
$key = "RKUTestFrmKey";
$value ="RKUTestFrmVal";

$spwebApp=Get-SPWebApplication -Identity $webAppUrl;
if($spwebApp.Properties.ContainsKey($key) -eq $False)
{
 $spwebApp.Properties.Add($key,$value);
 $spwebApp.Update();       
}
Write-Host $spwebApp.Properties[$key]

# Site Level Property Bag
$siteurl = "http://devvWebApp.com";
$site = New-Object Microsoft.SharePoint.SPSite($siteurl)
$rootWeb = $site.RootWeb
$rootWeb.Properties.Add("RKUtest", "ValueRKUTest");
$rootWeb.Properties.Update();
Write-Host $rootWeb.Properties["RKUtest"];