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());
}

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...