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");