Monday 5 September 2016

Fix a degraded SharePoint 2013 index partition

#set Search Service Application
$ssa = Get-SPEnterpriseSearchServiceApplication

#recreate search topology with new index component
#reset the index if the bad component is the index

#grab component name of faulty topology component and it's respective server name
Get-SPEnterpriseSearchStatus -SearchApplication $ssa -Text

#put server name where [SERVER] is.. remove the []
$hosta = get-spenterprisesearchserviceinstance -identity [SERVER]

#get the existing topology
$active = Get-SPEnterpriseSearchTopology -SearchApplication $ssa -Active

#copy the existing topology
$clone = New-SPEnterpriseSearchTopology -SearchApplication $ssa -Clone -SearchTopology $active

#remove the bad component, placing the name where [BAD COMPONENT NAME] is... remove the []
$ComponentID = (Get-SPEnterpriseSearchComponent -SearchTopology $clone -Identity [BAD COMPONENT NAME]).componentID
Remove-SPEnterpriseSearchComponent -Identity $ComponentID.GUID -SearchTopology $clone -confirm:$false

#create the new component, the example below is for the index specifically - create a new folder for the index so it's empty!
New-SPEnterpriseSearchIndexComponent -SearchTopology $clone -SearchServiceInstance $hostA -IndexPartition 0 -RootDirectory F:\SPIndex

#Set this copy as the active topology
Set-SPEnterpriseSearchTopology -identity $clone

Tuesday 30 August 2016

Upload the document using REST API in the SharePoint 2013

Below scripts are used to upload the document using REST API in the SharePoint site.

$(document).ready(function () {
    SP.SOD.executeOrDelayUntilScriptLoaded(waitForCalloutScript, 'SP.js');
   
    $.getScript("/_layouts/15/" + "SP.RequestExecutor.js", function () {
        SP.RequestExecutorInternalSharedUtility.BinaryDecode = function SP_RequestExecutorInternalSharedUtility$BinaryDecode(data) {
            var ret = '';
            if (data) {
                var byteArray = new Uint8Array(data);
                for (var i = 0; i < data.byteLength; i++) {
                    ret = ret + String.fromCharCode(byteArray[i]);
                }
            }
            ;
            return ret;
        };
        SP.RequestExecutorUtility.IsDefined = function SP_RequestExecutorUtility$$1(data) {
            var nullValue = null;
            return data === nullValue || typeof data === 'undefined' || !data.length;
        };
        SP.RequestExecutor.ParseHeaders = function SP_RequestExecutor$ParseHeaders(headers) {
            if (SP.RequestExecutorUtility.IsDefined(headers)) {
                return null;
            }
            var result = {};
            var reSplit = new RegExp('\r?\n');
            var headerArray = headers.split(reSplit);
            for (var i = 0; i < headerArray.length; i++) {
                var currentHeader = headerArray[i];
                if (!SP.RequestExecutorUtility.IsDefined(currentHeader)) {
                    var splitPos = currentHeader.indexOf(':');
                    if (splitPos > 0) {
                        var key = currentHeader.substr(0, splitPos);
                        var value = currentHeader.substr(splitPos + 1);
                        key = SP.RequestExecutorNative.trim(key);
                        value = SP.RequestExecutorNative.trim(value);
                        result[key.toUpperCase()] = value;
                    }
                }
            }
            return result;
        };
        SP.RequestExecutor.internalProcessXMLHttpRequestOnreadystatechange = function SP_RequestExecutor$internalProcessXMLHttpRequestOnreadystatechange(xhr, requestInfo, timeoutId) {
            if (xhr.readyState === 4) {
                if (timeoutId) {
                    window.clearTimeout(timeoutId);
                }
                xhr.onreadystatechange = SP.RequestExecutorNative.emptyCallback;
                var responseInfo = new SP.ResponseInfo();
                responseInfo.state = requestInfo.state;
                responseInfo.responseAvailable = true;
                if (requestInfo.binaryStringResponseBody) {
                    responseInfo.body = SP.RequestExecutorInternalSharedUtility.BinaryDecode(xhr.response);
                }
                else {
                    responseInfo.body = xhr.responseText;
                }
                responseInfo.statusCode = xhr.status;
                responseInfo.statusText = xhr.statusText;
                responseInfo.contentType = xhr.getResponseHeader('content-type');
                responseInfo.allResponseHeaders = xhr.getAllResponseHeaders();
                responseInfo.headers = SP.RequestExecutor.ParseHeaders(responseInfo.allResponseHeaders);
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 1223) {
                    if (requestInfo.success) {
                        requestInfo.success(responseInfo);
                    }
                }
                else {
                    var error = SP.RequestExecutorErrors.httpError;
                    var statusText = xhr.statusText;
                    if (requestInfo.error) {
                        requestInfo.error(responseInfo, error, statusText);
                    }
                }
            }
        };
    });  
   
});

// SET THESE INITIAL PARAMETERS
// Name of the category list
var _categoryListTitle = "Template Categories";
// Name of the document Template Library
var _docTemplateListTitle = "New Document Templates"
// Name of the target document library
var _destinationLibTitle = "Project Documents";
var _destinationLibRootFolder = "ProjectDocuments";
// URL of the target document library, set after SP.js is loaded
var _destinationlibUrl = "";
var _destinationlibUrlNew = "";
// document properties file name
var _documentPropertiesFileName = "documentProps.aspx";
var _resultHTML = '';
var _tabHTML = '';
var _ctx;
var _sourceFile;
var _destinationFileUrl;
var _destinationFile;
var _newId
var collListItem;
function waitForCalloutScript() {
 _destinationlibId = window.frameElement.dialogArgs;
 _siteServerRelativeUrl = _spPageContextInfo.siteServerRelativeUrl;
 if (_siteServerRelativeUrl === "/")
  _siteServerRelativeUrl = "";
 //_destinationlibUrl = _siteServerRelativeUrl + "/ProjectDocuments/";
    SP.SOD.executeOrDelayUntilScriptLoaded(BuildTemplateSelectionPanel, 'callout.js');
}
// Build the Document Template tabs
function BuildTemplateSelectionPanel() {
    _ctx = new SP.ClientContext.get_current();
    if (_ctx != undefined && _ctx != null) {
        var _categoryList = _ctx.get_web().get_lists().getByTitle(_categoryListTitle);
  var _sourceList = _ctx.get_web().get_lists().getById(_destinationlibId);
  var _camlQuery = new SP.CamlQuery();
        var _categories = _categoryList.getItems(_camlQuery);
        _ctx.load(_categories);
  _ctx.load(_sourceList, 'Title', 'DefaultViewUrl');
  _ctx.executeQueryAsync(
            function (sender, args) {
    //var _sourceTitle = _sourceList.get_title();
    _destinationlibUrl = ShortenDefaultViewUrl(_sourceList.get_defaultViewUrl());
                _resultHTML += "<div id='tabCategories'><ul>";
                var _categoriesEnumerator = _categories.getEnumerator();
                while (_categoriesEnumerator.moveNext()) {
                    var _categoryItem = _categoriesEnumerator.get_current();
                    _resultHTML += "<li><a href='#" + _categoryItem.get_item('Title').replace(/\s+/g, '') + "'>" + _categoryItem.get_item('Title') + "</a></li>";
                    _tabHTML += "<div catid='" + _categoryItem.get_id() + "' id='" + _categoryItem.get_item('Title').replace(/\s+/g, '') + "'></div>"
                }
                _resultHTML += "</ul>" + _tabHTML + "</div>";
                $('#resultsdiv').empty();
                $('#resultsdiv').append(_resultHTML);
            },
            function (sender, args) {
                alert('Error occured: ' + args.get_message());
            });
        BuildTabs();
    }
}
function ShortenDefaultViewUrl(defaultViewUrl)
{
 var idx = defaultViewUrl.indexOf("/Forms", 1);
 return defaultViewUrl.slice(0,idx + 1);
}
function BuildTabs() {
    var _docTemplateList = _ctx.get_web().get_lists().getByTitle(_docTemplateListTitle);
    var _docTemplateByCategory = new SP.CamlQuery();
    var _docTemplates = _docTemplateList.getItems(_docTemplateByCategory);
    _ctx.load(_docTemplates, 'Include(FileLeafRef, Id,Category,Description0,DocIcon )');
    _ctx.executeQueryAsync(
        function (sender, args) {
            var _docTemplatesEnumerator = _docTemplates.getEnumerator();
            var calloutOptions;
            while (_docTemplatesEnumerator.moveNext()) {
                var _docTemplatesItem = _docTemplatesEnumerator.get_current();
                var _docImageUrl = "/_layouts/15/images/ic" + _docTemplatesItem.get_item('DocIcon') + ".png";
                var _elementId = "docTemp" + _docTemplatesItem.get_id();
                $("div[catid='" + _docTemplatesItem.get_item('Category').get_lookupId() + "']").append("<div id='" + _elementId + "' class='tab-content' style='padding:5px' ><a id='a" + _elementId + "' style='cursor:pointer' onclick=\"selectTemplate('" + _elementId + "','" + _docTemplatesItem.get_id() + "','" + _docTemplatesItem.get_item('DocIcon') + "');\"><img width='16' height='16' title='" + _docTemplatesItem.get_item('FileLeafRef') + "'" +
                            "+alt='" + _docTemplatesItem.get_item('FileLeafRef') + "' src='" + _docImageUrl + "' border='0'/>" + "&nbsp;" + _docTemplatesItem.get_item('FileLeafRef') + "</a></div>")
                calloutOptions = new CalloutOptions();
                calloutOptions.ID = _elementId + 'notificationcallout';
                calloutOptions.launchPoint = document.getElementById('a'+_elementId);
                calloutOptions.beakOrientation = 'topBottom';
                calloutOptions.content = _docTemplatesItem.get_item('Description0');
                calloutOptions.title = _docTemplatesItem.get_item('FileLeafRef');
                var callout = CalloutManager.createNew(calloutOptions);
                callout.set({ openOptions: { event: "hover" } });
                            
            }
            $("#tabCategories").tabs();
        },
         function (sender, args) {
             alert('Error occured: ' + args.get_message());
         });
}
// event for selecting the document template
function selectTemplate(elementid, id, docType) {
    $(".tab-content").css('background-color', 'white');
    $("#" + elementid).css('background-color', 'aqua');
    $("#selectedTemplate").val(id + "-" + docType);
}
// event for creating the document based on template
function CreateDocument() {
    if ((document.getElementById("txtFileName").value).length == 0) {
        alert("FileName should not be empty");
    }
    else if ((document.getElementById("selectedTemplate").value).length == 0) {
        alert("Please select a template for the new file");
    }
    else {
        _ctx = new SP.ClientContext.get_current();
        if (_ctx != undefined && _ctx != null) {
            // Get the Web site that is associated with the client context.
            this.web = _ctx.get_web();
            _ctx.load(this.web);
            // Returns the current list.
            this.sourceList = this.web.get_lists().getByTitle(_docTemplateListTitle);
            _ctx.load(this.sourceList);
            var _currentID = $("#selectedTemplate").val().split("-")[0];
            this.currentItem = sourceList.getItemById(_currentID);
            _ctx.load(this.currentItem);
            // Get the file that is represented by the item from a document library.
            _sourceFile = this.currentItem.get_file();
            _ctx.load(_sourceFile);
            _ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
                                   Function.createDelegate(this, this.onQueryFailed));
        }
    }
}
function onQuerySucceeded(sender, args) {
    if (_sourceFile != null) {
   
     var _fileName = document.getElementById("txtFileName").value + "." + $("#selectedTemplate").val().split("-")[1];
   
     //Get source file url
     var _sourceFileUrl = _sourceFile.get_serverRelativeUrl();
     var targetExecutor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);    
               
     $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
                type: "POST",
                headers: {
                    "Accept": "application/json;odata=verbose"
                },
                success: function (data) {
                    var digest = data.d.GetContextWebInformation.FormDigestValue;
                    // Build executor action to retrieve the file data.
                    var getFileAction = {
                        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + _sourceFileUrl + "')/$value",
                        method: "GET",
                        binaryStringResponseBody: true,
                        success: function (getFileData) {
                            var notifyId = SP.UI.Notify.addNotification('Copying file... ' + _sourceFile.get_serverRelativeUrl() + ' to ' + _destinationLibTitle, true);
                            // Get the binary data.
                            //var result = data.body;
                            // Build executor action to copy the file data to the new location.
                            var copyFileAction = {
                                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('"+ _destinationLibRootFolder +"')/Files/Add(url='" + _fileName + "', overwrite=true)",
                                method: "POST",
                                headers: {
                                    "Accept": "application/json; odata=verbose",
                                    "X-RequestDigest": digest
                                },
                                contentType: "application/json;odata=verbose",
                                binaryStringRequestBody: true,
                                body: getFileData.body,
                                success: function (copyFileData) {
                                 SP.UI.Notify.removeNotification(notifyId);
                     SP.UI.Notify.addNotification('File copied successfully', false);                               
                                    var camlQuery = new SP.CamlQuery();
                                    camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>" + _fileName + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>");
                                    var destinationContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl);
                                    var destiantionWeb = destinationContext.get_web();                                  
                                    var projDocumentsList = destiantionWeb.get_lists().getByTitle(_destinationLibTitle);
                                    var collListItem = projDocumentsList.getItems(camlQuery);
                                    destinationContext.load(collListItem);
                                    destinationContext.executeQueryAsync(
                                        function (sender, args) {
                                            var listItemId = '';
                                            var listItemEnumerator = collListItem.getEnumerator();
                                            while (listItemEnumerator.moveNext()) {
                                                var oListItem = listItemEnumerator.get_current();
                                                listItemId = oListItem.get_id();
                                            }
                                            window.location = _spPageContextInfo.webAbsoluteUrl + "/"+ _destinationLibRootFolder +"/" + "Forms/" + _documentPropertiesFileName + "?ID=" + listItemId + "&docurl=" + _spPageContextInfo.webServerRelativeUrl + "/"+ _destinationLibRootFolder +"/"+_fileName;
                                        },
                                        function (sender, args) {
                                            alert('Error occured: ' + args.get_message());
                                        });                                  
                                },
                                error: function (ex) {
                                    //show your 'failed' message
                                     SP.UI.Notify.addNotification('Error copying file', false);
                      SP.UI.Notify.removeNotification(notifyId);
                                     alert(ex);
                                }
                            };
                            targetExecutor.executeAsync(copyFileAction);
                        },
                        error: function (ex) {
                            //fail                           
                            alert(ex);
                        }
                    };
                    targetExecutor.executeAsync(getFileAction);
                },
                error: function (ex) {
                    //fail
        alert(ex);
                }
            });           
    }
}
// Delegate that is called when server operation is completed with errors.
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Thursday 7 July 2016

Setup app domain in development server

Microsoft link - https://msdn.microsoft.com/en-us/library/fp179923(v=office.15)

Set up an on-premises development environment for SharePoint Add-ins

SharePoint Add-ins
Learn how to set up a development environment that is specifically suited to developing SharePoint Add-ins with an on-premises installation of SharePoint.
Last modified: September 02, 2015
Applies to: apps for SharePoint | Office 365 | SharePoint Add-ins | SharePoint Foundation 2013 | SharePoint Server 2013
Note Note
The name "apps for SharePoint" is changing to "SharePoint Add-ins". During the transition, the documentation and the UI of some SharePoint products and Visual Studio tools might still use the term "apps for SharePoint". For details, see New name for apps for Office and SharePoint.
In this article
Install the operating system for your development environment for SharePoint Add-ins
Install the prerequisites for the operating system and SharePoint
Configure services in SharePoint for server-to-server add-in use
Install Visual Studio and Office Developer Tools for Visual Studio
Configure an isolated add-in domain in SharePoint
Additional resources

The requirements for a development environment are less stringent and costly than the requirements for a production environment, and the guidelines described here do not support a production environment installation. See Overview of SharePoint 2013 installation and configuration, Hardware and software requirements for SharePoint 2013, and Configure an environment for SharePoint Add-ins for the instructions to set up a production environment installation of SharePoint.
In any development environment, you should use a computer with an x64-capable CPU, and at least 16 GB of RAM to install and run SharePoint; 24 GB of RAM is preferable.
Depending on your specific requirements and budget, you can choose from the following options:
Note Note
Installation of SharePoint is supported only on Windows Server 2008 R2 Service Pack 1 x64 or Windows Server 2012. If you want to develop SharePoint Add-ins for SharePoint on Windows 7 or Windows 8, you can sign up for an Office 365 Developer Site and develop add-ins remotely.

  1. Run the PrerequisiteInstaller.exe tool that is included with your installation files.
  2. Run the Setup.exe tool that is included with your installation files.
  3. Accept the Microsoft Software License Terms.
  4. On the Choose the installation you want page, choose Stand-alone.
    Figure 1. Installation type choice

    SharePoint 2013 Installation Server Type
  5. If any errors occur in the installation, review the log file. To find the log file, open a Command Prompt window, and then type the following commands at the command prompt. A link to the log file also appears when the installation is complete.
    cd %temp%
    dir /od *.log
    
  6. After the installation is complete, you’re prompted to start the SharePoint Products and Technologies Configuration Wizard.
    Note Note
    The SharePoint Products and Technologies Configuration Wizard may fail if you’re using a computer that is joined to a domain but that is not connected to a domain controller. If you see this failure, connect to a domain controller either directly or through a Virtual Private Network (VPN) connection, or sign in with a local account that has administrative privileges on the computer.
  7. After the configuration wizard is complete, you see the Template Selection page of the new SharePoint site. On this page, choose the Developer Site template. You can only deploy SharePoint Add-ins from Visual Studio to a Developer Site.
    Figure 2. Choose the site template page

    Site template page

In this step, you configure services in SharePoint for server-to-server add-in use. These steps ensure that you will be able to create high trust provider-hosted add-ins with your installation. See Create high-trust SharePoint Add-ins for more information about creating this kind of add-in.
  1. Ensure that the App Management Service and user profile application are configured. (It is called "App Management Service" because SharePoint Add-ins were originally named "apps for SharePoint".) The steps are as follows:
    1. In Central Administration, under Application Management, select Manage service applications.
    2. On the Service Applications page, ensure that the following services are started:
      • User Profile Service Application
      • App Management Service
    3. Under Application Management, select Manage services on server.
    4. On the Services on Server page, ensure that the following services are started:
      • User Profile Service
  2. Ensure that at least one profile is created in the User Profile Service Application. The steps are as follows:
    1. In Central Administration, under Application Management, select Manage service applications.
    2. Next, select User Profile Service Application.
    3. On the Manage Profile Service: User Profile Service Application page, under People, select Manage User Profiles.
    4. On the Manage User Profiles page, select New Profiles.
    5. On the Add User Profile page, type your account name and email address.
    6. Select Save and Close.
      Note Note
      If you get a message saying that the profile you are trying to create already exists, select Cancel and Go Back.
    7. Back on the Manage User Profiles page, you should see Total number of profiles: 1.

Verbose logging in Visual Studio

Follow these steps if you want to turn on verbose logging:
  1. Open the registry, and navigate to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\nn.n\SharePointTools, where nn.n is the version of Visual Studio, such as 12.0 or 14.0.
  2. Add a DWORD key named EnableDiagnostics.
  3. Give the key the value 1.
The registry path will change in future versions of Visual Studio.

Please read Host webs, add-in webs, and the isolated domain before you carry out any procedures in this section.
You must create an isolated domain in your test SharePoint farm. Also, your SharePoint installation needs a general wildcard host header domain where it can provision SharePoint-hosted add-ins.
For development purposes, you can modify your hosts file as you need to route your development computer to a test instance of a SharePoint Add-in. Visual Studio modifies your hosts file automatically when you build and deploy the add-in.
Note Note
For production farms, you would have to create a DNS routing strategy within your intranet and optionally configure your firewall. See Install and Manage SharePoint Add-ins for more information about how to create and configure a production environment for SharePoint Add-ins.
Perform the steps in the following procedure to create an isolated add-in domain.
Note Note
You must perform all of the steps in the following procedure while logged in as the farm administrator, and you must run the command prompt and the SharePoint Management Shell as an administrator.

Create an isolated add-in domain on your development computer

  1. Ensure that the spadmin and sptimer services are running by opening a command prompt and typing the following commands.
    net start spadminv4
    net start sptimerv4
    
  2. Create your isolated add-in domain by running the SharePoint Management Shell as an administrator and typing the following command. Replace the contosoaddins.com with your add-in domain. It should not be a subdomain of the host SharePoint domain. Doing so largely defeats the security advantages of having isolated add-in domains. For example, if the host domain is contoso.com, do not use addins.contoso.com as the add-in domain.
    Set-SPAppDomain "contosoaddins.com"
    
  3. Ensure that the SPSubscriptionSettingsService and AppManagementServiceInstance services are running by typing the following command in the SharePoint Management Shell.
    Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} | Start-SPServiceInstance
    
  4. Verify that the SPSubscriptionSettingsService and AppManagementServiceInstance services are running by typing the following command in the SharePoint Management Shell. The output will indicate whether each service is online.
    Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"}
    
  5. You must specify an account under which the SPSubscriptionService and AppManagementServiceInstance service instances will run. This account must be an SPManagedAccount. You can create an SPManagedAccount by typing the following command in the SharePoint Management Shell. (You’ll be prompted for the account domain\user and password.)
    $account = New-SPManagedAccount
    
  6. Specify an account, application pool, and database settings for the SPSubscriptionService and AppManagementServiceInstance services by typing the following code in the SharePoint Management Shell. If you created a SPManagedAccount in the preceding step, use that account name here.
    $account = Get-SPManagedAccount "domain\user" 
    $appPoolSubSvc = New-SPServiceApplicationPool -Name SettingsServiceAppPool -Account $account
    $appPoolAppSvc = New-SPServiceApplicationPool -Name AppServiceAppPool -Account $account
    $appSubSvc = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $appPoolSubSvc -Name SettingsServiceApp -DatabaseName SettingsServiceDB 
    $proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $appSubSvc
    $appAppSvc = New-SPAppManagementServiceApplication -ApplicationPool $appPoolAppSvc -Name AppServiceApp -DatabaseName AppServiceDB
    $proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appAppSvc
    
    
  7. Specify your add-in prefix (see Host webs, add-in webs, and the isolated domain) by typing the following code in the SharePoint Management Shell.
    Set-SPAppSiteSubscriptionName -Name "add-in" -Confirm:$false
    
Carry out the following procedure only if your environment uses a proxy server. After you create your isolated add-in domain, perform the steps in the following procedure to add that domain to your bypass list in Internet Explorer. This ensures that you can navigate to this domain after you deploy a SharePoint-hosted add-in or a provider-hosted add-in that includes an add-in web.

Add your isolated add-in domain to your bypass list in Internet Explorer

  1. In Internet Explorer, go to Tools.
  2. Choose Internet options.
  3. On the Connections tab, choose the LAN Settings button.
  4. Clear the Automatically detect settings check box.
  5. Select the Use a proxy server for your LAN check box.
  6. Choose the Advanced button, and then add *.YourAddinsDomain.com to the Exceptions list.
  7. Choose the OK button.
  8. Choose the OK button to close the Local Area Network (LAN) Settings dialog box.
  9. Choose the OK button to close the Internet Options dialog box.
See Deploying and installing SharePoint Add-ins: methods and options for information about your options for deploying your add-ins.
Tip Tip
After you deploy a SharePoint-hosted add-in to your installation, you may be prompted to log in with your credentials when you try to launch it. You will need to disable the loopback check to get rid of these prompts. See You receive error 401.1 when you browse a Web site that uses Integrated Authentication and is hosted on IIS 5.1 or a later version for instructions on how to disable the loopback check.

Monday 14 March 2016

Sample Client-Side Rendering (CSR) code in SharePoint 2013

function _registerSliderViewTemplate()
{

 //Include link for Category CSS file

var cssId = 'CategoryCss';
if (!document.getElementById(cssId))

{

 var head = document.getElementsByTagName('head')[0];

var link = document.createElement('link');


link.id = cssId;


 link.rel = 'stylesheet';

link.type = 'text/css';

link.href = '/_LAYOUTS/15/ProductCenter/Category.css';

link.media = 'all';


head.appendChild(link);

}

 // Initialize the variable that store the objects.

var overrideCtx = {};


overrideCtx.Templates = {};

overrideCtx.Templates.View = ViewOverrideFunc;

overrideCtx.BaseViewID = 1;

overrideCtx.ListTemplateType = 10347;

 // Register the template overrides.
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);

}


// This function builds the output for the view template

function ViewOverrideFunc(ctx) {

 if (ctx.listUrlDir != "/ProductCenter/Lists/Categories")

{

 return RenderViewTemplate(ctx);

}

 var listData = ctx.ListData;

/* This is sctricly neccesary to avoid duplicate content */

if (ctx.Templates.Body == '')
{

 return RenderViewTemplate(ctx);
}

 var finalHtml ='';

finalHtml += "<div class='hot-button-blue-container'>Categories <br/><br/>";

for (var idx in listData.Row)

{
 var listItem = listData.Row[idx];

 var catid = listItem.ID;

var catName = listItem.Title;

var targeturl = 'Products.aspx?CategoryId='+catid+'&amp;'+'Name='+catName;

var imageurl = listItem.PC_ItemImage;

var imagedesc = listItem.PC_ItemImage.desc;

var ImgArrowurl = listItem.FileRef;

 var imgArrUrl = ImgArrowurl.substring(0, ImgArrowurl.indexOf('/Lists'))+'/PublishingImages/ProductCenter/Arrow.png';

 finalHtml += "<div class='hot-commandbutton-grey-normal'>";

finalHtml += "<div>";

finalHtml += "<a href='"+targeturl+"'>";

finalHtml += "<table width='100%'>";

finalHtml += "<a href='"+targeturl+"'>";

finalHtml += "<td width='15%'>";

finalHtml += "<img src='"+imageurl+"' alt='"+imagedesc+"' border='0' />";

finalHtml += "</td>";

finalHtml += "<td width='70%' valign='middle'>";

finalHtml += "<div class='hot-commandbutton-grey-normal-title'>";

finalHtml += catName;

 finalHtml += "</div>";

finalHtml += "</td>";

finalHtml += "<td width='15%' valign='middle'>";

finalHtml += "<a href='"+targeturl+"'>";

finalHtml += "<img src='"+imgArrUrl+"' alt='NavICon' border='0'></img>";

finalHtml += "</a>";

finalHtml += "</td>";

finalHtml += "</a>";

finalHtml += "</table>";

finalHtml += "</a>";

finalHtml += "</div>";

finalHtml += "</div>";

}

 finalHtml += '</div>';

finalHtml += '<div style="clear:both;height:0px;"></div>';

 return finalHtml;
}



(function () {

ExecuteOrDelayUntilScriptLoaded(_registerSliderViewTemplate, 'clienttemplates.js');

})();

Friday 29 January 2016

PowerShell script for extracting IIS log details for specific SharePoint webapplication

Import-Module sqlps -DisableNameChecking

#Database server name
$serverName="xxxxx"
#IIS Logging database name
$databaseName="IISLoggingDB"
#Path of the file LogParser.exe
$LogParserPath="C:\Program Files (x86)\Log Parser 2.2"
#Siteid (taken from IIS server)
$SiteId="W3SVC17xxxxx"
#Path of IIS Log files
$IISLogPath="C:\inetpub\logs\LogFiles\$SiteId"
#IP Address of WFE server
$ip=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}
$IPAddress=$ip.ipaddress[0]

function Main {
param
(
    [parameter(mandatory=$true)][string]$serverName,
    [parameter(mandatory=$true)][string]$databaseName        
)

 $SQLCmd="SELECT count(*) as TotalCount FROM $SiteId";
 #Invoking SQL commnds
 $IsRecordExists=Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName  -Query $SQLCmd -ErrorAction SilentlyContinue

 if($IsRecordExists.TotalCount -gt 0)
 {
    #Get last execution date  
    $SQLCmd="SELECT TOP 1 date FROM $SiteId WHERE sIp='$IPAddress' ORDER BY date DESC";
    #Invoking SQL commnds
    $LastExecutionDate=Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName  -Query $SQLCmd
    if($LastExecutionDate -ne $null)
    {
    $LastExecutionDate = get-date $LastExecutionDate.date -Format 'yyyy-MM-dd'

    #Get last execution time  
    $SQLCmd="SELECT TOP 1 time FROM $SiteId  where date='"+$LastExecutionDate+"' ORDER BY time DESC";
    #Invoking SQL commnds
    $LastExecutionTime=Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName  -Query $SQLCmd
    $LastExecutionTime = get-date $LastExecutionTime.time.AddSeconds(1) -Format 'HH:mm:ss' 
    #Last execution date time
    $LastExecutionDateTime = get-date($LastExecutionDate +" "+ $LastExecutionTime) -Format 'yyyy-MM-dd HH:mm:ss'
    $Todaydate=Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    #Locate the logparser path
    cd $LogParserPath

    if($LastExecutionDateTime -ne $null)
       {
           #Execute the logparser.exe
           #This will create a table and insert the IIS log deatils where the file name is having 'aspx' 
           .\logparser.exe "SELECT * INTO $SiteId FROM $IISLogPath\*.log WHERE (TO_TIMESTAMP(date, time) BETWEEN TIMESTAMP('$LastExecutionDateTime', 'yyyy-MM-dd HH:mm:ss') AND TIMESTAMP('$Todaydate', 'yyyy-MM-dd HH:mm:ss')) and (EXTRACT_FILENAME(cs-uri-stem) LIKE '%aspx%') and s-ip='$IPAddress'" -i:iisw3c -o:SQL -server:$serverName -database:$databaseName -createTable: ON
       }
    }
    else
    {
      #Locate the logparser path
      cd $LogParserPath
      #Execute the logparser.exe
      #This will create a table and insert the IIS log deatils where the file name is having 'aspx'
      .\logparser.exe "SELECT * INTO $SiteId FROM $IISLogPath\*.log WHERE EXTRACT_FILENAME(cs-uri-stem) LIKE '%aspx%' and s-ip='$IPAddress'" -i:iisw3c -o:SQL -server:$serverName -database:$databaseName -createTable: ON
    }
   
 }
 else
 {
     #Locate the logparser path
     cd $LogParserPath
     #Execute the logparser.exe
     #This will create a table and insert the IIS log deatils where the file name is having 'aspx'
     .\logparser.exe "SELECT * INTO $SiteId FROM $IISLogPath\*.log WHERE EXTRACT_FILENAME(cs-uri-stem) LIKE '%aspx%' and s-ip='$IPAddress'" -i:iisw3c -o:SQL -server:$serverName -database:$databaseName -createTable: ON
 }
}

Main $serverName $databaseName

Tuesday 12 January 2016

Powershell Workflow: Install Powershell Vesrion 4 and Import SQLPS module

I had a requirement to collect the required site and list details from SharePoint sites and storing in SQL database. I have developed Powershell scripts and Powershell Workflows(for Multiple threading) to get the better Performance and then to reduce execution time.

In my environment Powershell Version 3.0 has installed already in the Server. I implemented powershell workflow scripts  as below,

GetSubSites.PS1 (Main script file calls other child PS1 files)

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")




$serverName="DEFxxxx"

$databaseName="SharePointAdminDB"

$invocation = (Get-Variable MyInvocation).Value

$directorypath = Split-Path $invocation.MyCommand.Path




function Main {




param
(
[parameter(mandatory=$true)][string]$serverName,

[parameter(mandatory=$true)][string]$databaseName,

[parameter(mandatory=$true)][string]$WebApplicationUrl



)


$webApp = Get-SPWebApplication $webApplicationURL

foreach($site in $webApp.Sites)



{
foreach($subWeb in $site.AllWebs)



{
IterateSubSites($subWeb)




$SelectSQLCmd="Select COUNT(*) as _count from SPSITES where WebapplicationUrl='"+$webApplicationURL+"' and SitecollectionUrl='"+$site.Url+"' and SubSiteUrl='"+$subWeb.Url+"'";




$recordExists = Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query $SelectSQLCmd




if($recordExists._count -gt 0)



{


$SQLCmd="UPDATE SPSITES SET WebapplicationUrl='"+$webApplicationURL+"' where WebapplicationUrl='"+$webApplicationURL+"' and SitecollectionUrl='"+$site.Url+"' and SubSiteUrl='"+$subWeb.Url+"'";

Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query $SQLCmd




"Update: Site URL - "+$subWeb.Url



}
else



{
$SQLCmd="INSERT INTO SPSITES (WebapplicationUrl, SitecollectionUrl, SubSiteUrl) VALUES ('" + $webApplicationURL + "','"+$site.Url+"','"+$subWeb.Url+"')"

Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query $SQLCmd

"Insert: Site URL - "+ $subWeb.Url



}



}
$subWeb.Dispose()



}
$site.Dispose()



}


#Recursive function iterates all subsites

function IterateSubSites ([Microsoft.SharePoint.SPWeb]$subSite)



{
if ($subSite -ne $null)



{
if($subSite.Webs -ne $null)



{
foreach($subsites in $subSite.Webs)



{
IterateSubSites($subsites)



}

}

}

}


#Get all webapplications from SPWebapplications sql table
function GetAllWebApplicationsFromTable {




param
(
[parameter(mandatory=$true)][string]$serverName,

[parameter(mandatory=$true)][string]$databaseName,

[parameter(mandatory=$true)][string]$SPFarmName,

[parameter(mandatory=$true)][string]$SQLCmd



)
$DBConnectionString = "Data Source=$serverName; Initial Catalog=$databaseName; Integrated Security=SSPI"

$conn = New-Object System.Data.SqlClient.SqlConnection($DBConnectionString)

$conn.Open()

$cmd = new-object system.data.sqlclient.sqlcommand($SQLCmd,$conn)

$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $cmd

$dsSites = New-Object System.Data.DataSet

$adapter.Fill($dsSites) | Out-Null

$conn.Close()

if($dsSites.Tables[0].rows.count -gt 0)



{
$ret=$dsSites.Tables[0]

foreach ($set in $ret)



{
$webAppUrl = $set.WebapplicationUrl




Main $serverName $databaseName $webAppUrl



}

}

}

 

 
Start-Transcript

Set-ExecutionPolicy Unrestricted




#get Farm Name and match with SQL records get webapplication urls
$SPFarm = Get-spfarm

$SPFarmName = $SPFarm.Name




#Iterate all site collections and sub sites, store in SPSITES table
GetAllWebApplicationsFromTable $serverName $databaseName $SPFarmName "select * from SPWebApplications where FarmName='$SPFarmName'"




#Iterate all list details and store in SPLISTS table
."$directorypath\GetListDetails.ps1" $serverName $databaseName




#Iterate all list details and store in SPSiteCollectionDetails table
."$directorypath\GetSiteCollectionDetails.ps1" $serverName $databaseName




#Iterate all list workflow details and store in SPListWorkflowDetails table
."$directorypath\GetListWorkflowDetails.ps1" $serverName $databaseName




#Iterate all list workflow details and store in SPListWorkflowDetails table
."$directorypath\GetSiteGroupsandUsers.ps1" $serverName $databaseName




While executing the PowerShell  scripts it throws the Out of memory exception error because of the default memory size(MaxMemoryPerShellMB) is 150MB. 

I have increased the default memory(MaxMemoryPerShellMB) to 4GB,


However  Windows Remote Management (WinRM) service does not use the customized value of the MaxMemoryPerShellMB quota. Instead, the WinRM service uses the default value, which is 150 MB.



None of above is worked for me. So finally i have installed Powershell Version 4.0 and then installed required Features back for using Invoke SQL commands in the powershell window.

You can install Powershell Version 4.0(x64 or x86) and restart the Server,
https://www.microsoft.com/en-us/download/details.aspx?id=40855

To run invoke-sqlcmd, the below three files are required,
Microsoft® Windows PowerShell Extensions for SQL Server® 2012
Microsoft® SQL Server® 2012 Shared Management Objects
Microsoft® System CLR Types for SQL Server® 2012

https://www.microsoft.com/en-us/download/details.aspx?id=29065

 Then navigate to "C:\Program Files\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLPS"

run .\SQLPS.PS1 file in SharePoint powershell window

Execute Import-Module SQLPS

At last i can able to execute SQL commands in the powershell Version 4.0