Friday, November 27, 2015

Monday, November 23, 2015

Update date friendly format for all lists in a site collection

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$site= Get-SPWeb "SITEURL"
$ColumnName ="Modified"
foreach ($web in $site.Site.AllWebs)
{
    Write-Host "Updating Site: " $web.Title
    for ($i=0; $i -lt $web.lists.count; $i++)
    {
        $list = $web.lists[$i]
        Write-Host $List.Title
        if($list.fields.ContainsField($ColumnName))
        {
            $column = $list.Fields[$ColumnName]
            $column.FriendlyDisplayFormat = [Microsoft.SharePoint.SPDateTimeFieldFriendlyFormatType]::Disabled
            $column.Update()
            Write-Host "Field type updated on: $($list.Title)"
        }
    }
    $web.Dispose();
}

Wednesday, November 18, 2015

Promise to overcome async

promise = new Promise(function(resolve, reject) {
     var ctxr = new SP.ClientContext(siteUrl);
     var oList = ctxr.get_web().get_lists().getByTitle('LISTNAME');
     var camlQuery = new SP.CamlQuery();
     .
     .
     .
     ctxr.executeQueryAsync(onQuerySucceeded, onQueryFailed);
});

Tuesday, November 17, 2015

Using client people picker

 initializePeoplePicker('<peoplePickerDivId>', "");

People picker values can be read by

        var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv1_TopSpan;
        var users = peoplePicker.GetAllUserInfo();
        var usersArr = new Array();
        var userInfo = '';
        for (var i = 0; i < users.length; i++) {
            usersArr.push(SP.FieldUserValue.fromUser(users[i].Key));
            alert(SP.FieldUserValue.fromUser(users[i].Key).get_lookupValue());
        }

function initializePeoplePicker(peoplePickerElementId, strUser) {
    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = true;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '280px';
    if (strUser != "") {
        this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
        var peoplePicker = eval("this.SPClientPeoplePicker.SPClientPeoplePickerDict." + peoplePickerElementId + "_TopSpan");
        peoplePicker.AddUserKeys(strUser);
    } else {
        this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
    }
}

Tuesday, September 1, 2015

Deleting List Items Using ProcessBatchData

private static void DeleteItems(){
using (SPSite oSite = new SPSite(<SiteUrl>))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists[<ListName>];
                            SPQuery oQuery = new SPQuery();
                            oQuery.Query = "<Where><Eq><FieldRef Name='<ColumnName>' /><Value Type='Text'>"<ColumnValue>"</Value></Eq></Where>";
                          
                            SPListItemCollection listItem = oList.GetItems(oQuery);                          
                            StringBuilder sbDelete = new StringBuilder();
                            string xmlFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
                            sbDelete.Append(xmlFormat);
                            sbDelete.Append("<Batch>");
                            string buildQuery = "<Method><SetList Scope=\"Request\">" + oList.ID + "</SetList>";
                            buildQuery = buildQuery +
                            "<SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>"; foreach (SPListItem item in listItem)
                            {
                                sbDelete.Append(string.Format(buildQuery, item.ID.ToString()));
                            }
                            sbDelete.Append("</Batch>");
                            oWeb.ProcessBatchData(sbDelete.ToString());
                        }
                    }
                });
}

Wednesday, August 26, 2015

Download version documents from SharePoint document library

private static void DownloadVersion()
        {
            using (ClientContext clientContext = new ClientContext("siteurl"))
            {

                NetworkCredential credentials = new NetworkCredential("username", "password", "domain");
                clientContext.Credentials = credentials;
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

                Microsoft.SharePoint.Client.File sourceFile = web.GetFileByServerRelativeUrl(web.ServerRelativeUrl + "/Documents/Test.docx");

                clientContext.Load(sourceFile, item => item.Name);
                clientContext.ExecuteQuery();

                var versions = sourceFile.Versions;
                clientContext.Load(versions);

                var oldVersions = clientContext.LoadQuery(versions.Where(v => v != null));
                clientContext.ExecuteQuery();

                string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                string pathDownload = Path.Combine(pathUser, "Downloads");

                if (oldVersions != null)
                {
                    foreach (Microsoft.SharePoint.Client.FileVersion _version in oldVersions)
                    {
                        clientContext.Load(_version, item => item.VersionLabel);
                        clientContext.ExecuteQuery();

                        if (!Directory.Exists(pathDownload))
                        {
                            Directory.CreateDirectory(pathDownload);
                        }

                        using (var webClient = new System.Net.WebClient())
                        {
                            webClient.Credentials = credentials;
                            string filePath = Path.Combine(pathDownload + "\\", Path.GetFileNameWithoutExtension(sourceFile.Name) + _version.VersionLabel + ".docx");
                            webClient.DownloadFile("siteUrl" + _version.Url, filePath);
                        }
                    }
                }
            }
        }

Tuesday, July 21, 2015

Updating the view to have ID field as bold using Link to JS file

(function () {
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.Fields = {
'ID': { 'View' : EditorField}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

function EditorField(ctx) {
var retVal='';
retVal="<b>" + ctx.CurrentItem.ID + "</b>";
return retVal;
}

Wednesday, June 24, 2015

Create SiteCollection Using Powershell

$homeUrl = read-host "Enter WebApplication URL"
$managepath = read-host "Enter site collection relative path here including any managed path. Managed path needs to be existing"
$scName = read-host "Enter site collection name here"
$sitesHomeUrl = $homeUrl + $managepath + "/" + $scName
$primaryOwner = read-host "Enter primary owner account here"
$secondaryOwner = read-host "Enter scondary owner account here"
$contentDatabaseName = read-host "Enter content database name here"
$contentDatabaseServerName = read-host "Enter database server name here"
$templateName = "BLANKINTERNETCONTAINER#0"

#Create new content database
New-SPContentDatabase -Name $contentDatabaseName -DatabaseServer $contentDatabaseServerName -WebApplication $homeUrl
#Create new site collection
write-host $sitesHomeUrl;
New-SPSite -Url $sitesHomeUrl -OwnerAlias $primaryOwner -SecondaryOwnerAlias $secondaryOwner -ContentDatabase $contentDatabaseName -Template $templateName

Tuesday, June 9, 2015

Get list guid using SPServices

function GetListId(listName) {
var id = "";
$().SPServices({
operation: "GetList",
listName: listName,
async: false,
completefunc: function (xData, Status) {
id = $(xData.responseXML).find("List").attr("ID");
}
});
return id;

Monday, June 8, 2015

Reuse loader image in SharePoint 2013

oLoader = SP.UI.ModalDialog.showWaitScreenWithNoClose(SP.Res.dialogLoading15);

oLoader.close();

Thursday, April 23, 2015

Check current user exists in a group using an AJAX call

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('Site Members')/Users?         $filter=Id eq " + _spPageContextInfo.userId,
    type: "GET",
    cache: true,
    async: false,
    headers:{
        "ACCEPT": "application/json;odata=verbose"
    },
    success: function (data) {
  if (data.d.results[0] != undefined) {
        //user is a member
}
    },
    error: function () {
    }
});

Check current user exists on a group and hiding links using client object model

var userGroups;
function CheckPermissions(){
    var clientContext = new SP.ClientContext.get_current();
    var currentUser = clientContext.get_web().get_currentUser();
    clientContext.load(currentUser);
    userGroups = currentUser.get_groups();
    clientContext.load(userGroups);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onCheckPermissionSucceeded),
       Function.createDelegate(this, this.onCheckPermissionFailed));
}
function onCheckPermissionSucceeded(sender, args) {
    var groupsEnumerator = userGroups.getEnumerator();
    while (groupsEnumerator.moveNext()) {
  var group= groupsEnumerator.get_current();
  if(group.get_title() == "Site Members") {
  $("li a:contains('Link1')").hide();
$("li a:contains('Link2')").hide();
break;
  }
}
}  
function onCheckPermissionFailed(sender, args) {
  console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Tuesday, March 3, 2015

Bypass document properties while uploading the document

var urlReferrer=document.referrer.toString ();
if(urlReferrer.indexOf("Upload")!=-1)
{
    window.frameElement.commitPopup();
}

Friday, February 20, 2015

Getting data from a webservice using an AJAX call

  $.ajax({
            url: SERVICEURL,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" },
            async: false,
            crossDomain: true,
            success: function (data) {
                var email = data.getElementsByTagName("person")[0].getElementsByTagName("email")[0]; //email is the field returned by the service
                if (email != null && email != undefined)
                    document.getElementById('lblEmail').innerHTML = email[0].childNodes[0].nodeValue
            },
            error: function (xhr) {
                console.log(xhr.status + ': ' + xhr.statusText);
            }
        });

Getting data from a webservice

var xmlhttp = new XMLHttpRequest();
        if (window.XMLHttpRequest)
            xmlhttp = new XMLHttpRequest();
        else
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.open("GET", SERVICEURL, false);
        xmlhttp.send();
        var xmlDoc = xmlhttp.responseXML;
        if (xmlDoc != null) {
                var email = xmlDoc.getElementsByTagName("email");//Here email is the field returned from the service
                if (email != null && email != undefined && email.length != 0) {
                    document.getElementById('<%= lblEmail.ClientID %>').innerHTML = email[0].childNodes[0].nodeValue;
                    document.getElementById('lnkEmail').setAttribute('href', "mailto:" + email[0].childNodes[0].nodeValue);
                }
            }
        }

Friday, February 13, 2015

Update list item with multiple attachment using server object model

SPList oList = oWeb.Lists.TryGetList(LISTNAME);
SPListItem oItem = oList.Items.Add();
oItem["Title"] = "Sample text";
oItem.Update();

HttpFileCollection hfc = HttpContext.Current.Request.Files;
for (int iCount = 0; iCount < hfc.Count; iCount++)
{
    {
        HttpPostedFile hpf = hfc[iCount];
        if (!String.IsNullOrEmpty(hpf.FileName))
        {
            Stream fStream = hpf.InputStream;
            byte[] contents = new byte[fStream.Length];
            fStream.Read(contents, 0, (int)fStream.Length);
            fStream.Close();
            fStream.Dispose();

            SPAttachmentCollection attachments = oItem.Attachments;
            string fileName = Path.GetFileName(hpf.FileName);
            attachments.Add(fileName, contents);
        }
    }
}
oItem.Update();

Thursday, February 5, 2015

Updating list item with attachment using CSOM

ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle(listName);
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["Title"] = "Sample Text";
oListItem.Update();
clientContext.ExecuteQuery();
if (FileUploadControl.HasFiles)
{
foreach (var file in FileUploadControl.PostedFiles)
        {
        byte[] contents = new byte[Convert.ToInt32(file.ContentLength)];
                Stream fStream = file.InputStream;
                fStream.Read(contents, 0, Convert.ToInt32(file.ContentLength));
                fStream.Close();
                MemoryStream mStream = new MemoryStream(contents);
                AttachmentCreationInformation aci = new AttachmentCreationInformation();
                aci.ContentStream = mStream;
                aci.FileName = file.FileName;
                Attachment attachment = oListItem.AttachmentFiles.Add(aci);
                clientContext.Load(attachment);
                clientContext.ExecuteQuery();
}
        FileUploadControl.Dispose();
}
clientContext.Dispose();

Friday, January 23, 2015

Update item using CSOM

 <script language="ecmascript" type="text/ecmascript">
    function updateListItem() {
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var oListColl = oWeb.get_lists();
        var oList = oListColl.getByTitle(LISTNAME);    
        var oListItem = oList.getItemById(ITEMID);
        oListItem.set_item('testcolumn', 'Item Updated');
        oListItem.update();      
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }

    function onQuerySucceeded() {
        alert('Item updated successfully.');
    }
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
</script>
<input onclick="updateListItem()" type="button" value="Update List Item"/>

Tuesday, January 20, 2015

Updating a column for a particular item in a list using LINQ

SPListItem resultItem = (from SPListItem oItem in oWeb.Lists["CustomList"].Items
                         where Convert.ToString(oItem["ColumnName"]) == 'Value'
                         select oItem).First();
resultItem["Title"] = "Sample";
resultItem.Update();