Monday, December 26, 2016

Upload and Publish MasterPage to SharePoint Online by using PowerShell/CSOM


cls
#Specify tenant admin and site URL
$User = "Naga@contoso.com"
$SiteURL = "https://*****.sharepoint.com/Subsite"
$MasterPageDeploymentFolder = $("C:\MasterPage")
#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteURL'" -ForegroundColor Green
}
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

function Upload-Files()
{
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
# Get the SharePoint web
    $web = $Context.Web;
    $usrRDBC = $null
#Upload page layouts file
Foreach ($MSFile in (dir $MasterPageDeploymentFolder -File))
{
Write-Host $MSFile.FullName
Deploy-MasterPage -Web $Context.Web -FilePath $MSFile.FullName
}
}
Function Deploy-MasterPage([Microsoft.SharePoint.Client.Web]$Web,[string]$FilePath)
{
     $htmlMasterPageContentTypeId = "0x0101000F1C8B9E0EB4BE489F09807B2C53288F0054AD6EF48B9F7B45A142F8173F171BD10003D357F861E29844953D5CAA1D4D8A3A00F416DBD8A79A6643A8465E6D4B8B558A"
     $fileName = [System.IO.Path]::GetFileName($FilePath)
     $fileContent = [System.IO.File]::ReadAllBytes($FilePath)
     $fileInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
     $fileInfo.Content = $fileContent
     $fileInfo.Url = $catalogList.RootFolder.ServerRelativeUrl + "/" + $fileName
     $fileInfo.Overwrite = $true
     $file = $catalogList.RootFolder.Files.Add($fileInfo)
     $Web.Context.Load($file)
     $Web.Context.ExecuteQuery()

     $listItem = $file.ListItemAllFields
     $listItem["Title"] = $file.Name;
     #listItem["MasterPageDescription"] = description;
     $listItem["ContentTypeId"] = $htmlMasterPageContentTypeId
     $listItem["UIVersion"] = [Convert]::ToString(15)
     $listItem["PublishingHidden"] = $false
     $listItem["HtmlDesignAssociated"] = $true
     $listItem.Update()
$listItem.File.Publish("")
     $Web.Context.ExecuteQuery()
}
#Execute the function
Upload-Files

Upload and Publish page layouts to SharePoint Online by using PowerShell/CSOM

cls
#Specify tenant admin and site URL
$User = "Naga@contoso.com"
$SiteURL = "https://*****.sharepoint.com/Subsite"
$PageLayoutDeploymentFolder = $("C:\PageLayouts")

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"

$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteURL'" -ForegroundColor Green
}
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds


function Upload-Files()
{
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

# Get the SharePoint web
    $web = $Context.Web;
    $usrRDBC = $null

$ArticlePageContentTypeId = "0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D"
#Upload page layouts file
Foreach ($PLFile in (dir $PageLayoutDeploymentFolder -File))
{
Write-Host $PLFile.FullName
Deploy-PageLayout -Web $Context.Web -FilePath $PLFile.FullName -AssociatedContentTypeId $ArticlePageContentTypeId
}
}

Function Deploy-PageLayout([Microsoft.SharePoint.Client.Web]$Web,[string]$FilePath,[string]$AssociatedContentTypeId)
{
     $pageLayoutContentTypeId = "0x01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE811002985A1BA00CCBC45B088E4150D7BC86C"
     $fileName = [System.IO.Path]::GetFileName($FilePath)
     $associatedContentType = $Web.AvailableContentTypes.GetById($AssociatedContentTypeId)
     $catalogList = $Web.GetCatalog([Microsoft.SharePoint.Client.ListTemplateType]::MasterPageCatalog)  
     $Web.Context.Load($catalogList.RootFolder)
     $Web.Context.Load($associatedContentType)
     $Web.Context.ExecuteQuery()
     $fileContent = [System.IO.File]::ReadAllBytes($FilePath)
     $fileInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
     $fileInfo.Content = $fileContent
     $fileInfo.Url = $catalogList.RootFolder.ServerRelativeUrl + "/" + $fileName
     $fileInfo.Overwrite = $true
     $file = $catalogList.RootFolder.Files.Add($fileInfo)
     $Web.Context.Load($file)
     $Web.Context.ExecuteQuery()

     $listItem = $file.ListItemAllFields
     $listItem["Title"] = $file.Name;
     #listItem["MasterPageDescription"] = description;
     $listItem["ContentTypeId"] = $pageLayoutContentTypeId
     $listItem["PublishingAssociatedContentType"] = [string]::Format(";#{0};#{1};#", $associatedContentType.Name, $associatedContentType.Id.StringValue)
     $listItem["UIVersion"] = [Convert]::ToString(15)
$listItem["PublishingHidden"] = $false
     $listItem.Update()
$listItem.File.Publish("")
     $Web.Context.ExecuteQuery()
}

#Execute the function
Upload-Files

Happy coding.. :)

Activate SharePoint Online features by using PowerShell/CSOM

Using below script we can activate the feature in sharepoint online site

############################################################################################################################################
# Required Parameters:
#  -> $UserName: User Name to connect to the SharePoint Online Site
#  -> $sPass: Password for the user.
#  -> $SiteUrl: SharePoint Online Site Collection
#  -> $FeatureGuid: GUID of the feature to be enabled
############################################################################################################################################

#Definition of the function that allows to enable a SPO Feature
function Activate-SPOFeature
{
    param ($SiteUrl,$UserName,$sPass,$FeatureGuid)
    try
    {    
        #Adding the Client OM Assemblies        
        Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

  $context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$sPass)
if (!$context.ServerObjectIsNull.Value)
{
   #Write-Host "Connected to SharePoint Online site: '$SubSiteURL'" -ForegroundColor green
#Add-Content -Path $LogFileName -Value([string]::Concat("Connected to SharePoint Online site:",$url))
}
$context.Credentials = $Creds
$checkAlertEmailFeature = $context.Web.Features.GetById($FeatureGuid)
   $checkAlertEmailFeature.Retrieve("DisplayName")
   $context.Load($checkAlertEmailFeature)
   $context.ExecuteQuery()
   
   if($checkAlertEmailFeature.DefinitionId -eq $null){
       Write-Host "Alert Notification  Feature need to active"  -ForegroundColor Green
$newSiteFeature = $context.Web.Features.Add($FeatureGuid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::Site)
$context.Load($newSiteFeature)
$context.ExecuteQuery()
if($newSiteFeature.DefinitionId -ne $null)
{
          Add-Content -Path $LogFileName -Value([string]::Concat("Alert Notification feature activated"))
Write-Host "Alert Notification feature activated"  -ForegroundColor Green
      }
else
{
Write-Host "Alert Notification feature not yet activated"  -ForegroundColor Green
Add-Content -Path $LogFileName -Value([string]::Concat("Alert Notification feature not yet activated"))
}
   }
   else
{
       Add-Content -Path $LogFileName -Value([string]::Concat("Alert Notification feature activated"))
   }
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()  
    }    
}

#Required Parameters
$SiteUrl = "https://*****.sharepoint.com/Subsite"
$UserName = "Naga@contoso.com"
$FeatureGuid= "ab2e9a62-d1b3-4f47-9678-7e7a72e1c645"
#$sPass = Read-Host -Prompt "Enter your password: " -AsSecureString  
$sPass=convertto-securestring "******" -asplaintext -force

Activate-SPOFeature -sSiteColUrl $SiteUrl -sUserName $UserName -sPassword $sPass -sFeatureGuid $FeatureGuid

Happy code.. :)

Steps to update SharePoint Top Navigation in Mobile view

when we access Top Navigation in desktop view mouse hover functionality will work to see all child menus but it wouldn't work on mobile view.
In mobile view we have to inject custom click functionality on parent menu by help of jquery.


Add below meta tags in master page html file

<meta http-equiv="Expires" content="0" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />

Find and replace Top Navigation id using below script line

$("ul[id*='RootAspMenu']").attr( "id", "myTopNav" );



And have below function on Master Page body

$(function() {
if ($.browser.msie && $.browser.version.substr(0,1)<7)
{
$('li').has('ul').mouseover(function(){
$(this).children('ul').css('visibility','visible');}).mouseout(function(){
$(this).children('ul').css('visibility','hidden');})
}

// Mobile
$('#menu-wrap').prepend('<div id="menu-trigger">Menu</div>');
$("#menu-trigger").on("click", function(){$("#myTopNav").slideToggle();});

// iPad
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad) $('#myTopNav ul').addClass('no-transition');    
    });  


Add below code into JS file and gave this reference into master page

$(function () {
    var pull = $('#pull');
    menu = $('div#DeltaTopNavigation ul#myTopNav');
    menu.find("ul").slideToggle();
    menu.find("li").on('click', function (e) {
        e.stopImmediatePropagation();
        $($(this).find('ul')[0]).slideToggle();
    });

    $(pull).on('click', function (e) {
        e.stopImmediatePropagation();
        menu.slideToggle();

    });

    $(window).resize(function () {
        var w = $(window).width();
        if (w > 320 && menu.is(':hidden')) {
            menu.removeAttr('style');
        }
    });

});

Save and upload masterpage to respective library.

Please reach me if you are not clear at any point of implementation.

Thursday, November 24, 2016

Create a list in SharePoint online with the help schema file using PowerShell/CSOM

We required two XML configuration files

  • first one is get major info like Site Url, Username

<?xml version="1.0" encoding="utf-8"?>
<WebSite Url="https://contoso.sharepoint.com/sites/SharepointOnine/" >
<User Name="nagaraju.p@contoso.com" ></User>
</WebSite>

  • We have place list schema files in one folder then below script will take care to create multiple list.

<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="Client Profile" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/ClientProfile" BaseType="0"
      xmlns="http://schemas.microsoft.com/sharepoint/">
  <MetaData>
    <ContentTypes>
      <ContentType ID="0x0100DC5C3AA235E71E498232D6A6F20FDEAD" Name="$Resources:core,Item;" Group="$Resources:core,List_Content_Types;" Description="$Resources:core,ItemCTDesc;">
        <Folder TargetName="Item"/>
        <FieldRefs>
          <FieldRef Name="Title" DisplayName="$Resources:core,Title;" Required="TRUE"/>
          <FieldRef Name="PartnerName" DisplayName="Partner Name" Required="TRUE"/>
          <FieldRef Name="NADescription" DisplayName="Description" Required="TRUE" Format="Image"/>
          <FieldRef Name="NotifyUsers" DisplayName="Notify Users" Required="TRUE"/>
          <FieldRef Name="Active" DisplayName="Active" Required="FALSE"/>  
          <FieldRef Name="Leader" DisplayName="Leader" Required="FALSE"/>        
        </FieldRefs>
      </ContentType>
      <ContentTypeRef ID="0x01">
        <Folder TargetName="Item" />
      </ContentTypeRef>
      <ContentTypeRef ID="0x0120" />
    </ContentTypes>
    <Fields>
      <Field Type="Text" Name="Title" DisplayName="Title" Required="TRUE" StaticName="Title" MaxLength="150" />
      <Field Type="User" Name="PartnerName" DisplayName="User Name" Required="TRUE" StaticName="PartnerName" UserSelectionMode="PeopleOnly" UserSelectionScope="0"></Field>
      <Field Type="Note" Name="NADescription" DisplayName="Description" Required="TRUE" NumLines="6"></Field>
      <Field Type="Choice" Name="NotifyUsers" DisplayName="NotifyUsers" Required="FALSE" Format="Dropdown">
        <CHOICES>
          <CHOICE>Yes</CHOICE>
          <CHOICE>No</CHOICE>
        </CHOICES>
        <Default>No</Default>
      </Field>
      <Field Type="DateTime" Name="StartDate" DisplayName="Start Date" Format="DateTime">
      </Field>
      <Field Type="URL" DisplayName="Partner Conatct Image" Format="Image" Name="PartnerConatctImage">
      </Field>
      <Field Type="Boolean" DisplayName="Active" Name="Active">
        <Default>0</Default>
      </Field>
    </Fields>
    <Views>
      <View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
        <Toolbar Type="Standard" />
        <XslLink Default="TRUE">main.xsl</XslLink>
        <RowLimit Paged="TRUE">30</RowLimit>
        <ViewFields>
          <FieldRef Name="LinkTitleNoMenu"></FieldRef>
          <FieldRef Name="PartnerName"></FieldRef>
        </ViewFields>
        <Query>
          <OrderBy>
            <FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
          </OrderBy>
        </Query>
        <ParameterBindings>
          <ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
          <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
          <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
        </ParameterBindings>
      </View>
      <View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/15/images/generic.png?rev=23" Url="AllItems.aspx">
        <Toolbar Type="Standard" />
        <XslLink Default="TRUE">main.xsl</XslLink>
        <JSLink>clienttemplates.js</JSLink>
        <RowLimit Paged="TRUE">30</RowLimit>
        <ViewFields>
          <FieldRef Name="LinkTitle"></FieldRef>
          <FieldRef Name="NADescription"></FieldRef>
        </ViewFields>
        <Query>
          <OrderBy>
            <FieldRef Name="ID"></FieldRef>
          </OrderBy>
        </Query>
        <ParameterBindings>
          <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
          <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
        </ParameterBindings>
      </View>
    </Views>
    <Forms>
      <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
      <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
      <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
    </Forms>
  </MetaData>
</List>


  • Finally run the below PowerShell/CSOM script.

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $("$dp0\WW-DeployConfig.xml")
$xmldata = [xml](Get-Content($xmlFilePath));
#Specify tenant admin and site URL
$User = $xmldata.WebSite.User.Name
$webUrl = $xmldata.WebSite.Url
$schemaXmlFilePath = $("$dp0\ListSchema\SampleList.xml")
Write-Host "Input List schema file URL: " $schemaXmlFilePath
$listTemplateId = "100"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
if (!$ctx.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteURL'" -ForegroundColor Green
}
#Bind to site collection
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$ctx.Credentials = $Creds

#Retrieve lists
$Lists = $ctx.Web.Lists
$ctx.Load($Lists)
$ctx.Load($ctx.Web.ListTemplates)
Write-Host "Loading list templates.."
$ctx.ExecuteQuery()
$files = Get-ChildItem $("$dp0\ListSchema")
for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName
Write-Host "Input XML file url: "$outfile
$schemaXml = [xml] (Get-Content $outfile)
$template = $ctx.Web.ListTemplates | WHERE { $_.ListTemplateTypeKind -eq $listTemplateId }
$info = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$info.Title = $schemaXml.List.Title
Write-Host "List Title: "$schemaXml.List.Title
$info.Url = $schemaXml.List.Url
$info.CustomSchemaXml = $schemaXml.OuterXml
$info.TemplateType = $listTemplateId
$info.TemplateFeatureId = $template.FeatureId
$list = $ctx.Web.Lists.Add($info)
$ctx.Load($list)
Write-Host $schemaXml.List.Title" list is Creating.."
$ctx.ExecuteQuery()
}

Thursday, September 22, 2016

SharePoint 2010/2013 - Verify if current user is a member of a Group using group name (CSOM Javascript)

$(document).ready(function () {
    currentUserIsMemberOf("SharePoint Owners Group").done(function (result) {
        alert(result)
    });
});


var currentUserIsMemberOf = function (groupName) {
    var found = false; var dfd = $.Deferred(function () {
        SP.SOD.executeOrDelayUntilScriptLoaded(function () {
            context = new SP.ClientContext.get_current();
            allGroups = context.get_web().get_siteGroups(); c
            ontext.load(allGroups); context.load(allGroups, 'Include(Users)');
            context.executeQueryAsync(function () {
                var groupInfo; var groupsEnumerator = allGroups.getEnumerator();
                while (groupsEnumerator.moveNext()) {
                    var group = groupsEnumerator.get_current();
                    if (group.get_title() == groupName) {
                        var usersEnumerator = group.get_users().getEnumerator();
                        while (usersEnumerator.moveNext()) {
                            var user = usersEnumerator.get_current();
                            if (user.get_id() == _spPageContextInfo.userId) {
                                found = true;
                                break;
                            }
                        }
                    }
                } dfd.resolve(found);
            }, function () { dfd.reject(args.get_message()); });
        }, 'sp.js');
    }); return dfd.promise();
}

Ref Link: https://gist.github.com/robertosljunior/cc46d4447cf6d6b60c67/119d8f3d404c35e67af3d34bade5ea871e36400d

Thursday, January 21, 2016

Create Charts using SharePoint List data, JavaScript and Google charts


  • Create a custom list name as Bar Chart List
  • Create a list columns (Month, Actual, Cummulative, Cummulative Goal)
  • Using SharePoint REST call we will fetch data from list and bind to temp array variable
  • pass that variable to google chart function
  • chat will be created
  • We have two files HTML and JS

HTML File


script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="/SiteAssets/LMS/JS/EmcoreBarchart.js"></script> <!--  Update JS path -->

<div id="chart_div" style="width: 700px; height: 500px;"></div>

<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.charts.load('current', { 'packages': ['corechart'] });
</script>

JS File

var asiaData = [];
var Header = ['Month', 'Actual', 'Cummulative', 'Cummulative Goal'];
(function ($) {
    $(document).ready(function () {
        // Ensure that the SP.js file is loaded before the custom code runs.
        SP.SOD.executeOrDelayUntilScriptLoaded(CreateBarChart, 'SP.js');
    });


    function CreateBarChart() {

        var listName = "Bar Chat List";
        jQuery.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/Items?$orderby=Modified desc&",
            type: "GET",
            headers: { Accept: "application/json;odata=verbose" },
            success: function (data) {
                $("#mainPlantandOfficeTable").html();
                if (data.d.results.length > 0) {
                    var results = data.d.results;
                    asiaData.push(Header);
                    $.each(results, function (index, dataPlants) {
                        var temp = [];
                        var PlantID = dataPlants.Id;
                        var barMonth = dataPlants.Month;
                        var barActual = dataPlants.Actual;
                        var barCummulative = dataPlants.Cummulative;
                        var barCummulativeGoal = dataPlants.CummulativeGoal;

                        temp.push(barMonth);
                        temp.push(parseFloat(barActual));                        
                        temp.push(parseFloat(barCummulative));
                        temp.push(parseFloat(barCummulativeGoal));
                        asiaData.push(temp);
                    });
                    //function for bar chart
                    google.charts.setOnLoadCallback(drawVisualization);

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                Console.log("EmcoreBarchat.js:CreateBarChart:: " + textStatus);
            }
        });


    }
})(jQuery);

function drawVisualization() {
   
    var data = google.visualization.arrayToDataTable(asiaData);

    var options = {
        title: 'Lean Training',
        //vAxis: { title: 'Cups' },
        //hAxis: { title: 'Month' },
        seriesType: 'bars',
        pointSize: 10,
        series: { 1: { type: 'line', pointShape: 'circle' }, 2: { type: 'line' } }
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}



Ref Link: https://google-developers.appspot.com/chart/interactive/docs/gallery/combochart#example

Wednesday, January 20, 2016

SharePoint List data bind to Drop down control using JavaScript

I create a list in Sharepoint which has 3 columns Title,Label and SiteUrl as per business requirement label want to show text and Url will be the value using javascript.

Need add this HTML into file
<div id="divVariationLabel">
    <select id="drpVariationlbl" id="drpVariationlbl" onchange="redirectSite()" />
</div>

Create JS file add this below script into it then add this file reference into the HTML file.

/***************************************************************************
* Name : CreateDrodown.js                                                                                                          *
* Descritption : This is the javascript file for creatig dropdown using List data                           *
***************************************************************************/
var countryData = [];
(function ($) {
    $(document).ready(function () {
        // Ensure that the SP.js file is loaded before the custom code runs.
        SP.SOD.executeOrDelayUntilScriptLoaded(CreateDropdown, 'SP.js');

    });

    /***************************************************************
    * Function : CreateDropdown                                                                             *
    * Descritption : This function is used to fill the Dropdown                                *
    ***************************************************************
    function CreateDropdown() {
        var listName = "Variation Label";
        jQuery.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/Items",
            type: "GET",
            headers: { Accept: "application/json;odata=verbose" },
            success: function (data) {
                if (data.d.results.length > 0) {
                    var results = data.d.results;
                    $.each(results, function (index, dataLabels) {
                        var temp = [];
                        var PlantID = dataLabels.Id;
                        var countryName = dataLabels.Title;
                        var countryLabel = dataLabels.Label;
                        var countrySiteUrl = dataLabels.SiteUrl;

                        //temp.push('<div class="maptitle">' + dataPlants.Title + '</div>' + plantOfficeAddress);
                        temp.push(countryName);
                        temp.push(countryLabel);
                        temp.push(countrySiteUrl);
                        countryData.push(temp);
                    });
                    for (var subArr in countryData) {                      
                            $('<option />', { value: countryData[subArr][2].Url, text: countryData[subArr][0], variationlabel: countryData[subArr][1] }).appendTo('#drpVariationlbl');
                       
                    }
                }
            }
        });
    }


})(jQuery);