Friday, May 12, 2017

Generic SharePoint Jquery / Javascript functions -1

Below are few very generic Jquery / Javascript functions which can be used by SharePoint developer in daily activities.

var getFileName = function () {
    var chkVisible = $('[id*="_onetidIOFile"]').is(':visible');
    var filename;

    if (chkVisible) {
        filename = $('[id*="_onetidIOFile"]').val() + $("span[dir='ltr']").text();
    }
    else {
        filename = $("[id*='_onetidIOFile']:eq(1), span[dir='ltr']").text();
    }
    return filename;
}

var setTitleField = function (strTitleVal) {
    $("input[Title='Title']").val(strTitleVal);
}

var hideTitleRow = function () {
    $("input[Title='Title']").closest('tr').hide();
}

var hideInputFieldRow = function (fldName) {
    $("nobr:contains('" + fldName + "')").closest("tr").hide();
}

var btnTextChange = function () {
    //setButtonAvailability(
    //currentElem ,
    //strCondition
    //btnValue

    setButtonAvailability(this, 'This file can be Published to SP', 'Publish File');
}


var setButtonAvailability = function (currElem, strCondition, btnValue) {

    //currentElem ,
    //strCondition
    //btnValue

    if ((currElem.innerText === strCondition) && ($("input[value$='" + btnValue + "']").is(":disabled"))) {
        $("input[value$='" + btnValue + "']").prop('disabled', false);
    }
    else if ((currElem.innerText != strCondition)) {
        $("input[value$='" + btnValue + "']").attr("disabled", "disabled");
    }
}


var changeButtonValue = function (btnID, strNewValue) {
    var btnVal = document.getElementById(btnID).value;
    $("input[value$='" + btnVal + "']").attr('value', strNewValue);
}


var IsValidFileName = function (strFileName) {
    var fileNameAdditionalDots = new RegExp("[(?!\.\w*$)\.]");
    var fileNameSpecialCharacters = new RegExp("[~#%&*{}<>':;?/+|\"]");

    if (strFileName !== '') {
        //if (fileNameSpecialCharacters.test(strFileName) || fileNameAdditionalDots.test(strFileName)) {
        if (fileNameSpecialCharacters.test(strFileName)) {
            alert("Please remove the special characters or additional dots from the file name.");
            return false;
        }
        else {
            return true;
        }
    }
    else {
        alert("File name cannot be empty.");
        return false;
    }
}

var ifSelectionSelected = function (strDocType,strFldName) {
    if (strDocType === '' || strDocType === '(None)') {
        alert('Please select value for field '+strFldName);
        return false;
    }
    else {
        return true;
    }
}

var stringEncripte = function (strToEncript) {
    var xorKey = 129;
    var EncryptedString = '';
    for (i = 0; i < strToEncript.length; ++i) {
        EncryptedString += String.fromCharCode(xorKey ^ strToEncript.charCodeAt(i));
    }
    return EncryptedString;
}

var DisableBtnIfPublished = function (isPublishedFieldID, btnValue) {
    var isPublished = GetField(isPublishedFieldID);
    if (isPublished.checked) {
        $("input[value$='" + btnValue + "']").attr("disabled", "disabled");
    }
    else {
        $("input[value$='" + btnValue + "']").prop('disabled', false);
    }
}

var isElementVisible = function (strControl, strControlText) {
    return $(strControl).filter(function () {
        return $(this).text() === strControlText;
    }).is(':visible');
}

var ToggleButtonBehavior = function () {

    if (isElementVisible('div', 'Please select a Document Type.')) {
        $("input[value$='Publish File']").attr("disabled", "disabled");
    }
    else if (isElementVisible('table', 'This file has failed validation. Please see below for details:')) {
        $("input[value$='Publish File']").attr("disabled", "disabled");
    }
    else if (isElementVisible('table', 'This file has passed column name validation')) {
        var isPublishedFldId = $("input[Title='Is Published']").attr('id');
        DisableBtnIfPublished(isPublishedFldId, 'Publish File');
    }
    else {
        $("input[value$='Publish File']").attr("disabled", "disabled");
        setTimeout(ToggleButtonBehavior, 1000);
    }
    
    try {
        SP.SOD.executeOrDelayUntilScriptLoaded(SP.UI.ModalDialog.get_childDialog().autoSize(), 'sp.ui.dialog.js');
    }
    catch (error) {
        /*console.log('Waiting for File Validation.');*/
    } 
}

Automatic web.config changes using a SharePoint, File Size Upload,Web Application level feature

By default for SharePoint, Machine.config is configured to accept HTTP Requests up to 4096 KB (4 MB) and it is reflected in all your ASP.NET applications. TO upload larger files, You can change the Machine.config file directly, or you can change only the Web.config file of the respective application(s). Ideal way is to change web.config of the relevant application.

Now if you have access to server, you can modify web.config directly. Open your Web.config file, and just below the tag, add the following tag:

<system.web>
<httpRuntime executionTimeout="999999" maxRequestLength="2097151" />.....

But if the same changes required to be made to UAT or PROD environment, most of the time developer does not have access to servers where they can access web.config. In that scenario we have to achieve this by developing WebApplication level feature, which does this changes for us.

Below is the class which does same job on feature activated.

public class customWebConfigEventReceiver : SPFeatureReceiver
    {
        string modOwner = "LargeFileUpload";

        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            RemoveAllCustomisations(webApp);

            Collection modsCollection = webApp.WebConfigModifications;
            bool configExist = false;
            for (int i = 0; i < modsCollection.Count; i++)
            {
                if (modsCollection[i].Owner == modOwner)
                {
                    configExist = true;
                    break;
                }
            }
            if (!configExist)
            {
                webApp.WebConfigModifications.Add(createWebConfigModification("/configuration/system.web/httpRuntime", "executionTimeout", modOwner, "999999"));
                webApp.WebConfigModifications.Add(createWebConfigModification("/configuration/system.web/httpRuntime", "maxRequestLength", modOwner, "2097151"));
                webApp.Update();
                webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
            }


        }

        protected SPWebConfigModification createWebConfigModification(string sPath, string sName, string sOwner, string sValue)
        {
            //SPWebConfigModification myModification = new SPWebConfigModification(modName, modPath);
            SPWebConfigModification httpRuntimeModification = new SPWebConfigModification();
            httpRuntimeModification.Path = sPath;
            httpRuntimeModification.Name = sName;
            httpRuntimeModification.Sequence = 0;
            httpRuntimeModification.Owner = sOwner;
            httpRuntimeModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
            httpRuntimeModification.Value = sValue;
            return httpRuntimeModification;
        }

        private void RemoveAllCustomisations(SPWebApplication webApp)
        {
            if (webApp != null)
            {
                Collection collection = webApp.WebConfigModifications;
                int iStartCount = collection.Count;

                // Remove any modifications that were originally created by the owner.
                for (int c = iStartCount - 1; c >= 0; c--)
                {
                    SPWebConfigModification configMod = collection[c];

                    if (configMod.Owner == modOwner)
                    {
                        collection.Remove(configMod);
                    }
                }

                // Apply changes only if any items were removed.
                if (iStartCount > collection.Count)
                {
                    webApp.Update();
                    webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
                }
            }
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
            RemoveAllCustomisations(webApp);
            webApp.WebConfigModifications.Remove(createWebConfigModification("/configuration/system.web/httpRuntime", "executionTimeout", modOwner, "999999"));
            webApp.WebConfigModifications.Add(createWebConfigModification("/configuration/system.web/httpRuntime", "maxRequestLength", modOwner, "51200"));
            webApp.Update();
            webApp.Farm.Services.GetValue().ApplyWebConfigModifications();

        }
}

You can make settings value (True/False) in Feature Property based on need like,

  • Activate On Default
  • Always Force Install
  • Auto Active In Central Admin

Monday, May 8, 2017

Display complete result in PowerShell instead of dots

By default, when there is not enough space in the console window, PowerShell automatically cuts off parts of result columns and shows incomplete results:

So PowerShell trim the result by .. like shown below.

PS> Get–Help –Name Service

Name                              Category  Module                    Synopsis
––––                              ––––––––  ––––––                    ––––––––
Get–Service                       Cmdlet    Microsoft.PowerShell.M... Gets t...
New–Service                       Cmdlet    Microsoft.PowerShell.M... Create...
New–WebServiceProxy               Cmdlet    Microsoft.PowerShell.M... Create...
Restart–Service                   Cmdlet    Microsoft.PowerShell.M... Stops ...
Resume–Service                    Cmdlet    Microsoft.PowerShell.M... Resume...
Set–Service                       Cmdlet    Microsoft.PowerShell.M... Starts...
Start–Service                     Cmdlet    Microsoft.PowerShell.M... Starts...
Stop–Service                      Cmdlet    Microsoft.PowerShell.M... Stops ...
Suspend–Service                   Cmdlet    Microsoft.PowerShell.M... Suspen...
Connect–QADService                Cmdlet    QuestAD                   Connec...

To display everything instead of trim result.

PS> Get-Help -Name Service | Out-GridView -Title 'the results are in'

also we can display result with wrap text by following command.

PS> Get-Help -Name Service | Format-Table -Wrap

Wednesday, August 12, 2015

Throttling on a list-by-list basis

Farm Administrator can disable Throttling on a list-by-list basis.  To do this, run the following:

$web = Get-SPWeb http://webURL
$list = $web.Lists["ListName"]
$list.EnableThrottling = $false
$list.Update()


   
To validate the Throttling settings are effective, run:

$list.IsThrottled

If it returns True, the the List has been throttled and it will have more items then he throtle limit.
If it returns false, it has less items then the Throttle limit or throttling has been disabled via the EnableThrottling property.

To re-enable throttling on a list, simply run
 

$list.EnableThrottling = $true
$list.Update()





Tuesday, August 11, 2015

JavaScript module, using jQuery, for manipulating SharePoint form fields from the URL

This is nothing new that I have built but this was one of the requirement where I can not implement custom solution of SharePoint and here it is showing nice and how powerful JQuery and JavaScript for some of nice implementation.
 
I would like to add this as my reference as this is really very handy script which can be used in different scenarios based on URL parameters.

/Lists/Tasks/NewForm.aspx?Title=this is a test of text field

2009-05-31_131517.png

This is what you will get it as text assigned on field text box.

This script file can be used in any module not limited to SharePoint only but any web application.

Reference : https://spff.codeplex.com/

 

Wednesday, December 4, 2013

SharePoint 2013 Search REST API



SharePoint 2013 includes a Search REST service to add search functionality to your client and mobile applications by using any technology that supports REST web requests. You can use the Search REST service to submit Keyword Query Language (KQL) or FAST Query Language (FQL) queries in your apps for SharePoint, remote client applications, mobile applications, and other applications.

The Search REST service supports both HTTP POST and HTTP GET requests.

GET requests

Construct the URI for query GET requests to the Search REST service as follows:

/_api/search/query

For GET requests, you specify the query parameters in the URL. You can construct the GET request URL in two ways:
  • http://server/_api/search/query?query_parameter=value&query_parameter=value
  • http://server/_api/search/query(query_parameter=value&query_parameter=)
POST requests

You construct the URI for query POST requests to the Search REST service as follows:

/_api/search/postquery

For POST requests, you pass the query parameters in the request in JavaScript Object Notation (JSON) format.

The HTTP POST version of the Search REST service supports all parameters supported by the HTTP GET version. However, some of the parameters have different data types, as described in Table 1.

Table 1. Query parameters with different data types for POST requests

Parameter
Data type
string[]
string[]
​string[]

Use POST requests in the following scenarios:
  • When you'll exceed the URL length restriction with a GET request.
  • When you can't specify the query parameters in a simple URL. For example, if you have to pass parameter values that contain a complex type array, or comma-separated strings, you have more flexibility when constructing the POST request.
  • When you use the ReorderingRules parameter because it is supported only with POST requests.

Location of REST service
http://SERVER/site/_api/search
 
query
http://SERVER/site/_api/search/query
Supports HTTP Get and is used to retrieve search results.
postquery
http://SERVER/site/_api/search/postquery
Supports HTTP POST and is used to retrieve search results. This method can be used to overcome URI length restrictions when using the HTTP GET based method "query".
suggest
http://SERVER/site/_api/search/suggest
Supports HTTP GET and is used to retrieve query suggestions.
Query Parameters
Name
Description
Type
Default
querytext
The text of the search query.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'
querytemplate
The query template text.
String
Empty
 
enableinterleaving
Specifies if the result sets which are generated by executing query rule actions to add result block should be mixed with the result set for the original query.
bool
True
http://SERVER/site/_api/search/query?querytext='Search_Value'&enableinterleaving=false
sourceid
Specifies the unique identifier of the Result Source to use for executing the search query.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'&sourceid=‘GUID'
rankingmodelid
The GUID of the Rank Model to be used for this search query.
String
Empty
 
startrow
A zero-based index of the first search result to be returned.
Integer [ >= 0]
0
http://SERVER/site/_api/search/query?querytext='Search_Value'&startrow=11
rowlimit
The maximum number of search results to be returned, starting at the index specified in  startrow.
Integer [ >= 0]
10
http://SERVER/site/_api/search/query?querytext='Search_Value'&startrow=11&rowlimit=3
rowsperpage
The number of results to return per page.
Integer [ >= 0]
0
 
selectproperties
Specifies the list of managed properties to return for each search result item. For a managed property to be returned; the Retrievable flag must be set to "true" in the Search Schema.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'&selectproperties='Path,Url,Title,Author'
culture
Specifies the identifier of the language culture of the search query. If present, the value must be a valid LCID of a culture name. A list of LCIDs is available at this location.
Integer
-1
http://SERVER/site/_api/search/query?querytext='Search_Value'&culture=1044
refiners
Specifies a list of refiners to return as a comma-separated list of strings.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'&refiners='companies,contentclass,ContentType,FileExtension,FileType'
refinementfilters
The list of refinement tokens for drilldown into search results. Refinement tokens are returned as part of the RefinementResults table for the search query.
String
Empty
http://SERVER/site/_api/search/query?querytext='sharepoint'&refiners='filetype'&refinementfilters='filetype:equals("pptx")'
hiddenconstraints
Specifies additional query Search_Value that will be appended to the query.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'&hiddenconstraints='word'
sortlist
Specifies the list of properties to sort the search results by.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'&sortlist='rank:ascending'
enablestemming
Specifies whether stemming is enabled for the query.
bool
True
http://SERVER/site/_api/search/query?querytext='Search_Value'&enablestemming=false
trimduplicates
Specifies whether duplicate items should be removed from search results. This property can also
 be used to collapse hits in the result set.
bool
True
http://SERVER/site/_api/search/query?querytext='Search_Value'&trimduplicates=false
trimduplicatesincludeid
Specifies the value associated with a collapse group, typically used when a user clicks the duplicates link of an item with duplicates.
long
0L
http://SERVER/site/_api/search/query?querytext='Search_Value'&trimduplicates=true&trimduplicatesincludeid=47
timeout
Specifies the amount of time, in milliseconds, before the query request times out.
Integer
30000
http://SERVER/site/_api/search/query?querytext='Search_Value'&timeout=50000
enablenicknames
Specifies whether the exact Search_Value in the search query are used to find matches, or if nicknames
 are used as well.
bool
False
http://SERVER/site/_api/search/query?querytext='Search_Value'&enablenicknames=true
enablephonetic
Specifies whether the phonetic forms of the query Search_Value are used to find matches.
bool
False
http://SERVER/site/_api/search/query?querytext='Search_Value'&enablephonetic=true
enablefql
Specifies whether the query string is according to the FAST Query Language (FQL) syntax.
Bool
False
http://SERVER/site/_api/search/query?querytext='Search_Value'&enablefql=true
hithighlightedproperties
Specifies the list of properties to include in the HitHighlightedProperties for each result item.
String
Empty
http://SERVER/site/_api/search/query?querytext='Search_Value'&hithighlightedproperties='Title,Author'
bypassresulttypes
Specifies if the search result item type should be returned for the query results.
bool
False
 
processbestbets
Specifies if the search promoted results should be returned, if available, as a result set.
bool
True
 
clienttype
Name of a client which issued query.
String
Empty
 
personalizationdata
Gets or sets the unique identifier (GUID) for the current user who submitted the search query.
String
Empty
 
resultsurl
Specifies the URL for the page where the search results are going to be displayed.
String
Empty
 
querytag
Any custom tags to be used to identify the query. Multiple tags are separated by semicolons.
String
Empty
 
enablequeryrules
Specifies if Query Rules are turned on for this query.
bool
True
http://SERVER/site/_api/search/query?querytext='Search_Value'&enablequeryrules=false
enablesorting
Indicates whether results should be sorted.
bool
True
http://SERVER/site/_api/search/query?querytext='Search_Value'&enablesorting=false