Wednesday, December 17, 2014

Get current logged in username using REST API

$.ajax({
   url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=DisplayName",
   type: "GET",
   headers: {"accept": "application/json;odata=verbose"},
   success: function (data) {
      userName=data.d.DisplayName;
   },
   error: function (xhr) {
      alert(xhr.status + ': ' + xhr.statusText);
   }
}); 

Get current logged in username using Client-Side Object Model

ExecuteOrDelayUntilScriptLoaded(getUserName, "sp.js");
var userName='';
function getUserName(){
var clientContext = SP.ClientContext.get_current();
var website = clientContext.get_web();
currentUser = website.get_currentUser();
clientContext.load(website);
clientContext.load(currentUser);
clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}

function onRequestSucceeded() {
userName=currentUser.get_title();
alert(userName);
}

function onRequestFailed(sender, args) {
    alert('Error: ' + args.get_message());
}

Friday, December 12, 2014

Consuming Rest Service

            BasicHttpBinding basicHttpbinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            basicHttpbinding.Name = "BasicHttpBinding_temp";
            basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
            basicHttpbinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            EndpointAddress endpointAddress = new EndpointAddress("http://siteurl/Service.svc");

Create an object for the service referenced and pass the above two objects as its constructor parameter

Wednesday, November 19, 2014

Reading JSON data from a webservice


Create a class for the JSON data

public class JSONData
{
public string id{ get; set; }
public string name{ get; set; }
}

Use this to consume the webservice

string requestURL = "Webservice URL";
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(requestURL), "NTLM", CredentialCache.DefaultNetworkCredentials);
HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(requestURL);
spRequest.Credentials = credCache;
spRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
spRequest.Method = "GET";
spRequest.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();
if (endpointResponse.StatusCode == HttpStatusCode.OK)
{
                using (endpointResponse)
{
using (var reader = new StreamReader(endpointResponse.GetResponseStream()))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
string jSON = reader.ReadToEnd();
JSONData data = new JavaScriptSerializer().Deserialize<JSONData>(jSON);
string strId = data.id;
string strName=data.name;
}
catch (Exception ex)
{
throw ex;
}
}
}
}

Monday, November 3, 2014

Check item exists based on a column value using REST API

<script type="text/javascript">
function PreSaveAction() {
var result = false;
var value=$("select[title=MyColumn] option:selected").text();
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getbytitle('MyList')/Items?$select=LinkTitle,MyColumn/Title&$expand=MyColumn&$filter=MyColumn/Title eq '" + value;
$.ajax
({
url: requestUri,
type: "GET",
cache: true,
async: false,
headers:{
"ACCEPT": "application/json;odata=verbose"
        },
success: function (data) {
if($(data.d.results).length == 0)
result = true;
else
alert("Retry!!!");
},
error: function () {
}
});
return result;
}
</script>

Tuesday, October 21, 2014

Logging error in event viewer

        void LogError(TraceSeverity Level, Exception exception)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string errorMessage = exception.Message + "--" + exception.StackTrace;
                SPDiagnosticsService.Local.WriteTrace(0,
                    new SPDiagnosticsCategory("Error Log", Level, EventSeverity.Error), TraceSeverity.Unexpected, errorMessage, null);
            });
        }

Friday, October 10, 2014

Change text in a word file using OpenXML

using (SPSite oSite = new SPSite("SP SITE URL"))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        SPFile oFile = oWeb.GetFile("FILE TEMPLATE URL");
        byte[] byteArray = oFile.OpenBinary();
        using (MemoryStream memStr = new MemoryStream())
        {
            memStr.Write(byteArray, 0, byteArray.Length);
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
            {
                Table table = wordDoc.MainDocumentPart.Document.Body.Elements<Table>().First();//find first table
                TableRow row = table.Elements<TableRow>().ElementAt(7);//get the 7th row
                TableCell cell = row.Elements<TableCell>().ElementAt(2);//get the 2nd cell
                Paragraph p = cell.Elements<Paragraph>().First();//1st paragraph
                Run r = p.Elements<Run>().First();//1st run
                Text t = r.Elements<Text>().First();//get the text
                t.Text = "TEXT TO BE UPDATED";//set the text
            }
        }
    }
}

Wednesday, September 10, 2014

Clearing designer cache

Close SPD and then remove all files from the following folders

%APPDATA%\Microsoft\Web Server Extensions\Cache

%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache



Thursday, August 7, 2014

Get related item id from a workflow task list

​​​​<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Workflow Tasks');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));            
}

function onQuerySucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        oListItem = listItemEnumerator.get_current();
        obj=JSON.parse(oListItem.get_item('RelatedItems'));
        alert(obj[0].ItemId);
    }
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​

Friday, July 25, 2014

Popup dialog in SharePoint using javascript

function popupDialog(){
var options = SP.UI.$create_DialogOptions();
options.width = 800;
options.height = 800;

options.url = "http://serverURL";

options.dialogReturnValueCallback = Function.createDelegate(null, DialogCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
function DialogCallback(result,value){
window.location.href = "http://callbackURL";
}

Thursday, July 24, 2014

Get user properties using javascript

<script type="text/javascript">
    ExecuteOrDelayUntilScriptLoaded(getProfile, "sp.js");
    var context = null;
    var web = null;      
    function getProfile() {
        context = SP.ClientContext.get_current();
        web = context.get_web();
        userInfoList = web.get_siteUserInfoList();
        camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/><Value Type=\'Number\'>' + _spPageContextInfo.userId +
'</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>');
        this.listItems = userInfoList.getItems(camlQuery);
        context.load(listItems);
        context.executeQueryAsync(Function.createDelegate(this, this.onProfileSuccessMethod), Function.createDelegate(this,

this.onFailureMethod));
    }

    function onProfileSuccessMethod(sender, args) {
        var item = listItems.itemAt(0);
        var obj = item.get_item('FirstName');
        alert(obj);
        }
 
    function onFailureMethod(sender, args) {
        alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
    }
</script> 

Getting current login details using javascript

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}

function onQuerySucceeded() {
    alert(currentUser.get_loginName());
    alert(currentUser.get_id());
    alert(currentUser.get_title());
    alert(currentUser.get_email());
}

function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

</script>

Wednesday, July 23, 2014

Retrieving list items using JSOM

The below code adds the list title to a html control

<select id="ddlTitle" multiple="multiple"></select>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));            
}

function onQuerySucceeded(sender, args) {
    var option='';
    var oListItem='';

    var listItemEnumerator = collListItem.getEnumerator();
    var ddlTitle=document.getElementById("ddlTitle");
    while (listItemEnumerator.moveNext()) {
        oListItem = listItemEnumerator.get_current();
        option=document.createElement("option");
        option.text=oListItem.get_item('Title');
        ddlTitle.add(option);      
    }
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>​​​​​​​​​​​​​​​​​

Monday, July 21, 2014

Create Publishing page using Client Object Model

   // Get Publishing Page Layouts

 List publishingLayouts = context.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");
ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());

context.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName ==  "BlankwepartPage"));
 context.ExecuteQuery();

 ListItem layout = allItems.Where(x => x.DisplayName == "BlankwepartPage").FirstOrDefault();
                        context.Load(layout);

                        // Create a publishing page

                        PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                        publishingPageInfo.Name = "Newpage.aspx";
                        publishingPageInfo.PageLayoutListItem = layout;



                        PublishingPage publishingPage = web.AddPublishingPage(publishingPageInfo);
                        publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                        publishingPage.ListItem.File.Publish(string.Empty);
                   
                        context.Load(publishingPage);
                        context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl);
                        context.ExecuteQuery();
                     
                        Console.WriteLine("Newpage.aspx  Created and check-in completed");

Adding Content Editor Webpart on Publishing Page using Client Object Model

 using (ClientContext context = new SP.ClientContext(new Uri("http://contoso.com/")))
                {

                    Web webSite = context.Web;
                    context.Load(webSite);
                    SP.File page = webSite.GetFileByServerRelativeUrl("/sites/publishingsite/page.aspx");
                    page.CheckOut();
                    Console.WriteLine(pagename + "Page has been checked out for adding webpart");
                    var limitedWebPartManager = page.GetLimitedWebPartManager(SP.WebParts.PersonalizationScope.Shared);
                    SP.WebParts.LimitedWebPartManager manager = page.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);

                    string xmlWebpart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                        "<WebPart xmlns=\"http://schemas.microsoft.com/WebPart/v2\">" +
                                        "<Assembly>Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>" +
                                        "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" +
                                        "<Title>Sample Webpart</Title>" +
                                        "<Description>$Resources:core,ContentEditorWebPartDescription;</Description>" +
                                        "<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
                                        "<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
                                        "<![CDATA[webpart content here]]></Content>" +
                                        "<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>" +
                                        "</WebPart>";

                    Microsoft.SharePoint.Client.WebParts.WebPartDefinition oWebPartDefinition = manager.ImportWebPart(xmlWebpart);
                    SP.WebParts.WebPart webpartCE = oWebPartDefinition.WebPart;

                    context.Load(manager.AddWebPart(webpartCE, WebpartZone, Convert.ToInt16(WebpartZoneIndex)));
                    context.ExecuteQuery();

                    page.CheckIn("checking in", CheckinType.MajorCheckIn);
                    page.Publish(string.Empty);
                    context.Load(page);
                    context.ExecuteQuery();
                    Console.WriteLine(pagename + "Added webpart Check-in completed");
                    Console.WriteLine("Webpart has been added");

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...