Friday, June 29, 2018

Bind data from Linq to DataTable with out Loop

1. Create DataTable with structure:

 DataTable dt = new DataTable();
            dt.Columns.Add("EmployeeId", typeof(string));
            dt.Columns.Add("Email", typeof(string));
            dt.Columns.Add("EmployeeName", typeof(string));
            dt.Columns.Add("Department", typeof(string));

2. Write Linq query as below:
            var Result = from objEmpDetail in empDetails.AsEnumerable()
                         where (a.DepartmentId ==10001)
                         select dt.LoadDataRow(new object[]
                         {
                            objEmpDetail.EmployeeId,
                            objEmpDetail.Email,
                            objEmpDetail.EmployeeName,
                           objEmpDetail.Department
                         }, false);

3. Copy the result to datatable:
            Result.CopyToDataTable();


Wednesday, April 18, 2018

Taxonomy Field - Cascading Dropdowns using JSLink

Taxonomy Field - Cascading Dropdowns using JSLink

var globalORGValue ="";
var globalOriginalORGValue = "";
(function () {

    // Create object that have the context information about the field that we want to change it's output render
    var ORGFiledContext = {};
    ORGFiledContext.Templates = {};
    ORGFiledContext.OnPostRender = OnPostRender
 

    ORGFiledContext.Templates.Fields = {
        // Apply the new rendering for Age field on New and Edit forms
        "BusinessTitle": {
            "NewForm": businessFiledTemplate,
            "EditForm": businessFiledTemplate
        },
        "CompanyTitle": {
            "NewForm": CompanyFiledTemplate,
            "EditForm": CompanyFiledTemplate
        },
        "DepartmentTitle": {
            "NewForm": departmentFiledTemplate,
            "EditForm": departmentFiledTemplate
        },
        "ORGBusiness": {
            "NewForm": ORGbusinessFiledTemplate,
            "EditForm": ORGbusinessFiledTemplate
        }




    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ORGFiledContext);

})();


function OnPostRender(ctx) {
 
}

function ORGbusinessFiledTemplate(ctx) {
 
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    globalOriginalORGValue = ctx.CurrentFieldValue;
    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        if(globalORGValue !="")
            return globalORGValue;
        else
            return globalOriginalORGValue;
    });

return SP.UI.Taxonomy.TaxonomyFieldTemplate.renderDisplayControl(ctx);
}


// This function provides the rendering logic
function businessFiledTemplate(ctx) {


    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        if(document.getElementById(formCtx.fieldName + "_control").selectedIndex == -1 )
            return "";
        else
            return document.getElementById(formCtx.fieldName + "_control").options[document.getElementById(formCtx.fieldName + "_control").selectedIndex].text;
    });

    // Instead of hardcoding the field value, we can fetch it from the context
    var fieldInternalName = ctx.CurrentFieldSchema.Name;
    var controlId = fieldInternalName + "_control";

    // Initialization of the field: here I'm attaching onchange event to my control,
    // so that whenever text is changed, FormContext.updateControlValue is executed.
    ctx.FormContext.registerInitCallback(fieldInternalName, function () {

        $addHandler($get(controlId), "change", function (e) {
            //    ctx.FormContext.updateControlValue(fieldInternalName, $get(controlId).value);
            // alert("x_Handler for .change() called. with " + $(this).val());
            var _ORG =document.getElementById("BusinessTitle_control").options[document.getElementById("BusinessTitle_control").selectedIndex];
            globalORGValue = _ORG.text + "|" + _ORG.value;
            LoadInit("CompanyTitle_control", $(this).val(), ctx.ListData.Items[0], 2);

        });
       //Hardcode your First Termset (should be parent for all) GUID
    LoadInit(controlId, '745193dc-65db-437d-8a3b-af3695924296', ctx.ListData.Items[0], 1);
       
    });

    // Render Html5 input (number)
    return "<select id='" + controlId + "' ><option>Loading...</option></select>";
}


function CompanyFiledTemplate(ctx) {

    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        if(document.getElementById(formCtx.fieldName + "_control").selectedIndex == -1 )
            return "";
        else
            return document.getElementById(formCtx.fieldName + "_control").options[document.getElementById(formCtx.fieldName + "_control").selectedIndex].text
    });

    // Instead of hardcoding the field value, we can fetch it from the context
    var fieldInternalName = ctx.CurrentFieldSchema.Name;
    var controlId = fieldInternalName + "_control";

    // Initialization of the field: here I'm attaching onchange event to my control,
    // so that whenever text is changed, FormContext.updateControlValue is executed.
    ctx.FormContext.registerInitCallback(fieldInternalName, function () {

        $addHandler($get(controlId), "change", function (e) {
            //    ctx.FormContext.updateControlValue(fieldInternalName, $get(controlId).value);
            //alert("x_Handler for .change() called. with " + $(this).val());
            var _ORG =document.getElementById("CompanyTitle_control").options[document.getElementById("CompanyTitle_control").selectedIndex];
            globalORGValue = _ORG.text + "|" + _ORG.value;
            LoadInit("DepartmentTitle_control", $(this).val(),ctx.ListData.Items[0], 3);
        });

    });

    // Render Html5 input (number)
    return "<select id='" + controlId + "' ><option></option></select>";
}

function departmentFiledTemplate(ctx) {

    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        if(document.getElementById(formCtx.fieldName + "_control").selectedIndex == -1 )
            return "";
        else
            return document.getElementById(formCtx.fieldName + "_control").options[document.getElementById(formCtx.fieldName + "_control").selectedIndex].text;
    });

    // Instead of hardcoding the field value, we can fetch it from the context
    var fieldInternalName = ctx.CurrentFieldSchema.Name;
    var controlId = fieldInternalName + "_control";

    ctx.FormContext.registerInitCallback(fieldInternalName, function () {

        $addHandler($get(controlId), "change", function (e) {
            //    ctx.FormContext.updateControlValue(fieldInternalName, $get(controlId).value);
            //alert("x_Handler for .change() called. with " + $(this).val());
if(document.getElementById("DepartmentTitle_control").selectedIndex!=0)
            {
         
var _ORG =document.getElementById("DepartmentTitle_control").options[document.getElementById("DepartmentTitle_control").selectedIndex];
            globalORGValue = _ORG.text + "|" + _ORG.value;
            }
             else
            {
            globalORGValue ="";
            }
         
        });

    });

    // Render Html5 input (number)
    return "<select id='" + controlId + "' value='" + formCtx.fieldValue + "'><option></option></select>";
}



function LoadInit(_elementId, _navTermSetId, _item, _level) {
//alert(_navTermSetId);
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        var elementId = "#" + _elementId;
        SP.SOD.registerSod('jquery.js', '//' +  document.location.hostname + '/Style%20Library/js/jquery-3.2.1.min.js');

        SP.SOD.executeFunc('jquery.js', 'jQuery', function () {
            SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
            SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', function () {
                SP.SOD.registerSod('sp.publishing.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.publishing.js'));
                SP.SOD.executeFunc('sp.publishing.js', 'SP.Publishing.Navigation.NavigationTermSet', function () {

                    var navTermSetId = _navTermSetId;                 
                    loadNavigationTermSet(navTermSetId,
                        function (terms) {
                            $(elementId).empty();
                         
                            var html = "<option></option>";
                            var html2 = "<option></option>";

                            var termEnumerator = terms.getEnumerator();
                            while (termEnumerator.moveNext()) {
                                var currentTerm = termEnumerator.get_current();
                            // To check is any term is deprecated or not
     var strDeprecate='';
                                 if(currentTerm.get_isDeprecated()==true)
                                {
                            //  to disable Deprecated item in Dropdown list
                               strDeprecate='disabled="disabled"';
                                }
                                if (currentTerm.get_isSourceTerm() == true) {
                             
                             
                                    html += "<option value='" + currentTerm.get_id() + "' " +strDeprecate+ " ";
                                    html += ">" + currentTerm.get_name() + "</option>";
                                } else {
                                    html2 += "<option value='" + currentTerm.get_id() + "' " +strDeprecate+ " ";
                                    html2 += ">" + currentTerm.get_name() + "</option>";


                                }

                            }
                            console.log(html);
                       // if(elementId != "#RecordType_control")
                     
                     
                                $(elementId).append(html);
                            var selectedItemGUID;
                            var selectedItemFound = false;
                            var _fieldValue = "";
                            if(_level == 1)
                            {
                                if(_item.BusinessTitle!="" && _item.BusinessTitle!=null)
                                _fieldValue = _item.BusinessTitle;
                                else
                                _fieldValue = globalMyProfile.Business;
                             
                            }
                            if(_level == 2)
                            {
                                if(_item.CompanyTitle!="" && _item.CompanyTitle!=null)
                                _fieldValue = _item.CompanyTitle;
                                else
                                _fieldValue = globalMyProfile.Company;
                             
                                $("#DepartmentTitle_control").empty();
                            }
                            if(_level == 3)
                            {
                                _fieldValue = _item.DepartmentTitle;
                            }
                            if(_level == 4)
                            {
                                _fieldValue = _item.RecordType;
                            }
                            if (_fieldValue != "") {
                                $(elementId + ' option')
                                    .filter(function (i, e) {
                                        if ($(e).text() == _fieldValue) {
                                            selectedItemGUID = $(e)[0].value;
                                            selectedItemFound = true;
                                        }
                                        return $(e).text() == _fieldValue;
                                    }).attr('selected', 'selected');

                                if(selectedItemFound )
    {
    if( elementId == "#BusinessTitle_control")
    LoadInit("CompanyTitle_control",selectedItemGUID ,_item,2);
    if( elementId == "#CompanyTitle_control")
    LoadInit("DepartmentTitle_control",selectedItemGUID ,_item,3);
   
    }
   
                            }

                       

                        },
                        function (sender, args) {
                            console.log('Request failed ' + args.get_message() + ':' + args.get_stackTrace());

                        }
                    );
                });
            });
        });
    });

}

function loadNavigationTermSet(navTermSetId, success, error) {

    var ctx = SP.ClientContext.get_current();
      console.log(navTermSetId)
    var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);
    var termStores = taxonomySession .get_termStores();
termStore = termStores.getByName("Managed MetaData Service ORG");
    var groups = termStore.get_groups()
var group = groups.getByName("ORGMMSBusiness") ;
var termSets = group.get_termSets()
termSet = termSets.getByName("ORGBusiness")
 var term = termSet.getTerm(navTermSetId);
  var terms = term.get_terms();

    ctx.load(terms);
    ctx.executeQueryAsync(function () {
            success(terms);
        },
        error);
}

Wednesday, December 20, 2017

How to use custom hyperbutton in the listveiw for each item with Popup

I am using JS Link CSR file to show the hyperlink in the ListView for each item and open a form in module popup window.

code is below:

(function () { 

    // Create object that have the context information about the field that we want to change it's output render  
    var publishFiledContext = {}; 
    publishFiledContext.Templates = {}; 
    publishFiledContext.Templates.Fields = { 
        // Apply the new rendering for Priority field on List View 
        "Publish": { "View": publishFiledTemplate } 
    }; 

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(publishFiledContext); 

})(); 

// This function provides the rendering logic for list view 
function publishFiledTemplate (ctx) { 

    var strHTML = "";
    var itemId = ctx.CurrentItem.ID;
    var itemTitle = ctx.CurrentItem.Title;
    var rootPath=ctx.HttpRoot;
    var listName=ctx.ListTitle;
    strHTML += "<a id='click"+itemId+"' href='#' onclick='return openDialog(\""+itemTitle+"\",\""+itemId+"\",\""+rootPath+"\",\""+listName+"\");'>Publish</a>"; 
                
    return strHTML ;
    



  
// This function used to open the form in dialog window as a popup

function openDialog(title,itemId,rootPath,listName)
{
    var options = SP.UI.$create_DialogOptions();
    options.title = title;
    options.width = 800;
    options.height = 700;
    options.url = rootPath+"/Lists/"+listName+"/DispForm.aspx?ID="+itemId;
    SP.UI.ModalDialog.showModalDialog(options);

    return false;
}

Please save this as a js file in "style library" and give that url in the listview webpart at "JS Link" property. the reference link should be "~sitecollection/Style Library/js/ViewHref.js"

Thursday, March 16, 2017

Get Items Count from Library/List from SiteCollection



############################################################
#Script to get all Library item count from the sitecollection and subsites
# Required Parameters:
#  -> $sUserName: User Name .
#  -> $sPassword: Password for the user.
#  -> $sDomain: AD Domain for the user.
#  -> $sSiteColUrl: Site Collection Url.
##########################################################

$host.Runspace.ThreadOptions = "ReuseThread"

#To get all Library item count from the sitecollection and subsites
function Get-SPAllDocCountInSiteCol
{



    param ($sSiteColUrl,$sUserName,$sDomain,$sPassword)
    try
    {  Clear-Host ""
        Write-Host "------------------------------------------------------------"  -foregroundcolor Gray
        Write-Host "Getting all Library/List Item count in a SharePoint Site" -foregroundcolor Gray
        Write-Host "-----------------------------------------------------------"  -foregroundcolor Gray
   
     $OpFilePath="Result.csv"
        #Adding the Client Object Model Assemblies  
        Add-Type -Path "Microsoft.SharePoint.Client.dll"
        Add-Type -Path "Microsoft.SharePoint.Client.Runtime.dll"

        #SPO Client Object Model Context
        $spContext = New-Object Microsoft.SharePoint.Client.ClientContext($sSiteColUrl)
        $spCredentials = New-Object System.Net.NetworkCredential($sUserName,$sPassword,$sDomain)
        $spContext.Credentials = $spCredentials

        #Root Web Site
        $spRootWebSite = $spContext.Web
        #Collecction of Sites under the Root Web Site
        $spSites = $spRootWebSite.Webs

        #Loading Operations
     
        $spContext.Load($spRootWebSite)
        $spContext.Load($spSites)

        #Get All Library and List from Root Site
        $spRootWebLists=$spRootWebSite.Lists
        #Loading Operations
        $spContext.Load($spRootWebLists)
        #QueryExecution
        $spContext.ExecuteQuery()

        #Delete File if Exists
        If(Test-Path $OpFilePath){
        Remove-Item $OpFilePath
        }

        $text =    "Site Title,Site URL ,Library/List Name ,Type,Items Count ,OverAll Count "
        #Create New File
        $text | Set-Content $OpFilePath
       

        $fCount=0

        #Print Statement
        Write-Host $spRootWebSite.Title " - " $spRootWebSite.Url -ForegroundColor Cyan
        Write-Host "------------------------------------------"  -ForegroundColor Magenta

        #Append the content into File
        $text =    $spRootWebSite.Title +","+ $spRootWebSite.Url+", , , , "
        $text | Add-Content $OpFilePath

        #We need to iterate through the $spRootWebLists Object in order to get individual Library/List information
        foreach($spRootWeblist in $spRootWebLists)
        {
            #Item Count for each Library
            Write-Host $spRootWeblist.Title " - " $spRootWeblist.ItemCount  -ForegroundColor Green
            #Sum of each Library Item Count
            $fCount=$fCount+$spRootWeblist.ItemCount
            #Append the content into File
            $text =   " , , "+ $spRootWeblist.Title +","+$spRootWeblist.BaseType+" ,"+ $spRootWeblist.ItemCount+", "
            $text | Add-Content $OpFilePath
        }
        #Overall Item Count from the Site
        Write-Host "OverAll Count : " $fCount -ForegroundColor White
        #Append the content into File
        $text =   " , , , , , "+$fCount
        $text | Add-Content $OpFilePath
           
        Write-Host "============================================="  -ForegroundColor Yellow


       #We need to iterate through the $spSites Object in order to get individual sites information
        foreach($spSite in $spSites){
            Write-Host $spSite.Title " - " $spSite.Url -ForegroundColor Cyan
            Write-Host "------------------------------------------"  -ForegroundColor Magenta
            #Append the content into File
            $text =    $spSite.Title +","+ $spSite.Url+", , , , "
            $text | Add-Content $OpFilePath

            #Get All Library and List from the Site
            $spLists=$spSite.Lists
       
            #Loading Operations
            $spContext.Load($spLists)
            #QueryExecution
            $spContext.ExecuteQuery()
            $fCount=0

            #We need to iterate through the $spRootWebLists Object in order to get individual Library/List information
            foreach($splist in $spLists)
            {
                #Item Count for each Library
                Write-Host $splist.Title " - " $splist.ItemCount  -ForegroundColor Green
                #Sum of each Library Item Count
                $fCount=$fCount+$splist.ItemCount
                #Append the content into File
                $text =   " , , "+ $splist.Title +","+$spRootWeblist.BaseType+" ,"+ $splist.ItemCount+", "
                $text | Add-Content $OpFilePath
            }
            Write-Host "OverAll Count : " $fCount -ForegroundColor White
            Write-Host "============================================="  -ForegroundColor Yellow
            #Append the content into File
            $text =   " , , , , , "+$fCount
            $text | Add-Content $OpFilePath
        }
        $spContext.Dispose()

   
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }  
}

#Required Parameters
$sSiteColUrl = "https://www.sample.com"
$sUserName = "username"
$sDomain="domainName"
$sPassword ="Password"


Get-SPAllDocCountInSiteCol -sSiteColUrl $sSiteColUrl -sUserName $sUsername -sDomain $sDomain -sPassword $sPassword

Monday, February 6, 2017

Covert DateTime format from UTC to Local time by JavaScript

1. Upload the JavaScript file in Style Library and Published.
2. Register this uploaded JavaScript in the Master Page.
3. Call the DateTime format function like below:


 dateFormat(new Date(item.ArticleStartDate), 'mm/dd/yyyy')

4. Please find the JavaScript as below: (Copy and Past the Note pad and save as "date.format.js")



var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};

// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;

// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}

// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");

mask = String(dF.masks[mask] || mask || dF.masks["default"]);

// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}

var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d:    d,
dd:   pad(d),
ddd:  dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m:    m + 1,
mm:   pad(m + 1),
mmm:  dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy:   String(y).slice(2),
yyyy: y,
h:    H % 12 || 12,
hh:   pad(H % 12 || 12),
H:    H,
HH:   pad(H),
M:    M,
MM:   pad(M),
s:    s,
ss:   pad(s),
l:    pad(L, 3),
L:    pad(L > 99 ? Math.round(L / 10) : L),
t:    H < 12 ? "a"  : "p",
tt:   H < 12 ? "am" : "pm",
T:    H < 12 ? "A"  : "P",
TT:   H < 12 ? "AM" : "PM",
Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};

return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); 
});
};
}();

// Some common format strings
dateFormat.masks = {
"default":      "ddd mmm dd yyyy HH:MM:ss",
shortDate:      "m/d/yy",
mediumDate:     "mmm d, yyyy",
longDate:       "mmmm d, yyyy",
fullDate:       "dddd, mmmm d, yyyy",
shortTime:      "h:MM TT",
mediumTime:     "h:MM:ss TT",
longTime:       "h:MM:ss TT Z",
isoDate:        "yyyy-mm-dd",
isoTime:        "HH:MM:ss",
isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};

Wednesday, July 20, 2016

Windows PowerShell - "running scripts is disabled on this system."

When I try to execute my .ps1 script in Windows PowerShell ISE window, it is throwing exception like below:

"cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
    + CategoryInfo          : SecurityError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess  "

I found the solution one the article from the Internet.

This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. 

You can do it by set the execution policy in powershell command window.

Open the Windows PowerShell with "Run as administrator" and enter the below command:

set-executionpolicy remotesigned

Thursday, April 28, 2016

How to get Image from Picture Library using REST API

I used REST API to get the Image form Picture Library and display my Banner Dynamically.

I used normal RESTful HTTP url like asusual Path and Query string param in the sequence of SELECT, FILTER and ORDER BY accordingly  but I am not able to get "EncodedAbsUrl"  in the result.

After I googled I got some idea, form some forums.

Like I used SELECT statement as a last querystring param, like below:

http://sharePointchild.com/_api/Web/Lists/GetByTitle('HomeBanner')/Items?filter=IsActive%20eq%201&$top=1&$orderby=IsActive%20desc&$select=EncodedAbsUrl

Code:

$(document).ready(function(){

var siteColUrl=_spPageContextInfo.siteAbsoluteUrl;

$.ajax({
method:"GET",
headers:{"Accept":"application/json; odata=verbose"},
url:siteColUrl+"/_api/Web/Lists/GetByTitle('HomeBanner')/Items?filter=IsActive%20eq%201&$top=1&$orderby=IsActive%20desc&$select=EncodedAbsUrl",
success: function (data) {

        completeBannerdata(data);
   }
   ,
    error: function (error) {

              failiureBannerdata(error);
         
        }

});

})

function completeBannerdata(data)
{

var items = data.d.results;
if(items.length>0)
{
       $('#imgBanner').attr('src', items[0]["EncodedAbsUrl"]);
       }
}

 function failiureBannerdata(error)
 {

 }