Quantcast
Channel: SharePoint Journey
Viewing all 542 articles
Browse latest View live

SP.js not load on Sharepoint Pages or Loading/ensuring JavaScript files

$
0
0

There is an issue I found when working on Sharepoint 2013. I got “SP.js” error right after 
published the page and cause some feature disable, such as ribbon and other scripts can
 not be executed. It seems that SP.js does not load properly for publishing page and 
anonymous users. Some articles said that sharepoint loads certain javascript files when
 it needs, after published the page, ribbon will close and several javasripts were unload 
automatically.
Actually Sharepoint provides some methods to call scripts for many conditions. So we 
could choose wisely among them to solved our problem. Take a look :
1) Script on Demand.
1
2
3
4
functionsharePointReady(){
    // call this code after load SP.js
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
2) Delay until SP.js loaded.
1
2
3
4
functionstuffToRun(){
   // code
}
ExecuteOrDelayUntilScriptLoaded(stuffToRun, "sp.js")




The different between 1 and 2:
SP.SOD.executeFunc(key, functionName, fn) method ensures that the specified file (key) 
that contains the specified function (functionName) is loaded and then runs the specified
 callback function (fn). Use case for “SP.SOD.executeFunc” can be that at some point you
 wish a JavaScript library like JQuery be loaded before you call a function defined inside it
 via callback function.
SP.SOD.executeOrDelayUntilScriptLoaded(func, depScriptFileName) method executes the
 specified function (func) if the file (depScriptFileName) containing it is loaded; otherwise, 
adds it to the pending job queue.
3) Load after other stuff finished.
1
2
3
4
functionrunAfterEverythingElse(){
    // code
}
_spBodyOnLoadFunctionNames.push("runAfterEverythingElse");





SharePoint JavaScript Library, in particular SP.SOD namespace contains methods for loading/
ensuring JavaScript files.
1.      SP.SOD.executeOrDelayUntilScriptLoaded - executes the specified function if the file containing 
it is loaded, for example:
2.  ExecuteOrDelayUntilScriptLoaded(myfunc,"SP.js");
3.        
4.       function myfunc()
5.       {
}
In that case myfunc will be invoked after sp.js file is loaded
6.      SP.SOD.executeFunc - ensures that the specified file that contains the specified function is loaded 
and then runs the specified callback function, for example:
7.  SP.SOD.executeFunc('sp.js','SP.ClientContext',
8.        function(){
9.            //your code goes here...
});
The behavior is similar to previous example but the main difference that this function also supports
 load on demand scripts.

3-If SP.js is Not Load
 Then  For User  Profile
  
$(window).load(function(){
     SP.SOD.executeFunc('sp.js', 'SP.ClientContext',init);
});

In JSOM Display GMT Time A Particular date Time in Different Location

$
0
0



<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<table>
                <tr>
                                <td>
                                                <div>India</div>
                                </td>
                                <td><input type="text" value="" id="datetimepicker"/></td>
                </tr>
                <tr>
                                <td>
                                <select id="ddlFirstCountry">
                                                <option value="Select">--Select--</option>
                                </select>
                </td>
                                <td><div id="ddlFirstCountryclock"></div></td>
                </tr>
                <tr>
                                <td>
                                                <select id="ddlSecondCountry">
                                                                <option value="Select">--Select--</option>
                                                </select>
                                </td>
                                <td><div id="ddlSecondCountryclock"></div></td>
                </tr>
                <tr>
                                <td>
                                                <select id="ddlThirdCountry">
                                                                <option value="Select">--Select--</option>
                                                </select>
                                </td>
                                <td><div id="ddlThirdCountryclock"></div></td>
                </tr>
                <tr>
                                <td>
                                                <select id="ddlFourthCountry">
                                                                <option value="Select">--Select--</option>
                                                </select>
                                </td>
                                <td><div id="ddlFourthCountryclock"></div></td>
                </tr>
                <tr>
                                <td>
                                               
                                </td>
                                <td><input value="Refresh" type="submit"/></td>
                </tr>


</table>
               
                <div id="clock_hou"></div>
               

                <div class="ms-hide">
                <WebPartPages:WebPartZone runat="server" title="loc:TitleBar" id="TitleBar" AllowLayoutChange="false" AllowPersonalization="false" Style="display:none;"><ZoneTemplate>
                <WebPartPages:TitleBarWebPart runat="server" HeaderTitle="Untitled_1" Title="Web Part Page Title Bar" FrameType="None" SuppressWebPartChrome="False" Description="" IsIncluded="True" ZoneID="TitleBar" PartOrder="2" FrameState="Normal" AllowRemove="False" AllowZoneChange="True" AllowMinimize="False" AllowConnect="True" AllowEdit="True" AllowHide="True" IsVisible="True" DetailLink="" HelpLink="" HelpMode="Modeless" Dir="Default" PartImageSmall="" MissingAssembly="Cannot import this Web Part." PartImageLarge="" IsIncludedFilter="" ExportControlledProperties="True" ConnectionID="00000000-0000-0000-0000-000000000000" ID="g_5e0ec1af_7283_43c4_b07e_43ad8b05e688" AllowClose="False" ChromeType="None" ExportMode="All" __MarkupType="vsattributemarkup" __WebPartId="{5E0EC1AF-7283-43C4-B07E-43AD8B05E688}" WebPart="true" Height="" Width=""></WebPartPages:TitleBarWebPart>

                </ZoneTemplate></WebPartPages:WebPartZone>
  </div>
  <table class="ms-core-tableNoSpace ms-webpartPage-root" width="100%">
                                                                <tr>
                                                                                <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" width="100%">
                                                                                <WebPartPages:WebPartZone runat="server" Title="loc:FullPage" ID="FullPage" FrameType="TitleBarOnly"><ZoneTemplate></ZoneTemplate></WebPartPages:WebPartZone> </td>
                                                                </tr>
                                                               
                                </table>
                                <link rel="stylesheet" type="text/css" href="../SiteAssets/jClocksGMT-master/css/jClocksGMT.css"/>
                                <link rel="stylesheet" type="text/css" href="../SiteAssets/jClocksGMT-master/css/jquery.datetimepicker.min.css"/>
                                <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
                                <script src="../SiteAssets/jClocksGMT-master/js/jquery.rotate.js"></script>
                                <script src="../SiteAssets/jClocksGMT-master/js/jClocksGMT.js"></script>
                                <script src="../SiteAssets/jClocksGMT-master/js/jquery.datetimepicker.full.js"></script>
                               
                                <script type="text/javascript">
                                var dateStart = new Date();
                                $('#datetimepicker').datetimepicker({
                                                                mask:'9999/19/39 29:59',
                                                                step:30,
                                                                yearStart:dateStart.getFullYear(),
                                                                yearEnd:(dateStart.getFullYear() +1)

                                });
                                $('select').on('change', function() {
                               
                                                                if($(this).find("option:selected").text() !='--Select--')
                                                                {
                                                                custmdatetime=$('#datetimepicker').val();
                                                                if((custmdatetime !='____/__/__ __:__') && (custmdatetime !='') )
                                                                {
                                                                                $('#'+this.id+'clock').html('');
                                                                               $('#'+this.id+'clock').jClocksGMT(
                                                {
                                title: $(this).find("option:selected").text(),
                                offset: this.value,
                                analog:false
                                });
                  }
                  else
                  {
                                alert('date can not blank!!');
                                return false;
                  }

                                }else
                                {
                                                alert('Please select right option!!');
                                                return false;
                                }
                                                //alert( this.value );
                                                //alert( this.id );
                                })
                                                $(document).ready(function(){
                                                               
                                                                var urlForAllItems = "/_api/Web/Lists/GetByTitle('globalclockMaster')/Items";
                                    BindDropDown(urlForAllItems);
                                   /*  $('#clock_hou').jClocksGMT(
                {
                    title: 'Houston, TX, USA',
                    offset: '-6',
                    analog:false,
                    custmdatetime:'October 13, 2014 12:13:00'
                });*/
                                                               
                                                });
                                               
                               
                                                function BindDropDown(url) {
               
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            //console.log(data.d.results);
            var usedNames = [];
            $.each(data.d.results, function (key, value)
                                                {
                                                                if (usedNames.indexOf(value.Company_x0020_Name) == -1) {
                                                $("#ddlFirstCountry").append("<option value=" + value.GMTOffset + ">" + value.country_title + "</option>");
                                                $("#ddlSecondCountry").append("<option value=" + value.GMTOffset + ">" + value.country_title + "</option>");
                                                $("#ddlThirdCountry").append("<option value=" + value.GMTOffset + ">" + value.country_title + "</option>");
                                                $("#ddlFourthCountry").append("<option value=" + value.GMTOffset + ">" + value.country_title + "</option>");
                                                usedNames.push(value.country_title);
                                }             
                                                });
                                                //$('#ddlCompanyName').selectpicker('refresh');
                                //$('#ddlCompanyName').selectpicker('render');
        },
        error: function (error) {
            //alert(JSON.stringify(error));
        }
    });
   
}   

                                </script>
</asp:Content>


CSS  jClocksGMT.css

.jcgmt-container {
    float:left;
    padding: 3px;
}
.jcgmt-container .jcgmt-lbl {
    font-size:10px;
    color: #333333;
    line-height: 22px;
    background: url(../images/jcgmt-clock_label.png) no-repeat;
    text-align: center;
    padding-bottom: 5px;
    width: 108px;
    margin: 0 auto;
}
.jcgmt-clockHolder {
    width:100px;
    margin:0 auto;
    position:relative;
    overflow: hidden;
}
.jcgmt-sec,
.jcgmt-min,
.jcgmt-hour {
    display:block;
    position:absolute;
}

.jcgmt-rotatingWrapper {
    position:absolute;
    width:100px;
    height:100px;
}
.jcgmt-digital,
.jcgmt-date {
    font-weight:bold;
    font-size: 12px;
    color: #444444;
    text-align:center;
    margin-left:8px;
}







Get Attachment Of List in Single Column Using Rest API

$
0
0
asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
                <meta name="GENERATOR" content="Microsoft SharePoint" />
                <meta name="ProgId" content="SharePoint.WebPartPage.Document" />
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <meta name="CollaborationServer" content="SharePoint Team Web Site" />
                <SharePoint:ScriptBlock runat="server">
                var navBarHelpOverrideKey = &quot;WSSEndUser&quot;;
                </SharePoint:ScriptBlock>
<SharePoint:StyleBlock runat="server">
body #s4-leftpanel {
                display:none;
}
.s4-ca {
                margin-left:0px;
}
</SharePoint:StyleBlock>
<style type="text/css">
#sideNavBox,#s4-titlerow,#s4-ribbonrow,#suiteBar
{
                display:none !important;
}
#contentBox
{
                margin-left:20px;
}
/*#example > thead >tr> th {
    background-color: #FFCCCC;
    color: black;
}
#example tr th {
    font-weight: bold;
    font-size: 13px;
    text-align:justify;
}
#example tr td {

                text-align:justify;
}

table tr.odd td{ background-color: white!important; }
table tr.even td{ background-color: lightgray !important; }*/
#divPostsLoader
{
                text-align:center;
                font-weight:bold;
                font-style:italic;
}
.SummeryHeader
{
                text-align:center;
                font-weight:bold;
                font-size: 17px;
    padding-bottom: 10px;
}
#example_filter
{
                margin-bottom:7px;
}
.morectnt span {
display: none;
}
/*.comment {
                width: 400px;
                background-color: #f0f0f0;
                margin: 10px;
}*/
<style type="text/css">
table#example{
                font-family: verdana,arial,sans-serif;
                font-size:11px;
                color:#333333;
                border-width: 1px;
                border-color: #666666;
                border-collapse: collapse !important;
}
table#example th {
                border-width: 1px;
                padding: 8px;
                border-style: solid;
                border-color: #666666;
                background-color: #dedede;
}
table#example td {
                border-width: 1px;
                padding: 8px;
                border-style: solid;
                border-color: #666666;
                background-color: #ffffff;
}
table.dataTable.no-footer
{
                border-collapse:collapse !important;
}

</style>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderSearchArea" runat="server">
                <SharePoint:DelegateControl runat="server"
                                ControlId="SmallSearchInputBox"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
                <SharePoint:ProjectProperty Property="Description" runat="server"/>
               
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

<script type="text/javascript" src="../SiteAssets/script/jquery.min.js"></script>
<link href="../SiteAssets/bootstrap/jquery.dataTables.min.css" rel="stylesheet" type="text/css"/>
 <script src="../SiteAssets/bootstrap/jquery.dataTables.min.js" type="text/javascript"></script>

                <script type="text/javascript">
                var monthNames = [
    "Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul",
    "Aug", "Sep", "Oct",
    "Nov", "Dec"
];

                var urlForAllItems = "/_api/web/lists/getbytitle('NGO_App_List')/items?$Select=Category,Modified,BusinessSegment,AppOwners/Title,QueueName,Technology,ProcessArea,Domain,AppShortName,AppFullName,AppDescription,Attachments,AttachmentFiles,Editor/Title&$expand=AttachmentFiles,Editor,AppOwners";
                getItems(urlForAllItems);
                                function getItems(url) {
                                                $('#divPostsLoader').html('loading.....');
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
                    var vtble="";
                    var srNO=1;
                    vtble +="<table id=\"example\" class=\"table table-striped table-bordered\" cellspacing=\"0\" width=\"100%\">";
                    vtble +='<thead>';
                    vtble +="<tr>";
                   // vtble +="<th style=\"width:20px !important;\">Sr.No.</th>";
                    vtble +="<th>Category</th>";
                                vtble +="<th>App Short Name</th>";
                                vtble +="<th>App Full Name</th>";
                                vtble +="<th>App Description</th>";
                                vtble +="<th>Domain / Industry</th>";
                                vtble +="<th>Process Area</th>";
                                vtble +="<th>Technology</th>";
                                vtble +="<th>Overview – Document attach</th>";
                                vtble +="<th>Queue Name</th>";
                                vtble +="<th>App Owners</th>";
                                vtble +="<th>Business Segment</th>";
                                vtble +="<th>Last updated date</th>";
                                vtble +="<th>Last updated by</th>";
            vtble +="</tr>";
                vtble +='</thead>';
                                                                                                vtble +='<tbody>';
                $.each(data.d.results, function(index, item){
               
                vtble +="<tr>";
              //  vtble +="<td>"+srNO+".</td>";
                vtble +="<td>"+item.Category+"</td>";
                vtble +="<td>"+item.AppShortName+"</td>";
                vtble +="<td>"+item.AppFullName+"</td>";
                vtble +="<td><div class=\"show\">"+item.AppDescription+"</div></td>";
                vtble +="<td>"+item.Domain+"</td>";
                vtble +="<td>"+item.ProcessArea+"</td>";
                vtble +="<td>";
                $.each(item.Technology.results, function(index, Techresults){
               
                                vtble +="<div>"+Techresults+"</div>";
               
                });
                vtble +="</td>";
                var isAttachment="false";
                vtble +="<td>";
                $.each(item.AttachmentFiles.results, function(index, Attach){
               
                                isAttachment="true";   
                                vtble +="<div><a target=\"_blank\" href=\""+Attach.ServerRelativeUrl+"\">"+Attach.FileName+"</a></div>";
               
                });
               
                if(isAttachment=="false")
                {
                                vtble +="No Attachment";
                }
                vtble +="</td>";
               
                
                vtble +="<td>"+item.QueueName+"</td>";
                vtble +="<td>"+item.AppOwners.Title+"</td>";
                vtble +="<td>"+item.BusinessSegment+"</td>";
                vtble +="<td>"+item.Editor.Title+"</td>";
                var dateCreated = new Date(item.Modified);
                vtble +="<td>"+ dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() +"</td>";
                vtble +="</tr>";
                srNO=srNO +1;
            });
            vtble +='</tbody>';
            vtble +="</table>";
            $('#NGOapp').html(vtble);
            table= $('#example').DataTable( {     
         "paging": true,
         "info": false,        
         "lengthChange":false,
         "pageLength": 10 
                });
                showmoreless();
                $('#divPostsLoader').empty();
            console.log(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}
               
               
                function fnExcelReport()
    {
             var tab_text="<table border='2px'><tr bgcolor='#FFCCCC'>";
             var textRange; var j=0;
                 tab = document.getElementById('example'); // id of table


          for(j = 0 ; j < tab.rows.length ; j++)
          {    
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }

          tab_text=tab_text+"</table>";
          tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
                      tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

               var ua = window.navigator.userAgent;
              var msie = ua.indexOf("MSIE ");

                 if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                    {
                           txtArea1.document.open("txt/html","replace");
                           txtArea1.document.write(tab_text);
                           txtArea1.document.close();
                           txtArea1.focus();
                            sa=txtArea1.document.execCommand("SaveAs",true,"NGOappsummery.xls");
                          } 
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); 


                      return (sa);
            }
       


function showmoreless()
{
                var showTotalChar = 50, showChar = "more", hideChar = "less";
$('.show').each(function() {
var content = $(this).text();
if (content.length > showTotalChar) {
var con = content.substr(0, showTotalChar);
var hcon = content.substr(showTotalChar, content.length - showTotalChar);
var txt= con +  '<span class="dots">...</span><span class="morectnt"><span>' + hcon + '</span>&nbsp;&nbsp;<a href="" class="showmoretxt">' + showChar + '</a></span>';
$(this).html(txt);
}
});
$(".showmoretxt").click(function() {
if ($(this).hasClass("sample")) {
$(this).removeClass("sample");
$(this).text(showChar);
} else {
$(this).addClass("sample");
$(this).text(hideChar);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
}

                </script>
                <div id="divPostsLoader"></div>
                <div class="SummeryHeader" id="ApplicationHeader">NGO Application Summery</div>
               
                <div style=" border-bottom:1px solid gray;"></div>
                <div style="margin-bottom:10px;">
                                <a style="float:right; color:red;font-weight:bold; text-decoration:none;margin-bottom:7px;margin-top:7px; font-style:italic;" href="javascript:void(0);" onclick="fnExcelReport()">
                                Export To Excel</a>
                </div>
                <div id="NGOapp"></div>
                <iframe id="txtArea1" style="display:none"></iframe>

                <div class="ms-hide">
                <WebPartPages:WebPartZone runat="server" title="loc:TitleBar" id="TitleBar" AllowLayoutChange="false" AllowPersonalization="false" Style="display:none;"><ZoneTemplate>
                <WebPartPages:TitleBarWebPart runat="server" HeaderTitle="Untitled_1" Title="Web Part Page Title Bar" FrameType="None" SuppressWebPartChrome="False" Description="" IsIncluded="True" ZoneID="TitleBar" PartOrder="2" FrameState="Normal" AllowRemove="False" AllowZoneChange="True" AllowMinimize="False" AllowConnect="True" AllowEdit="True" AllowHide="True" IsVisible="True" DetailLink="" HelpLink="" HelpMode="Modeless" Dir="Default" PartImageSmall="" MissingAssembly="Cannot import this Web Part." PartImageLarge="" IsIncludedFilter="" ExportControlledProperties="True" ConnectionID="00000000-0000-0000-0000-000000000000" ID="g_000aee6f_98fc_4163_906d_bfead211f9e8" AllowClose="False" ChromeType="None" ExportMode="All" __MarkupType="vsattributemarkup" __WebPartId="{000AEE6F-98FC-4163-906D-BFEAD211F9E8}" WebPart="true" Height="" Width=""></WebPartPages:TitleBarWebPart>

                </ZoneTemplate></WebPartPages:WebPartZone>
  </div>
  <table class="ms-core-tableNoSpace ms-webpartPage-root" width="100%">
                                                                <tr>
                                                                                <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" width="100%">
                                                                                <WebPartPages:WebPartZone runat="server" Title="loc:FullPage" ID="FullPage" FrameType="TitleBarOnly"><ZoneTemplate></ZoneTemplate></WebPartPages:WebPartZone> </td>
                                                                </tr>
                                                                <SharePoint:ScriptBlock runat="server">
                                                                if(typeof(MSOLayout_MakeInvisibleIfEmpty) == &quot;function&quot;)
                                                               
                                                               
                                                               
                                                               
                                                               
                                                                {MSOLayout_MakeInvisibleIfEmpty();}</SharePoint:ScriptBlock>
                                </table>
</asp:Content>

Get LDAP User Information Using C# with LDAP Connection

$
0
0
string txtEmp;
            string sa = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            txtEmp = sa.Split('\\')[1];
            string strDLdap = ConfigurationManager.AppSettings["myLDAPString"].ToString();
            DirectoryEntry connection = new DirectoryEntry(strDLdap);
            string strDLdAPUser = ConfigurationManager.AppSettings["myLDAPUser"].ToString();
            string strDLdAPPass =ConfigurationManager.AppSettings["myLDAPPassword"].ToString();
            connection.AuthenticationType = AuthenticationTypes.Secure;
            connection.Username = strDLdAPUser;
            connection.Password = strDLdAPPass;
            DirectorySearcher dssearch = new DirectorySearcher(connection);
            dssearch.Filter = "(sAMAccountName=" + txtEmp + ")";
            SearchResult sresult = dssearch.FindOne();
            DirectoryEntry dsresult = sresult.GetDirectoryEntry();
            string strfirstName = dsresult.Properties["givenName"][0].ToString();
            string strlastName = dsresult.Properties["sn"][0].ToString();
            string Name = strfirstName + "" + strlastName;
            string strRequestedBy = dsresult.Properties["mail"][0].ToString();
            string strComapnay = dsresult.Properties["company"][0].ToString();
            displayName = dsresult.Properties["displayName"][0].ToString();
            InsertUserInfo(displayName, strComapnay, DateTime.Now.ToString("MM-dd-yyyy"), strRequestedBy);
 

Get All Group Name using JSOM And Rest Api Of SharePoint Site

$
0
0
JSOM
 
<input type='button' value='Get All Groups' onclick="clickMethod();"/>
<br />
 
<script language="javascript" type="text/javascript">
var siteGroups ='';
function clickMethod() {
  
var clientContext = new SP.ClientContext.get_current();
 
siteGroups = clientContext.get_web().get_siteGroups();
clientContext.load(siteGroups);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
 
function onQuerySucceeded() {
 
var allGroups='Group Name:       Group ID '+'\n';
for (var i =0 ; i < siteGroups.get_count(); i++)
{
allGroups +=siteGroups.itemAt(i).get_title()+'       '+siteGroups.itemAt(i).get_id()+'\n';
}
console.log(allGroups);
}
function onQueryFailed() {
   
alert('Request failed.');
}
</script>\
 
 
 
Rest Api
 
http://s07ngo:40072/_api/web/roleassignments/groups
 

Document Set Download as a ZIP FOLDER Using OOB

$
0
0


Document Set Download as a ZIP FOLDER Using OOB

One Of the Benifits of using document sets in SharePoint 2010,2013 is that it treats a single item and all its related documents as a workset. Means we can upload all documents related to an item inside itself. In Other words Document sets is a content type that acts as a container for the related documents for an item.

I come to know about the requirement related to download all the document from the document set.

So here is the key: we need to form the Url as below:

{SiteUrl}/_layouts/DocSetExport.aspx?List={ListId}&ID={ItemId}


Download the file from Document Library

SiteUrl}/_layouts/15/download.aspx?SourceUrl={ListName}/{FileName}

and rest of the things SharePoint will automatically manage.

Send Email to TO CC,BCC Using SP.Utilities.Utility and SMPT C# and Rest API

$
0
0
C#
  
public void SendEmailSMPT(string Email, string ApprovalName, string DocumentName, stringstrMessage, string SubjectBody)
        {
            SPWebApplication webApp = SPContext.Current.Site.WebApplication;
            // SPWebApplication webApp = this.Parent as SPWebApplication;
            SPWeb web = webApp.Sites[0].RootWeb;
            string mailFrom = webApp.OutboundMailSenderAddress;
            string smtpAddress = webApp.OutboundMailServiceInstance.Server.Address;
            string mailTo = string.Empty;
            string mailCc = string.Empty;
            string mailBcc = string.Empty;
            string mailSubject = SubjectBody;
            string mailBody = strMessage;
            bool blnIsBodyHTML = true;
            bool mailSent = false;
            SmtpClient smtpClient = null;
            if (Email != "")
            {
                try
                {
                    // Assign SMTP address
                    string BEPSBCCUser = System.Web.Configuration.WebConfigurationManager.AppSettings["BEPSBCCUser"].ToString();
                    smtpClient = new SmtpClient();
                    smtpClient.Host = smtpAddress;
 
                    //Create an email message
                    MailMessage mailMessage = new MailMessage();
                    MailAddress mailAddressFrom = new MailAddress(mailFrom);
                    mailMessage.From = mailAddressFrom;
 
                    if (String.IsNullOrEmpty(mailTo))
                    {
                        MailAddress mailAddressTo = new MailAddress(Email);
                        mailMessage.To.Add(mailAddressTo);
                    }
                    else
                    {
                        MailAddress mailAddressTo = new MailAddress("sRam@ngo.com");
                        mailMessage.To.Add(mailAddressTo);
                    }
 
 
                    if (!String.IsNullOrEmpty(BEPSBCCUser))
                    {
                        string[] arrMailIDs = mailCc.Split(';');
                        for (int i = 0; i < arrMailIDs.Length; i++)
                        {
                            MailAddress mailAddressCc = new MailAddress(arrMailIDs[i]);
                            mailMessage.CC.Add(mailAddressCc);
                        }
                    }
                    else
                    {
 
                        
                        MailAddress mailAddressTo = new MailAddress("Ram@ngo.com");
                        mailMessage.To.Add(mailAddressTo);
                    }
 
                    if (!String.IsNullOrEmpty(mailBcc))
                    {
                        string[] arrMailIDs = mailBcc.Split(';');
                        for (int i = 0; i < arrMailIDs.Length; i++)
                        {
                            MailAddress mailAddressBcc = new MailAddress(arrMailIDs[i]);
                            mailMessage.Bcc.Add(mailAddressBcc);
                        }
                    }
 
 
                    mailMessage.Subject = mailSubject;
                    mailMessage.Body = mailBody;
                    mailMessage.IsBodyHtml = blnIsBodyHTML;
                    mailMessage.Priority = MailPriority.Normal;
 
                    // Send the email
                    smtpClient.Send(mailMessage);
                    mailSent = true;
                }
                catch (Exception)
                {
                    //mailSent = false;
                    ////webApp = this.Parent as SPWebApplication;
                    //SPList taskList = spWeb.Lists["Mate_Error_Notification"];
                    //SPListItem newTask = taskList.Items.Add();
                    //newTask["Title"] = "" + Title + "";
                    //newTask["ErrorDiscription"] = "Error in sending email";
                    //newTask.Update();
 
                }
            }
            else
            {
                //webApp = this.Parent as SPWebApplication;
                //SPList taskList = webApp.Sites[0].RootWeb.Lists["Mate_Error_Notification"];
                //SPListItem newTask = taskList.Items.Add();
                //newTask["Title"] = "" + Title + "";
                //newTask["ErrorDiscription"] = "EmailId is not in group ";
                //newTask.Update();
            }
 
        }
        #endregion
        #region Bind HTML Body of items
        public void BindHtml(string DocumentName, string CreaterName, string ActionBy, stringAprrovedRejectText, string AprrovedRejectComment, string OptenTabType)
        {
            string imagepath = "SiteAssets/Images/tp-1.jpg?ver=1.0";
            string footerpath = "SiteAssets/Images/footer-2.png?ver=1.0";
            strMessage.Append("<div align=\"center\" style='font-family:Calibri'>");
            strMessage.Append("<table width = \"580\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">");
            strMessage.Append("<tr>");
            strMessage.Append("<td bgcolor = \"#efeff0\"><img src = \"" + siteurl + "" + "/" +"" + imagepath + "" + "\" width = \"580\" height = \"222\" alt = \"\" /></ td >");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td><table width = \"580\"  border = \"0\" cellspacing = \"0\" cellpadding = \"0\">");
            strMessage.Append("<tr>");
            strMessage.Append("<td align =\"center\" valign = \"top\" bgcolor = \"#efeff0\"><table width = \"85%\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">");
            strMessage.Append("<span style=\"font-weight: bold \">Dear " + CreaterName + "</span>");
            strMessage.Append("<tr>");
            strMessage.Append("<td>The uploaded document <a href =\"" + siteurl + "" + "/" +"SitePages/Default.aspx?FN=" + "" + LibraryName + "/" + HdnFolder.Value + "" + "/" + OptenTabType + "\" target=\"new\">" + DocumentName.ToUpper() + "</a> has been  " + AprrovedRejectText + "  by " + ActionBy + " . </td>");
            strMessage.Append("</tr>");
            //strMessage.Append("<tr>");
            //strMessage.Append("<td>Kindly review the same.(Document : <a href=\"" + siteurl + "" + "/" + "SitePages/MDL.aspx?FN=" + "" + LibraryName + "/" + HdnFolder.Value + "" + "/" + OptenTabType + "\" target=\"new\">" + DocumentName.ToUpper() + "</a>  )</td>");
            //strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td style=\"height:10px;\"></td>");
            strMessage.Append("</tr>");
            if (txtComment.Text != "")
            {
                strMessage.Append("<tr>");
                strMessage.Append("<td><span style=\"font-weight: bold \">" + AprrovedRejectComment + "</span></br> " + txtComment.Text + "</td>");
                strMessage.Append("</tr>");
            }
            strMessage.Append("<tr>");
            strMessage.Append("<td style=\"height:10px;\"></td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<p><td > Thanks & Regards  </td></p>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td > NGO Document Management Admin </td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td><span style=\"font-size:12.0pt\"><a href=\"mailto: Ram@ngo.com \">Ram@ngo.com</a></span></p></td>");
            strMessage.Append("</tr>");
            strMessage.Append("</table></td>");
            strMessage.Append("</tr>");
            strMessage.Append("</table>");
            strMessage.Append("</td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td align = \"center\" bgcolor = \"#efeff0\" style = \" height:30px\"></td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
          
            strMessage.Append("<td align = \"center\" bgcolor = \"#e91d24\" style = \" height:50px\"><img src = \"" + siteurl + "" + "/" + "" + footerpath + "" + "\" width =\"274\" height = \"28\" alt = \"\" /></td >");
            strMessage.Append("</tr>");
            strMessage.Append("</table>");
            strMessage.Append("</div>");
 
        }
        #endregion

REST API:

           Var EmailTo="r@ngo.com";
           var EmailCC=" r@ngo.com ";
            var EmailBCC=" r@ngo.com;Ram.Vinay@ngo.com";
           var htmlBody= BindHtml(DocumentName,AprrovedRejectText,AprrovedRejectComment, OptenTabType,ItemFolderLocation,CreatedBy);
           sendEmail("ngo@ngo.com",CreatedUserEmailId,htmlBody,AprrovedRejectSubject, EmailBCC,EmailCC);  
 
function sendEmail(from, to, body, subject,bcc,cc) {
     console.log(to);
    var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
    var formDigest = document.getElementById("__REQUESTDIGEST").value;
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: 'POST',
        async:false,
        data: JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': from,
                'To': { 'results': [to] },
                'CC': { 'results': [cc] },
                'BCC': { 'results': [bcc] },
                'Subject': subject,
                'Body': body
            }
        }
      ),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": formDigest
        },
        success: function (data) {
        alert('Yes');
          //  var result = data.d.results;
           // var i = result.length;
        },
        error: function (err) {
            alert(JSON.stringify(err));
        }
    });
}
 
 
function BindHtml(DocumentName,AprrovedRejectText,AprrovedRejectComment,OptenTabType,ItemFolderLocation,CreatedBy)
  {
            var strBody = "";
            var imagepath = "SiteAssets/Images/tp-1.jpg?ver=1.0";
            var footerpath = "SiteAssets/Images/footer-2.png?ver=1.0";
            var siteurl="http://s07ssharv008lvs:40072";
            strBody += "<div align=\"center\" style='font-family:Calibri'>";
            strBody += "<table width = \"580\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">";
            strBody += "<tr>";
            strBody += "<td bgcolor = \"#efeff0\"><img src = \"" + siteurl + "" + "/" + "" + imagepath + "" + "\" width = \"580\" height = \"222\" alt = \"\" /></ td >";
           strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td><table width = \"580\"  border = \"0\" cellspacing = \"0\" cellpadding = \"0\">";
            strBody += "<tr>";
            strBody += "<td align =\"center\" valign = \"top\" bgcolor = \"#efeff0\"><table width = \"85%\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">";
            strBody += "<span style=\"font-weight: bold \">Dear " + CreatedBy + "</span>";
            strBody += "<tr>";
            strBody += "<td>The uploaded document <a href =\"" + siteurl + "" + "/" + "SitePages/Default.aspx?FN="+ encodeURI(ItemFolderLocation) + "" + "/" + OptenTabType + "\" target=\"new\">" + DocumentName.toUpperCase()+ "</a> has been  " + AprrovedRejectText + "  by " + $('#userIdLogin').text()+ " . </td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td style=\"height:10px;\"></td>";
            strBody += "</tr>";
            if (txtComment.Text != "")
            {
                strBody += "<tr>";
                strBody += "<td><span style=\"font-weight: bold \">" + AprrovedRejectComment + "</span></br> " + $('#txtComment').val()+ "</td>";
              
 
                strBody += "</tr>";
            }
            strBody += "<tr>";
            strBody += "<td style=\"height:10px;\"></td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<p><td > Thanks & Regards  </td></p>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td > NGO Document Management Admin </td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td><span style=\"font-size:12.0pt\"><a href=\"mailto:ngo@ngo.com \">ngo@ngo.com</a></span></p></td>";
            strBody += "</tr>";
            strBody += "</table></td>";
            strBody += "</tr>";
            strBody += "</table>";
            strBody += "</td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td align = \"center\" bgcolor = \"#efeff0\" style = \" height:30px\"></td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td align = \"center\" bgcolor = \"#e91d24\" style = \" height:50px\"><img src = \"" + siteurl + "" + "/" + "" + footerpath + "" + "\" width =\"274\" height = \"28\" alt = \"\" /></td >";
            strBody += "</tr>";
            strBody += "</table>";
            strBody += "</div>";
           
            return strBody;
  }
  function onUpdateDocSuccess()
  {       
  //alert('Update Success');
  }
  function onUpdateDocFail()
  {
   alert('Failed ');
  }
 

Filtering Items by Date Range using SharePoint 2013 REST API

$
0
0
If we  are using ListData.svc then the following query for filtering the data.

http://<Site URL>/_vti_bin/ListData.svc/Events?$select=Id,Title,StartTime,EndTime,AllDayEvent&$filter=StartTime ge datetime'2013-06-10' and EndTime lt datetime'2013-06-12'

 If we  are using REST API then the following query for filtering the data.

http://<Site URL>/_api/web/lists/getbytitle('events')/items?$select=Id,Title,Description,EventDate,EndDate,fAllDayEvent,Date3&$filter=Date3 ge datetime'2013-06-13T00:00:00Z' and Date3 le datetime'2013-06-14T00:00:00Z'


http://rambabuinsharepoint.blogspot.in/

Bind Dropdown and Dropdown selection change Event /Bind data in Table and Hyper link and Search Operation and Export to excel

$
0
0
SearchPage.aspx
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
                <SharePoint:ListItemProperty Property="BaseName" maxlength="40" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
                <meta name="GENERATOR" content="Microsoft SharePoint" />
                <meta name="ProgId" content="SharePoint.WebPartPage.Document" />
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <meta name="CollaborationServer" content="SharePoint Team Web Site" />
                <SharePoint:ScriptBlock runat="server">
                var navBarHelpOverrideKey = &quot;WSSEndUser&quot;; </SharePoint:ScriptBlock>
<SharePoint:StyleBlock runat="server">
body #s4-leftpanel {
                display:none;
}
.s4-ca {
                margin-left:0px;
} </SharePoint:StyleBlock>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderSearchArea" runat="server">
                <SharePoint:DelegateControl runat="server"
                                ControlId="SmallSearchInputBox"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
                <SharePoint:ProjectProperty Property="Description" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
                <script type="text/javascript" src="../SiteAssets/ITISGScripts/Jquery1.12.4.js"></script>
                                <link href="../SiteAssets/bootstrap/jquery.dataTables.min.css" rel="stylesheet" type="text/css"/>
                <script src="../SiteAssets/bootstrap/jquery.dataTables.min.js" type="text/javascript"></script>
<link type="text/css" href="../SiteAssets/NGOGCSS/DefaultSettings.css" rel="stylesheet"/>
<link href = "../SiteAssets/NGOScripts/jquery-ui.css" rel = "stylesheet">
<script src = "../SiteAssets/NGOScripts/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="../SiteAssets/bootstrap/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="../SiteAssets/bootstrap/bootstrap-select.min.css"/>
    <script type="text/javascript" src="../SiteAssets/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript" src="../SiteAssets/bootstrap/bootstrap-select.min.js"></script>
  
    
<style type="text/css">
#SearchTable
{
border-style:solid;
border-color:#da2128;
width:100%;
}
#example_length
{
                display:none !important;
}
#SearchTable tr td
{
                padding-bottom:10px;
}
#example
{
                font-size:12px;
}
#example tr th
{
                font-weight:bold;
                font-size:13px;
}
#example_filter
{
                float:right;
                padding-right:1%;
               
}
#example > thead >tr> th
{
                background-color: #FFCCCC;
    color: black;   
}
#gridTable
{
                width:100%;
}
.multiselect.dropdown-toggle.btn.btn-default > div.restricted {
    margin-right: 5px;
    max-width: 100px;
    overflow: hidden;
}
.btnClass
{
                width: 150px !important;
    background: #da2128 !important;
    color: white !important;
   
}
.CRDeatailsCss
{
                color:#ff501e !important;
}
.lefthead
{
                font-weight:bold;
}
.selectClass
{
                width:150px !important;
               
}
.textboxClass
{
                width:150px !important;
               border:1px solid #ccc !important;
}
.paging-nav {
  text-align: right;
  padding-top: 2px;
}
.paging-nav a {
  margin: auto 1px;
  text-decoration: none;
  display: inline-block;
  padding: 1px 7px;
  background:#6d6e71;
  color: white;
  border-radius: 3px;
}
.paging-nav .selected-page {
  background-color: #ff501e !important;
  font-weight: bold;
}
.paging-nav,
#tableData {
  width: 400px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}
#tablepaging td:nth-of-type(6) a
{
                color:#ff501e !important;
}
#SearchTable tr td
{
                width:33.33%;
                text-align:center;
}
.tdLeft
{
                float: left;
    padding-top: 5px;
    width: 150px;
    font-weight:bold;
    font-size:13px;
}
table tr.odd td{ background-color: white!important; }
table tr.even td{ background-color: lightgray !important; }
#divPostsLoader
{
                text-align:center;
                font-weight:bold;
                font-style:italic;
}
</style>
<div id="SearchBar">
                <table id="SearchTable">
                                <tr>
                                                <td>
                                                                <div class="tdLeft">Technology</div>
                                                                <div><select class="selectpicker selectClass" data-live-search="true"  id="ddltechnology" name="technology">
                                                <option value="All">--All--</option></select></div>
                                                </td>
                                                <td>
                                                                                <div class="tdLeft">Technology Description</div>
                                                                                <div><select class="selectpicker selectClass" data-live-search="true"  id="ddltechnologydesc" name="technologydesc">
                                                <option value="Select">--Select--</option></select></div>
                                                </td>
                                                <td>
                                                                <div class="tdLeft">Site</div>
                                                                <div><select  class="selectpicker selectClass" data-live-search="true" id="ddlSites" name="sites">
                                                                <option value="All">--All--</option></select></div>
                                                </td>
                                               
                                                </tr>
                                                <tr>
                                                <td>
                                                                <div class="tdLeft">From:</div>
                                                                <div><input class="textboxClass" type="text" id="fromDate"/></div>
                                                </td>
                                                <td>
                                                                                <div class="tdLeft">To:</div>
                                                                                <input class="textboxClass" type="text" id="toDate"/>
                                                </td>
                                                <td>
                                                <div class="tdLeft"></div>
                                                <div><input type="button" id="btnsubmit" class="btnClass" title="Submit Search" onclick="GetFilteredData()" name="Submit Search" value="Submit Search" /></div>
                                                </td>
                                               
                                </tr>
                               
                                <tr style="display:none">           
                                                <td>
                                                Enter CR Number
                                                </td>
                               
                                                <td  style="width:250px;padding:5px">
                                                <input style="display:none" type="text" id="txtcrnumber" />
                                                </td>                   
                                </tr>
                                <tr>
                                                <td></td>
                                                <td style="padding:5px">
                                                                               
                                                </td>
                                </tr>
                               
                </table>
                <div style="margin-bottom:5px;">
                                <a style="float:right; color:red;font-weight:bold; text-decoration:none;" href="javascript:void(0);" onclick="fnExcelReport()">
                                Export To Excel</a>
                </div>
                <div  style=" border-bottom:1px solid gray;margin-bottom:10px;"></div>
                <table id="gridTable">
                                <tr>
                                                <td>
                                                                <div id="ChartDraw" style="/* width:50% !important; *//* width: 60% !important; */">
                                                                                <div id="GridTableResult">
                                                                                               
                                                                               </div>
                                                                               <div id="divPostsLoader"></div>
                                                   </div>
                                                </td>
                                </tr>
                </table>
</div>
<iframe id="txtArea1" style="display:none"></iframe>
<script type="text/javascript" src="../SiteAssets/NGOScripts/NGOSearchFinal.js"></script>
</asp:Content>
NGOSearchFinal.js
var CQuery="";
var queryCount=0;
var RowCount = 3;
var monthNames = [
    "Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul",
    "Aug", "Sep", "Oct",
    "Nov", "Dec"
];
var clientContext = null;
var web = null;
var table=null;
$( document ).ready(function() {
    ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
  
});
function Initialize()
{
                $('#divPostsLoader').html('loading.....');
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("lst_NGOCRDetails");
var camlQuery = new SP.CamlQuery();
var q = '<View></View>';
camlQuery.set_viewXml(q);
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems);
var list = web.get_lists().getByTitle("lst_NGOTechnologies");
var camlQuery = new SP.CamlQuery();
var q = '<View/>';
camlQuery.set_viewXml(q);
this.listItemsTech = list.getItems(camlQuery);
clientContext.load(listItemsTech);
var list = web.get_lists().getByTitle("lst_NGOSites");
var camlQuery = new SP.CamlQuery();
var q = '<View/>';
camlQuery.set_viewXml(q);
this.listItemsSite = list.getItems(camlQuery);
clientContext.load(listItemsSite);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onListItemsLoadSuccess(sender, args) {
                var listEnumerator = this.listItems.getEnumerator();
                var listEnumeratorTech = this.listItemsTech.getEnumerator();
                var listEnumeratorSite = this.listItemsSite.getEnumerator();
                var htmlbody='';
               
                while (listEnumeratorTech.moveNext()) {
                     var lstitemTech = listEnumeratorTech.get_current();
                                $("#ddltechnology").append("<option value=" + lstitemTech.get_item("Title") + ">" + lstitemTech.get_item("Title") + "</option>");
        }
                                while (listEnumeratorSite.moveNext()) {
                     var lstitemSite = listEnumeratorSite.get_current();
                                $("#ddlSites").append("<option value=" + lstitemSite.get_item("Title") + ">" + lstitemSite.get_item("Title") + "</option>");
        }
        $('#ddltechnology').selectpicker('refresh');
                $('#ddltechnology').selectpicker('render');      
                $('#ddlSites').selectpicker('refresh');
                $('#ddlSites').selectpicker('render');       
                                                                                                htmlbody +='<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">';
                                                                                                htmlbody +='<thead>';
                                                                                                htmlbody +='<tr>';
                                                                                                                htmlbody +='<th>CR Number</th>';
                                                                                                                htmlbody +='<th>Technology</th>';
                                                                                                                htmlbody +='<th>Technology Description</th>';
                                                                                                                htmlbody +='<th>Site Name</th>';
                                                                                                                htmlbody +='<th>CR Detail</th>';
                                                                                                                htmlbody +='<th>Created by</th>';
                                                                                                                htmlbody +='<th>Created Date</th>';
                                                                                                htmlbody +='</tr>';
                                                                                                htmlbody +='</thead>';
                                                                                                htmlbody +='<tbody>';
                                                                                               
                                                                                               
                //iterate though all of the items
                while (listEnumerator.moveNext()) {
                     var lstitem = listEnumerator.get_current();
                    // alert(lstitem.get_item('CRNumber'));
                                 
                                                var fieldUserValueCreatedBy = lstitem.get_item("Author");
                                                                var dateCreated = new Date(lstitem.get_item('Created'));
                                                                htmlbody+='<tr>';
                                 htmlbody+= '<td>'+ lstitem.get_item('CRNumber')+ '</td>';
                                 htmlbody+= '<td>'+ lstitem.get_item('Technology')+ '</td>'; 
                                 htmlbody+= '<td>'+ lstitem.get_item('TechnologyDescription')+ '</td>';
                                 htmlbody+= '<td>'+ lstitem.get_item('SiteName')+ '</td>';
                               //  console.log(lstitem.get_item("RedirectionUrl").get_url());
                               try {
                                                lstitem.get_item("RedirectionUrl").get_url()
                                                                                htmlbody+= '<td><a class="CRDeatailsCss" href="'+ lstitem.get_item("RedirectionUrl").get_url() + '">CR Detail</a></td>';
                                                                                }
                                                                                catch(err) {
                                                                                                htmlbody+= '<td><a class="CRDeatailsCss" href="#">CR Detail</a></td>';            
                                                                                                }
                                
                                 htmlbody+= '<td>'+ fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                                 htmlbody+= '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() +  '</td>';
                             htmlbody+='</tr>';
                               
        }
                                                                htmlbody +='</tbody>';
                                                                                    htmlbody +='</table>';
        $('#GridTableResult').html(htmlbody);
       //table= $('table#example').DataTable({"lengthMenu": [20],"pagingType": "full_numbers"});
       table= $('#example').DataTable( {     
         "searching": false,
         "paging": true,
         "info": false,        
         "lengthChange":false,
         "pageLength": 20
    } );
    $('#divPostsLoader').empty();
       
       
               
}
               
function onQueryFailed(sender, args) {
                //alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function BindSiteAreaDropDown(Technology)
{
                clientContext = new SP.ClientContext.get_current();
                web = clientContext.get_web();
                var list = web.get_lists().getByTitle("lst_TechnologyDetail");
                var camlQuery = new SP.CamlQuery();
                var q = '<View><Query><Where><Eq><FieldRef Name=\'Title\' /><Value Type=\'Text\'>'+Technology+'</Value></Eq></Where></Query></View>';
                camlQuery.set_viewXml(q);
                this.listItems = list.getItems(camlQuery);
                clientContext.load(listItems);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.onSiteAreaSuccess),Function.createDelegate(this, this.onSiteAreaFailed));
}
function onSiteAreaSuccess()
{
                var listEnumerator = this.listItems.getEnumerator();
                var usedNames = [];
                $('#ddltechnologydesc').empty();
                $("#ddltechnologydesc").append("<option value=\"Select\">--Select--</option>");
                while (listEnumerator.moveNext()) {
                     var lstitem = listEnumerator.get_current();
                                if (usedNames.indexOf(lstitem.get_item("TechnologyDescription")) == -1) {
                                                                $("#ddltechnologydesc").append("<option value=\""+ lstitem.get_item("TechnologyDescription") +"\">" + lstitem.get_item("TechnologyDescription") + "</option>");
                                                                usedNames.push(lstitem.get_item("TechnologyDescription"));
                                                }             
        }
        
                                                $('#ddltechnologydesc').selectpicker('refresh');
                                $('#ddltechnologydesc').selectpicker('render');      
}
function onSiteAreaFailed(sender, args)
{
                //alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
$("#ddltechnology").change(function(){
                                var  TechName = this.value;
                                BindSiteAreaDropDown(TechName);
               
    });
///Bind Drop down
$("#fromDate").datepicker({ dateFormat: 'yy-mm-dd' });
$("#toDate").datepicker({ dateFormat: 'yy-mm-dd' });
function GetFilteredData()
{
                queryCount=0;
                CQuery="";
               
                if(($('#ddltechnology').val()=='All') && ($('#ddlSites').val()=='All') && ($('#ddltechnologydesc').val()=='Select') && ($('#fromDate').val().length == 0) && ($('#toDate').val().length == 0))
                {
                                bindGrid();
                }
                if($('#ddltechnology').val()!='All')
                {
                                queryCount=queryCount+1;
                                CQuery +="<Eq><FieldRef Name='Technology' /><Value Type='Text'>"+$('#ddltechnology').val()+"</Value></Eq>;";
                }
                if($('#ddlSites').val()!='All')
                {
                                queryCount=queryCount+1;
                                CQuery +="<Eq><FieldRef Name='SiteName' /><Value Type='Text'>"+$('#ddlSites').val()+"</Value></Eq>;";
                }
                if($('#ddltechnologydesc').val()!='Select')
                {
                                queryCount=queryCount+1;
                                CQuery +="<Eq><FieldRef Name='TechnologyDescription' /><Value Type='Text'>"+$('#ddltechnologydesc').val()+"</Value></Eq>;";
                }
                if($('#fromDate').val().length !=0)
                {
                                queryCount=queryCount+1;
                                CQuery +="<Geq><FieldRef Name='Created'/><Value IncludeTimeValue='TRUE' Type='DateTime'>"+$('#fromDate').val()+"</Value></Geq>;";
                }
                if($('#toDate').val().length !=0)
                {
                                queryCount=queryCount+1;
                                CQuery +="<Leq><FieldRef Name='Created' /><Value IncludeTimeValue='TRUE' Type='DateTime'>"+$('#toDate').val()+"</Value></Leq>;";
                }
                if(queryCount==1)
                {
                                CQuery=CQuery.split(';')[0];
                }
                if(queryCount==2)
                {
                               
                                 CQuery="<And>"+CQuery.split(';')[0]+CQuery.split(';')[1]+"</And>";
                }
                if(queryCount==3)
                {
                                CQuery="<And>"+CQuery.split(';')[0]+"<And>"+CQuery.split(';')[1]+CQuery.split(';')[2]+"</And></And>";
                }
                if(queryCount==4)
                {
                                CQuery="<And>"+CQuery.split(';')[0]+"<And>"+CQuery.split(';')[1]+"<And>"+CQuery.split(';')[2]+CQuery.split(';')[3]+"</And></And></And>";
                }
                if(queryCount==5)
                {
                                CQuery="<And>"+CQuery.split(';')[0]+"<And>"+CQuery.split(';')[1]+"<And>"+CQuery.split(';')[2]+"<And>"+CQuery.split(';')[3]+CQuery.split(';')[4]+"</And></And></And></And>";
                }
                bindGridOnFilter(CQuery);
}
function bindGrid()
{
                $('#divPostsLoader').html('loading.....');
                var list = web.get_lists().getByTitle("lst_ITISGCRDetails");
                var camlQuery = new SP.CamlQuery();
                var q = '<View/>';
                camlQuery.set_viewXml(q);
                this.listItems = list.getItems(camlQuery);
                clientContext.load(listItems);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onbindGridSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onbindGridSuccess()
{
                var listEnumerator = this.listItems.getEnumerator();
                var htmlbody='';
                $('#GridTableResult').html('');
                                                                                htmlbody +='<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">';
                                                                                                htmlbody +='<thead>';
                                                                                                htmlbody +='<tr>';
                                                                                                                htmlbody +='<th>CR Number</th>';
                                                                                                                htmlbody +='<th>Technology</th>';
                                                                                                                htmlbody +='<th>Technology Description</th>';
                                                                                                                htmlbody +='<th>Site Name</th>';
                                                                                                                htmlbody +='<th>CR Detail</th>';
                                                                                                                htmlbody +='<th>Created by</th>';
                                                                                                                htmlbody +='<th>Created Date</th>';
                                                                                                htmlbody +='</tr>';
                                                                                                htmlbody +='</thead>';
                                                                                                htmlbody +='<tbody>';
               
               
                while (listEnumerator.moveNext()) {
                     var lstitem = listEnumerator.get_current();
                    // alert(lstitem.get_item('CRNumber'));
                                 
                                                var fieldUserValueCreatedBy = lstitem.get_item("Author");
                                                                var dateCreated = new Date(lstitem.get_item('Created'));
                                                                htmlbody+='<tr>';
                                 htmlbody+= '<td>'+ lstitem.get_item('CRNumber')+ '</td>';
                                 htmlbody+= '<td>'+ lstitem.get_item('Technology')+ '</td>'; 
                                 htmlbody+= '<td>'+ lstitem.get_item('TechnologyDescription')+ '</td>';
                                 htmlbody+= '<td>'+ lstitem.get_item('SiteName')+ '</td>';
                               //  console.log(lstitem.get_item("RedirectionUrl").get_url());
                               try {
                                                lstitem.get_item("RedirectionUrl").get_url()
                                                                                htmlbody+= '<td><a class="CRDeatailsCss" href="'+ lstitem.get_item("RedirectionUrl").get_url() + '">CR Detail</a></td>';
                                                                                }
                                                                                catch(err) {
                                                                                                htmlbody+= '<td><a class="CRDeatailsCss" href="#">CR Detail</a></td>';            
                                                                                                }
                                
                                 htmlbody+= '<td>'+ fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                                 htmlbody+= '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() +  '</td>';
                             htmlbody+='</tr>';
                               
        }
        htmlbody +='</tbody>';
                                htmlbody +='</table>';
        $('#GridTableResult').html(htmlbody);
                table= $('#example').DataTable( {     
         "searching": false,
         "paging": true,
         "info": false,        
         "lengthChange":false,
         "pageLength": 20 
                });
                $('#divPostsLoader').empty();
  
}
function bindGridOnFilter(Query)
{
                $('#divPostsLoader').html('loading.....');
                var list = web.get_lists().getByTitle("lst_ITISGCRDetails");
                var camlQuery = new SP.CamlQuery();
                var q = '<View><Query><Where>'+Query+'</Where></Query></View>';
                camlQuery.set_viewXml(q);
                this.listItems = list.getItems(camlQuery);
                clientContext.load(listItems);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onbindGridOnFilterSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onbindGridOnFilterSuccess()
{
                var listEnumerator = this.listItems.getEnumerator();
                var htmlbody='';
                                                                                $('#GridTableResult').html('');
                                                                                htmlbody +='<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">';
                                                                                                htmlbody +='<thead>';
                                                                                                htmlbody +='<tr>';
                                                                                                                htmlbody +='<th>CR Number</th>';
                                                                                                                htmlbody +='<th>Technology</th>';
                                                                                                                htmlbody +='<th>Technology Description</th>';
                                                                                                                htmlbody +='<th>Site Name</th>';
                                                                                                                htmlbody +='<th>CR Detail</th>';
                                                                                                                htmlbody +='<th>Created by</th>';
                                                                                                                htmlbody +='<th>Created Date</th>';
                                                                                                htmlbody +='</tr>';
                                                                                                htmlbody +='</thead>';
                                                                                                htmlbody +='<tbody>';
                               
                while (listEnumerator.moveNext()) {
                     var lstitem = listEnumerator.get_current();
                    // alert(lstitem.get_item('CRNumber'));
                                 
                                                var fieldUserValueCreatedBy = lstitem.get_item("Author");
                                                                var dateCreated = new Date(lstitem.get_item('Created'));
                                                                htmlbody+='<tr>';
                                 htmlbody+= '<td>'+ lstitem.get_item('CRNumber')+ '</td>';
                                 htmlbody+= '<td>'+ lstitem.get_item('Technology')+ '</td>'; 
                                 htmlbody+= '<td>'+ lstitem.get_item('TechnologyDescription')+ '</td>';
                                 htmlbody+= '<td>'+ lstitem.get_item('SiteName')+ '</td>';
                               //  console.log(lstitem.get_item("RedirectionUrl").get_url());
                               try {
                                                lstitem.get_item("RedirectionUrl").get_url()
                                                                                htmlbody+= '<td><a class="CRDeatailsCss" href="'+ lstitem.get_item("RedirectionUrl").get_url() + '">CR Detail</a></td>';
                                                                                }
                                                                                catch(err) {
                                                                                                htmlbody+= '<td><a class="CRDeatailsCss" href="#">CR Detail</a></td>';            
                                                                                                }
                                
                                 htmlbody+= '<td>'+ fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                                 htmlbody+= '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() +  '</td>';
                             htmlbody+='</tr>';
                               
        }
       
                                                               
                                                                htmlbody +='</tbody>';
                                                                                    htmlbody +='</table>';
        $('#GridTableResult').html(htmlbody);
       //table= $('table#example').DataTable({"lengthMenu": [20],"pagingType": "full_numbers"});
       table= $('#example').DataTable( {     
         "searching": false,
         "paging": true,
         "info": false,        
         "lengthChange":false,
         "pageLength": 20 
    } );
    $('#divPostsLoader').empty();
}
function fnExcelReport()
    {
             var tab_text="<table border='2px'><tr bgcolor='#FFCCCC'>";
             var textRange; var j=0;
                 tab = document.getElementById('example'); // id of table
          for(j = 0 ; j < tab.rows.length ; j++)
          {    
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }
          tab_text=tab_text+"</table>";
          tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
                      tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
               var ua = window.navigator.userAgent;
              var msie = ua.indexOf("MSIE ");
                 if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                    {
                           txtArea1.document.open("txt/html","replace");
                          txtArea1.document.write(tab_text);
                           txtArea1.document.close();
                           txtArea1.focus();
                            sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
                          } 
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); 
                      return (sa);
                            }
       
DefaultSettings.css:
body #s4-leftpanel {
                display:none;
}
.s4-ca {
                margin-left:0px;
}
.ms-core-pageTitle
{display:none !important;}
#suiteBar,#s4-ribbonrow,#s4-titlerow,#sideNavBox
{
                display:none !important;
}
#contentBox
{
                margin-left:30px !important;
}
#maindropdownform tr td
{
    padding:5px;
}
#mainbuttons tr td
{
    text-align:center;
   
}

Created Dateand Modified Date Using JSOM

$
0
0
                console.log(currentItem.get_item("Last_x0020_Modified").split('T')[0]);
               console.log(currentItem.get_item("Created_x0020_Date").split('T')[0]);
               console.log(currentItem.get_item("Last_x0020_Modified").split('T')[1].split('Z')[0]);
               console.log(currentItem.get_item("Created_x0020_Date").split('T')[1].split('Z')[0]);

Get User Details from Person or Group field using REST API

$
0
0
This article helps to understand, how to get user details like FirstName, LastName, Email Addrss etc. for a Person/Group field using REST API.

Normally, in a list where we have Person/Group column (say Employee), when we use REST API to get this column value, we get User ID instead of actual value what we see in list column. Reason being Person/Group column is actually a lookup field internally.

Say I have a list Employees with column "Users", and for one item value for Users is "Danish Islam" (set to Name with Presence property). 



Now if I query this list using below REST API -

_api/web/lists/getbytitle('employees')/items
I see result as in below screenshot-




Here if you observe, Users column is returned as "UsersId" and with value "10" not the actual value.

Now if I want the actual value, I have to modify my query something like below-

_api/web/lists/getbytitle('employees')/items?$select=Users/Title&$expand=Users/Id
See the highlighted change, this will return exact value like below-




Similarly If i want to display Email Address or First Name or Last Name, I just have to replace keyword after column name - Title after Users.  See below example-

Query:

_api/web/lists/getbytitle('employees')/items?$select=Users/EMail,Users/FirstName,Users/LastName,Users/EMail&$expand=Users/Id

Result: 


Resize Iframe Dynamically in C#

$
0
0
<iframe runat="server" width="100%" id="IFReport" src="" frameborder="0"clientidmode="Static" height="500"></iframe>

Write a JavaScript method for resizing it, as in:

<script type="text/javascript">    function setIframeHeight(iframe) {        if (iframe) {            var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;            if (iframeWin.document.body) {                iframe.height = 17 + iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;            }        }    };</script>
As you notice, I have set the runat="Server" of the iframe. So we can't call the setIframeHeight method directly by writing the onload of the iframe.

We will set the iframe attribute for calling that method as in:
this.IFReport.Attributes.Add("onload""setIframeHeight(document.getElementById('" + IFReport.ClientID + "'));");

Useful Links

$
0
0


SharePoint blogs and sites
http://sharepointquicksolutions.blogspot.in/2012/08/sharepoint-interview-questions-and.html
http://sampathnarsingam.blogspot.in/
http://snahta.blogspot.in/2010/11/sp2010-model-window-closing.html
http://blog.creative-sharepoint.com/2013/06/embedding-a-powerpoint-presentation-into-a-sharepoint-2013-page/
https://wb2-web.sharepoint.com/Pages/webbrewerstest2.aspx
http://jyothsnag.blogspot.in/2012/07/getset-values-for-managed-metadata.html
http://spointthoughts.blogspot.in/2012/09/how-to-add-ecb-menu-item-in.html
http://sharepoint.sureshc.com/2010/01/how-to-determine-if-spuser-is-manager.html?view=sidebar
http://mohamedakb.blogspot.in/2012/06/set-item-level-permission.html
http://community.bamboosolutions.com/blogs/sharepoint-2013/archive/2013/02/01/how-to-manage-permissions-for-a-list-item-or-document-in-sharepoint-2013.aspx
http://geekswithblogs.net/juanlarios/archive/2009/09/04/giving-user-access-to-site-with-custom-permission-level.aspx
http://howtosharepoint.blogspot.in/2010/10/programmatically-add-delete-modify-item.html
http://rehmangul.wordpress.com/2009/12/04/setting-item-level-permissions/
//For enabling the Enterprise Key words programmatically
http://point2sharepoint.blogspot.in/2011/04/add-enterprise-keywords-column_3251.html
http://www.stickyglue.co.za/index.php/archives/151
http://lyndzhang.wordpress.com/2012/12/28/sharepoint-2010-get-user-profile-info-using-visual-studio-2010-c/
http://blogs.tamtam.nl/duarte/CategoryView,category,Sharepoint2003.aspx
http://www.sharepoint-journey.com/sharepoint-solutions.html
http://msdn.microsoft.com/en-us/library/office/jj687488.aspx   // customizing the search results
http://msdn.microsoft.com/en-us/sharepoint/aa905690.aspx  // sharepoint 2013 downloads
http://sharepointfieldnotes.blogspot.in/
http://www.sys-con.com/node/25811970
http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2013/01/03/how-to-use-the-sharepoint-2013-search-keywordquery-class.aspx
http://sp77.blogspot.in/2013/04/working-with-people-search-keywordquery.html
http://blog.mastykarz.nl/programmatically-working-keyword-search-queries-sharepoint-2013/
http://chakkaradeep.com/index.php/using-keywordquery-to-search-in-your-sharepoint-site/
http://blog.petermunch.net/2010/04/30/versioning-and-upgrading-your-features-with-sharepoint-2010-application-lifecycle-management/
http://community.bamboosolutions.com/blogs/sharepoint-2013/archive/2012/11/05/how-to-create-a-web-part-page-in-sharepoint-2013.aspx
http://blog.lekman.com/2010/11/automated-sharepoint-2010-installations.html
http://blog.creative-sharepoint.com/2013/04/creating-a-sharepoint-2013-community-site/
https://www.nothingbutsharepoint.com/sites/eusp/Pages/Step-by-Step-Create-a-SharePoint-2013-Composed-Look.aspx // branding
http://adicodes.com/category/sharepoint-2010/
http://www.sharepointnerd.com/students/10175/Forms/WebPartView.aspx
http://technet.microsoft.com/en-us/library/ff628582.aspx // for attach and deattach the content database.Database Management
http://msdn.microsoft.com/en-us/library/jj191506.aspx  // for mastr pages and page layouts
http://www.sharepoint.inf4web.com/780/how-to-create-shortcut-of-14-hive-folder-on-taskbar/ // good information about the share point
http://www.codeproject.com/Questions/241490/Class-not-registered-Exception-from-HRESULT-0x8004
http://marcellotonarelli.wordpress.com/2012/03/14/sharepoint-site-collection-lock-and-unlocking/
http://www.mindfiresolutions.com/
http://en.share-gate.com/blog/sharepoint-2013-search-settings-and-search-box-drop-down-menu
http://radutut.wordpress.com/2013/03/11/update-search-settings-using-powershell-in-sharepoint-2013/
http://stevemannspath.blogspot.in/2013/07/sharepoint-2013-search-setting-all.html
http://blogs.technet.com/b/tothesharepoint/archive/2013/03/06/from-site-column-to-managed-property-what-s-up-with-that.aspx#AboutProperties
http://blogs.technet.com/b/tothesharepoint/archive/2013/03/06/from-site-column-to-managed-property-what-s-up-with-that.aspx#AboutProperties
http://www.sharepointanalysthq.com/2010/04/site-collection-navigation-settings/
http://donalconlon.wordpress.com/2010/07/29/user-profile-metadata-properties-not-recognizing-the-term-store/   // good blog
http://www.stuartroberts.net/index.php/2012/05/28/export-metadata-terms/comment-page-1/#comment-4490  // good blog
http://designpatternslibrary.codeplex.com/  // all design patterens
http://gallery.technet.microsoft.com/office/site/search?f%5B0%5D.Type=RootCategory&f%5B0%5D.Value=sharepoint // sharepoint code samples
http://sharepointdrive.blogspot.in/2012/04/automating-sharepoint-site-backup-using_14.html  // for scheduling the backup the site using powershell
//Sharepoint videos
http://sharepoint-videos.com/
http://www.demantprasad.com/2013/07/how-to-set-sharepoint-choice-field.html  // user
http://msdn.microsoft.com/en-us/library/jj163942.aspx
http://preachingsharepoint.blogspot.in/2012/04/microsoft-skydrive-tutorial-for.html
http://www.sharepointpals.com/    // useful site
http://www.getcodesamples.com/tag/User%20Interface   // sharepoint developer links
http://wallstcheatsheet.com/stocks/the-6-worst-things-about-working-for-google.html/6/ //Google wrost things
http://beginnersbook.com/2013/02/event-receivers-in-sharepoint/
http://salnikan.wordpress.com/2011/07/26/prevention-of-duplicate-entries-based-on-two-or-more-columns-in-a-sharepoint-list/ // composite keys
http://consultingblogs.emc.com/mattlally/archive/2012/01/06/sharepoint-2010-validate-special-characters.aspx // column  validation
http://sampathnarsingam.blogspot.in/    // good site for sharepoint
http://ammarfassy.wordpress.com/2013/10/01/restore-spsite-0x80070003/  sharepoint administration.
http://social.technet.microsoft.com/wiki/contents/articles/19797.sharepoint-2013-a-no-code-solution-to-build-a-change-management-request.aspx
http://code.msdn.microsoft.com/office/SharePoint-2013-Setting-084b6afa
http://www.getcodesamples.com/tag/User%20Interface  // developemen site.
http://www.silver-it.com/node/64  //client side permission code
https://blog.credera.com/technology-insights/microsoft-solutions/sharepoint-2013-development-solutions-vs-apps/
https://www.nothingbutsharepoint.com/sites/devwiki/articles/Pages/SharePoint-2013-Custom-Error-Pages.aspx
https://www.nothingbutsharepoint.com/sites/devwiki/articles/Pages/SharePoint-Showing-Notification-and-Status-Message-Using-SP-js.aspx
Share point custom list forms
-------------------------
http://blog.beckybertram.com/Lists/Posts/Post.aspx?ID=6

------------------------------------------------------------
https://www.nothingbutsharepoint.com/sites/eusp/pages/creating-your-own-content-slider-for-sharepoint.aspx
http://sharepointontop.blogspot.in/2013/03/create-page-layout-in-sharepoint-2013.html
http://blog.falchionconsulting.com/index.php/downloads/   // for custom power shell scripts

 https://www.nothingbutsharepoint.com/sites/eusp/articles/Pages/default.aspx // sharepoint good articles

// Different Jquery plug ins Share point
--------------------------------------------
http://www.freedownloadmanager.org/download/sharepoint-news-scroller-jquery-5888450.html
Migration from Sharepoint and Sharepoint 2013
-----------------------------------------------
http://sharepointengineer.com/2012/11/15/sharepoint-2010-to-2013-upgrade-step-by-step-2/
Share Point features:
----------------------------
http://sharepoint2013trainings.com/
http://sharepointdeveloper.info/how-to-programmatically-set-default-publishing-page-layout/
http://aleemsheikh.wordpress.com/2012/03/16/creating-list-fields-programmatically-in-sharepoint-2010-2/
http://dotnetfollower.com/wordpress/2013/07/sharepoint-how-to-add-links-and-headings-to-quick-launch-programmatically/
http://blogs.msdn.com/b/officeapps/archive/2013/09/18/step-by-step-sending-email-messages-from-a-workflow-in-an-app-for-sharepoint-2013.aspx
http://blog.sharedove.com/adisjugo/index.php/2012/07/25/visual-guide-setting-up-my-sites-in-sharepoint-2013/ --My Site Creation
IMP Links:
--------
http://blogs.perficient.com/microsoft/2012/01/sharepoint-2010-closing-a-modaldialog-manually-from-code-c-and-javascript/
http://bramnuyts.be/2011/04/01/add-an-event-receiver-to-a-specific-list-programmatically/
http://zimmergren.net/technical/sharepoints-hidden-user-list-user-information-list
http://blogs.technet.com/b/speschka/archive/2010/08/11/using-powershell-for-sharepoint-2010-in-c.aspx
http://social.technet.microsoft.com/Forums/en-US/88b11fe3-c218-49a3-ac4b-d1a04939980c/how-to-programmatically-execute-the-sharepoint-powershell-commands-ie-using-sharepoint-management?forum=sharepointgeneralprevious
http://www.mindfiresolutions.com/Create-and-Update-Views-Programmatically-in-SharePoint-451.php
http://www.marcirawan.com/configuring-sharepoint-2013-site-navigation-programmatically-using-feature/
http://www.anmolrehan-sharepointconsultant.com/2011/10/create-sharepoint-views.html
http://discoveringsharepoint.wordpress.com/tag/spfielduservaluecollection/
http://moonistahir.wordpress.com/2009/07/27/create-spview-programmatically-with-group-by-option/ // create views with group by
http://blog.karstein-consulting.com/2011/06/22/walkthrough-add-list-event-receiver-dynamically-at-runtime-in-sharepoint-2010/
http://blogs.technet.com/b/speschka/archive/2009/11/01/using-the-sharepoint-2010-client-object-model-part-5.aspx
http://www.learningsharepoint.com/sharepoint-2013-how-tos/ // sharepoint 2013
http://spdevnewb.blogspot.in/
http://www.sangeetahuja.com/2013/03/sharepoint-grouped-viewconditional.html
http://sharepointerthilosh.blogspot.in/2013/04/customise-list-view-webpart-using.html
http://sharepoint-works.blogspot.in/2012/05/programmatically-get-sharepoint-users.html#.Uoy6-MRplWY
http://suryapulipati.blogspot.in/2011/08/sharepoint-2010-custom-listview-webpart.html
http://johanolivier.blogspot.in/2013/03/a-better-way-to-attach-custom-sp2010.html
?ToolPaneView=2&pagemode=edit  // for page editing
http://www.linkedin.com/groups/Cant-Edit-page-Access-Denied-43166.S.96894100   // useful link for permissions
http://www.sharepointshoptalk.com/apps/videos/  // MVPs discussions
http://www.concurrency.com/blog/sharepoint-lists-creating-multiline-text-columns/   // create Multi line text
http://chanakyajayabalan.wordpress.com/  // for sharepoint good site
http://www.silver-it.com/node/64 // client object mmodel permissions checking
http://marcellotonarelli.wordpress.com/2010/04/02/sharepoint-2010-free-videos/
http://aircreek.com/blog/2012/how-to-configure-read-permission-level-to-browse-directories-in-sharepoint-2010-and-office-365/ // client object model
http://blog.cloudshare.com/2013/01/15/how-to-install-and-configure-workflow-infrastructure-in-sharepoint-2013/ Install sharepoint 2013 workflow

RSS Viewer :
------------------------------------
http://blog.creative-sharepoint.com/2013/06/displaying-sharepoint-blogs-on-a-sharepoint-online-homepage/
http://www.ashokraja.me/articles/How-to-Programmatically-Show-or-Hide-a-Modal-Popup-Dialog-with-Server-Side-Code-in-Share-Point-2013

http://blog.tedpattison.net/Lists/Categories/Category.aspx?CategoryId=2&Name=SharePoint Development
Microsoft Traininig videos for sharepoint 2013
-------------------------------------------
http://msdn.microsoft.com/en-US/sharepoint/fp123577    // new features in the share point in 2013

Export page to Excel automatically
-------------------------------------
http://www.codeproject.com/Tips/272244/Export-any-page-to-excel-automatically-asp-net

Code Samples for sharepoint 2010
----------------------------------
http://code.msdn.microsoft.com/office/SharePoint-2010-101-Code-da251182/view/SamplePack#content
http://gallery.technet.microsoft.com/sharepoint/site/search?f%5B0%5D.Type=Tag&f%5B0%5D.Value=SharePoint%202013&pageIndex=2

Programmatically added the Managed Meta data field
-----------------------------------------------
http://sharepointlady.wordpress.com/2012/04/20/set-managed-metadata-fields-value-programmatically/
http://sharepointjim.wordpress.com/2011/11/02/cannot-connect-to-the-sharepoint-site-make-sure-that-the-site-url-is-valid-that-the-sharepoint-site-is-running-on-the-local-computer-and-that-the-current-user-has-the-necessary-permissions-to-acc/
http://blogs.msdn.com/b/kvosters/archive/2012/11/29/the-local-farm-is-not-accessible-cmdlets-with-featuredependencyid-are-not-registered.aspx
Best Practice:
------------------
http://msdn.microsoft.com/en-us/library/ee724407(v=office.14).aspx

// Create custom forms
-----------------------------
http://community.bamboosolutions.com/blogs/sharepoint-2013/archive/2012/09/20/how-to-create-custom-forms-using-sharepoint-designer-2013.aspx
http://zoshaikh.wordpress.com/2011/09/23/how-to-add-webparts-on-newform-aspx-dispform-aspx-or-editform-aspx-on-sharepoint-list-and-libraries/
http://rajkamal29.blogspot.in/2010/03/c-programmatically-set-audiance.html

For metadata profile properties:
-------------------------------------
http://stackoverflow.com/questions/12932925/displaying-custom-user-properties-with-keywordquery-that-uses-managed-metadata-i
http://waelmohamed.wordpress.com/2010/05/10/sharepoint-user-profiles-part-2-working-with-user-profile-with-sharepoint-object-model/
Internal Names for the fields in Sharepoint
----------------------------------------------
http://blogs.msdn.com/b/michael_yeager/archive/2008/11/03/reference-list-for-internal-field-names.aspx
http://stackoverflow.com/questions/1075323/copy-list-items-from-one-list-to-another-in-sharepoint

http://www.sharepointdiary.com/2012/09/associate-event-receiver-to-particular-list.html
http://joelblogs.co.uk/2011/06/16/sharepoint-2010-base-types-list-template-and-definition-ids-and-content-types-ids/
http://rajanijilla.blogspot.in/2012/09/people-search-using-custom-property.html   // rajani blog
For calculated Column
-----------------------------
http://msdn.microsoft.com/en-us/library/bb862071(v=office.14).aspx

For Multiple files Uploader Problem:
---------------------------------------
http://bfgagliolo.wordpress.com/2011/12/12/sharepoint-2010-using-multi-file-upload-lost-metadata-on-office-2010-documents/

http://www.sharepointfront.com/update-personal-site-property-in-user-profile/

Sample sharepoint app in VS 2012
-----------------------------------
http://blogs.msdn.com/b/officeapps/archive/2013/09/18/step-by-step-sending-email-messages-from-a-workflow-in-an-app-for-sharepoint-2013.aspx
SharePoint Content Approval Status updating programmatically
-------------------------------------
http://sharepoint-developer.blogspot.in/2009/02/sharepoint-content-approval-status.html

Global Navigation and Current Navigation Programmatically
----------------------------------------------------------
http://www.marcirawan.com/configuring-sharepoint-2013-site-navigation-programmatically-using-feature/

// Programmatically add the content editor webpart
http://www.broculos.net/2013/09/how-to-programmatically-add-content.html#.Unsm9PlplWY

http://acunet/sites/Projects/TPL-IntranetAndKMS-PhaseII/Project%20Plan/PROD%20Migration/TPLIntranet_Deployment_v0.1.docx
http://blog.cloudshare.com/2013/01/15/how-to-install-and-configure-workflow-infrastructure-in-sharepoint-2013/
http://bborole.blogspot.in/2010/10/calculated-columns-cannot-contain.html


*************************************Blogs Information ********************************
http://www.chaholl.com/
http://geekswithblogs.net/GinoAbraham/
http://sharepointchick.com/
http://ibrahimk.blog.com/
http://dbweb.sbisite.com/blogs/lp/Lists/Categories/Category.aspx?Name=Navigation
http://sharepointking.wordpress.com/
http://community.bamboosolutions.com/blogs/
http://www.mssharepointtips.com/
http://blog.vgrem.com/
http://blog.pathtosharepoint.com/
http://sergeluca.wordpress.com/2010/06/08/workflows-in-sharepoint-2010-tutorial-step120-what%E2%80%99s-new/
http://www.pathtosharepoint.com/
http://benprins.wordpress.com/
http://blogs.technet.com/b/tothesharepoint/archive/2013/04/30/stage-9-configure-the-query-in-a-content-search-web-part-on-a-category-page.aspx#HowQueryCSWP
http://sympmarc.com/2013/06/05/displaying-the-most-recent-documents-from-all-document-libraries-in-a-sharepoint-site/
http://www.dotnet-tricks.com/
http://prafulgoyal.blogspot.in/
http://sharepoint.stackexchange.com/questions/50236/in-sharepoint-2013-how-do-i-use-the-person-field-people-picker-in-a-custom-we
http://sharepoint.stackexchange.com/questions/tagged/visual-web-part?sort=active&pageSize=50
http://buyevich.blogspot.in/2010/10/sharepoint-how-to-get-document-icon.html // for sharepoint tips
http://prit-saini.blogspot.in/2011/02/adding-expand-and-collapse-feature-in.html

How to Clear cache in SharePoint Designer?

$
0
0

When do you need to clear SharePoint Designer cache? 

  1. Once you have opened SharePoint site with one user in SharePoint Designer, SPD will save connection details. Now, next time when you try to open same SharePoint site from SPD, It will open that site with saved connection details. If you want to open that site with different connection details (Credentials) then you need to clear SharePoint Designer cache. The cache is not even cleared after doing a reinstall, so this really is the only way to clear it.
  2. Sometimes, SPD shows files are already checked out even though they aren't. While trying to check-in, SPD gives error "Cannot perform this operation. The file is no longer checked out or has been deleted." This is due to SharePoint Designer is out of sync with SharePoint and you have to clear cache in order to rebuild it.
  3. The cache is not even cleared after doing a reinstall. So, how would you do it? Here, is the only way - detailed steps to clear cache in SharePoint Designer.

Steps to Clear SharePoint Designer Cache:

Step 1: 
  • Close SharePoint Designer if it is open.

Step 2: [Clear Website Cache]  
  • Open Windows Explorer, Click the address bar and Paste “%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache”.
  • Delete everything within this location.

Step 3: [Clear Web Server Extensions Cache]
  • Open Windows Explorer, Click the address bar and Paste “%APPDATA%\Microsoft\Web Server Extensions\Cache”.
  • Delete everything in this location.

Step 4: [Disable “Cache site data across SharePoint Designer sessions”]
  • Open SharePoint Designer 2010/2013.
  • Navigate to the "File" menu then select "Options" -> "General" -> "Application Options".


     
  • On the “General” tab, under the “General” heading, uncheck “Cache site data across SharePoint Designer sessions”.


Client Side People Picker with JSOM in Office 365/SharePoint 2013

$
0
0

Requirement:

In one of the project, I had a requirement to use people picker in Client side HTML which should have same features as SharePoint OOTB people picker provides.


Approach/Solution:
Follow below steps to achieve client side people picker functionality using JSOM.

1. Below mentioned JS files are required to load client side people picker using JSOM. All
JS
files are OOTB SharePoint JS files which are available under "_layouts/15" folder in
SharePoint.
- clienttemplates.js
- clientforms.js
- clientpeoplepicker.js
- autofill.js
- sp.js
- sp.runtime.js
- sp.core.js
2. Put reference of all JS files into HTML file for which you want to create Client Side People
Picker.
3. Add below Div tag in your HTML file.
<div id="peoplePickerDiv"></div>
4. Add below code in your custom JS file (custompeoplepicker.js) and also put reference of this file into HTML file.
       // Initialize People Picker.   
 $(document).ready(function() {  
 // Specify the unique ID of the DOM element where the 
 // picker will render. 
 initializePeoplePicker('peoplePickerDiv');  
  });  
 // Render and initialize the client-side People Picker. 
 function initializePeoplePicker(peoplePickerElementId) {  
 // Create a schema to store picker properties, and set the properties. 
 var schema = {};  
 schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
 //This value specifies where you would want to search for the valid values
 schema['SearchPrincipalSource'] = 15;             
 //This value specifies where you would want to resolve for the valid values
 schema['ResolvePrincipalSource'] = 15;  
schema['AllowMultipleValues'] = true;  
 schema['MaximumEntitySuggestions'] = 50;  
 schema['Width'] = '280px';  
 // Render and initialize the picker. 
// Pass the ID of the DOM element that contains the picker, an array of initial   
// PickerEntity objects to set the picker value, and a schema that defines 
// picker properties.   
this.SPClientPeoplePicker_InitStandaloneControlWrapper(
peoplePickerElementId, null, schema);  
                        }
                         // Get user information from client side people picker.
  // Query the picker for user information.

 function getUserInfo() {
 // Get the people picker object from the page.
 var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
for (var i = 0; i < users.length; i++) {
var user = users[i];
for (var userProperty in user) {
userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
}
}
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
// Get the first user's ID by using the login name.
getUserId(users[0].Key);
}
// Get the user ID.
function getUserId(loginName) {
var context = new SP.ClientContext.get_current();
this.user = context.get_web().ensureUser(loginName);
context.load(this.user);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccess),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccess() {
console.log(this.user.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}

// Below code sets values into client side people picker.
var divPeople = SPClientPeoplePicker.SPClientPeoplePickerDict.PeoplePickerDiv_TopSpan;
PeoplePickerDiv_TopSpan - Specify the unique ID of the DOM element where thepicker will render.
var userObj = { 'Key': "sample@sample.com" };
divPeople.AddUnresolvedUser(userObj, true);

Export to Excel a Table Record and Print in Jquery

$
0
0
Web browser wars hurt developers’ hearts. It is mostly about CSS, sometimes about JavaScript, HTML etc…
Thus I know how it feels when you expect something to get done easily appears a lot more harder than you expected.
Code below is tested only with Chrome (24+). It is making these processes:
  • Gets the HTML code of your table inside your div element.
  • Replaces the spaces in the code with correct syntax for Excel (otherwise spaces will be removed in your Excel sheet).
  • Generates a specific file name (for minutes) in order to avoid overriding old files and to supply archiving by date values.
  • And lastly and most importantly, saving the file with a custom file name.


HTML Code :
<iframe id="txtArea1" style="display:none"></iframe>
<td> <input type="button" id="btnExporttoExcel" class="btnClass" title="Export To Excel" onclick="fnExcelReport()" name="Export To Excel" value="Export To Excel">  </td>
   </td>  <td><input id="idprint" value="Print"  class="btnClass"   onclick="return PrintDocument('responsiveGrid');"  type="button"/>  </td>
 
JS Code:
 
function fnExcelReport1()
{
        var dt = new Date();
        var day = dt.getDate();
        var month = dt.getMonth() + 1;
        var year = dt.getFullYear();
        var hour = dt.getHours();
        var mins = dt.getMinutes();
        var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
        //creating a temporary HTML link element (they support setting file names)
        var a = document.createElement('a');
        //getting data from our div that contains the HTML table
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById('responsiveGrid');
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        a.href = data_type + ', ' + table_html;
        //setting the file name
        a.download = 'exported_table_' + postfix + '.xls';
        //triggering the function
        a.click();
        //just in case, prevent default behaviour
        e.preventDefault();
}
 
//or
function fnExcelReport()
    {
         var dt = new Date();
         var day = dt.getDate();
         var month = dt.getMonth() + 1;
         var year = dt.getFullYear();
         var hour = dt.getHours();
         var mins = dt.getMinutes();
         var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
         var tab_text="<table border='2px'><tr bgcolor='#D1D3D4'>";
         var textRange; var j=0;
                 tab = document.getElementById('tablepaging'); // id of table
         for(j = 0 ; j < tab.rows.length ; j++)
          {    
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }
          tab_text=tab_text+"</table>";
          tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
          tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
          var ua = window.navigator.userAgent;
          var msie = ua.indexOf("MSIE ");
          if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
             {
                   txtArea1.document.open("txt/html","replace");
                   txtArea1.document.write(tab_text);
                   txtArea1.document.close();
                   txtArea1.focus();
                   var NameofExcel='BEPS_Report_' + postfix + '.xlsx';
                   Ram=txtArea1.document.execCommand("SaveAs",true,NameofExcel);
             } 
          else                 //other browser not tested on IE 11
                     Ram= window.open('data:application/vnd.ms-excel,filename=filename.xlsx,' + encodeURIComponent(tab_text));
                    // Ram= window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
                    return (Ram);
}       
 
function PrintDocument(divName) {
     alert('Ram');
     var printcontents = document.getElementById(divName).innerHTML;
     var originablecontents = document.body.innerHTML;
     document.body.innerHTML = printcontents;
     window.print();
     document.body.innerHTML = originablecontents;
}
 

Find Count All File Pending and Approved and Reject in Document Library Using Rest Api and JSOM

$
0
0
Aspx File:

<%-- _lcid="1033" _version="15.0.4420" _dal="1" --%>
<%-- _LocalBinding --%>
<%@ Page language="C#" MasterPageFile="../_catalogs/masterpage/NGO-SMIL_Master/NGO-SMIL_Master.master" meta:progid="SharePoint.WebPartPage.Document" inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" meta:webpartpageexpansion="full"  %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
                NGO&nbsp; Document Library System
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
 
<!--<link rel="stylesheet" type="text/css" href="../SiteAssets/Scripts/bootstrap/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="../SiteAssets/Scripts/bootstrap/bootstrap-select.min.css"/>-->
 
<script type="text/javascript" src="../SiteAssets/Scripts/jquery.min.js?ver=2.0"></script>
<script src="../SiteAssets/Scripts/jquery-ui.js?ver=2.0" type="text/javascript"></script>
<link href="../SiteAssets/Style/jquery-ui.css?ver=2.0" rel="stylesheet" type="text/css" />
 
<script src="/_layouts/15/sp.runtime.debug.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.debug.js" type="text/javascript"></script>
<script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
 
<script src="/_layouts/15/SP.UI.Dialog.js" type="text/javascript"></script>
 
<script src="../SiteAssets/Scripts/NGO_SMIL_Main_Report.js?ver=2.0" type="text/javascript"></script>
 
<script src="../SiteAssets/Scripts/jClocksGMT.js" type="text/javascript"></script>
<script src="../SiteAssets/Scripts/mone_browserinfo_plugin.js" type="text/javascript"></script>
<link href="../SiteAssets/Style/NGO_SMIL.css" type="text/css" rel="stylesheet" />
<meta name="GENERATOR" content="Microsoft SharePoint" />
<meta name="ProgId" content="SharePoint.WebPartPage.Document" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="CollaborationServer" content="SharePoint Team Web Site" />
<style type="text/css">
overflow-y: scroll;
</style>
<style>
.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #DA2128;
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 4s linear infinite;
}
 
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(80deg); }
  100% { -webkit-transform: rotate(360deg); }
}
 
@keyframes spin {
  0% { transform: rotate(80deg); }
  100% { transform: rotate(360deg); }
}
 
 
 
</style>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderSearchArea" runat="server">
                <SharePoint:DelegateControl runat="server"
                                ControlId="SmallSearchInputBox"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
                <SharePoint:ProjectProperty Property="Description" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<iframe id="txtArea1" style="display:none"></iframe>
<div style="display:none;position:absolute;margin-top: 160px;margin-left: 610px;" class="loader">Please <br> Wait.....</div>
<!--<div class="loading" align="center" style="position:absolute" id="modalSending">
    <img style="width: 55px;
    margin-top: 250px;
    margin-left: 409px;" src="../SiteAssets/loading.gif" />
</div>-->
                                                <div id="CompanyView" style="display:none" class="company-view">
              <!--Body Section -->
              <div class="body-container">
                <div class="body-section">
                  <div class="body-box">
                    <!--Heading -->
                    <h1 style="text-align: center;" id="hd1FolderTitle">NGO
                                                                                Document Library Report</h1>
                    <!--Ends Heading -->
                    <!--Drag Files -->
                     <!--Ends Drag Files -->
                    <!--Start Dropdown---!-->
                     <div style="border-width: 1px; border-style: ridge; border-color: #D1D3D4; " id="resFilter">
                      <table id="tableFilter"  >
                        <tr>
                        <td>
                        <div id="filter">
                                                                       <div class="controls_title" style="font-weight: bold; font-size: 13px; padding-bottom:5px;">
                                                                                                <span style="margin-right:8px;">Select an Entity :</span><span>
                                                                                                <select style="width: 200px;"  id="ddlCompanyName" name="CompanyName">
                                                                        <option value="Select">--Select--</option>
                                                                        </select></span></div>
                                                                        </div>
                                                                        </td>
                        <td>
                        <div id="Year">
                                                                        <div class="controls_title" style="font-weight: bold; font-size: 13px; padding-bottom:5px;">
                                                                                                <span style="margin-right:8px;">Select a Year :</span><span>
                                                                                                <select style="width: 200px;"  id="ddlYear" name="CompanyName">
                                                                          <option value="2016-2017">2016-2017</option>
                                                                          <option value="2016-2018">2016-2018</option>
                                                                    </select></span>
                                                                    <input type="button" id="btnsubmit" class="btnClass" title="Go" onclick="" name="Go" value="Go">
                                                                    </div>
                                                                    </div>
                                                                    </td>
                                                                    <td>
                                                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>Search :&nbsp;</span><input type="text" id="txtSearch" style="width: 350px" />
                                                                    </td>
                                                                     <td>
                                                                     <!--style="background-color: #6d6e71;color: #FFF;padding: .5em .75em;margin-top: -3px;height: 28px;"-->
                                                                     &nbsp;&nbsp;<input type="button" style="padding: .5em .75em;margin-top: -3px;height: 28px;" id="btnExporttoExcel" class="btnClass" title="Export To Excel" onclick="fnExcelReport()" name="Export To Excel" value="Export To Excel">
                                                                     </td>
                                                                     <td>&nbsp;&nbsp;<input id="idprint" style="padding: .5em .75em;margin-top: -3px;height: 28px;" value="Print"  class="btnClass"   onclick="return PrintDocument('responsiveGrid');"  type="button"/>
                     </td>
                    
                        </tr>
                      </table>
                    </div>
                                                                     <!-- End Dropdown---!-->
                    <!--Table -->
                   <!--<div id="responsiveGrid" class="" style="max-height: 350px; overflow: auto;">-->
                   <!---- Imp Point Set padding in default.css and style="min-height: 330px;">-->
                    <div id="responsiveGrid" style="display:none" class="" style="min-height: 345px;">
 
                      <table width="100%" class="table"  id="tablepaging"  >
                        <thead>
                          <tr valign="top">
                             <th style="border: 1px solid #e6e7e8" width="32"  align="left"  scope="col"><strong>Sr.No.</strong></th>
                            <th style="border: 1px solid #e6e7e8" align="left"><strong>Name of NGO<br>  Entity</strong></th>
                            <th style="border: 1px solid #e6e7e8" align="left"><strong>          Country</strong></th>
                            <th style="border: 1px solid #e6e7e8" align="left"><strong>Z-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>A-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>B-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>C-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>D-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>E-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>F-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>G-NGO</strong></th>
                            <th style="border: 1px solid #e6e7e8"><strong>H-NGO</strong></th>
 
                          
                          </tr>
                        </thead>
                        <tbody class="metro-tile metro-tile-small metro-tile-purple" id="tbodycontent">
                        </tbody>
                      </table>
                                    </div>
                                                                                <div id="pageNavPosition" style="padding-top: 1px" align="center">
                                                                                </div>
                
                  </div>
                </div>
              </div>
              <!--Ends Body Section -->
            </div>
 
 <asp:HiddenField ID="ipAdrressHiden"  runat="server"></asp:HiddenField>
<input type="text" id="lblMessage" title="No Record Found" value="No Record Found"  style="display:none;"/>
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
        {
         //HttpContext.Current.Response.Write("hello");
         GetUser_IP();
        
                                }
protected void GetUser_IP()
{
                string ipaddress;
                ipaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (ipaddress == "" || ipaddress == null)
                {
                                ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                ipAdrressHiden.Value=ipaddress;
}
</script>
              <!--Start Helpdesk Email Section -->
 
 
</asp:Content>
 
 
JS File :
var NoRecord = "No Record Found";
var vrNewDocumentListGUID = '08C96C6F-AEE0-4BD9-9C89-7305DB0B9FBC';
var monthNames = [
   "Jan", "Feb", "Mar",
   "Apr", "May", "Jun", "Jul",
   "Aug", "Sep", "Oct",
   "Nov", "Dec"
];
var LibraryNameForUpdate='NGO';
var statusApproved = 'Approved';
var statusRejected = "Rejected";
var statusPending = "Pending";
/************************************************************************************************************************************************/
/******************************Document Ready function******************************************************************************************************************/
// Function to execute when page loads.
 
$(document).ready(function() {
 
   //Get the watermark in search text box
    var watermark = 'Search Item';
    $('#txtSearch').blur(function () {
        if ($(this).val().length == 0)
            $(this).val(watermark).addClass('watermark');
    }).focus(function () {
        if ($(this).val() == watermark)
            $(this).val('').removeClass('watermark');
    }).val(watermark).addClass('watermark');
    //ExecuteOrDelayUntilScriptLoaded(BindDropDown,'sp.js');
    ServerrelativeURL = location.protocol + '//' + location.host;
    BrowserUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
    updateClock();
    init();
    BindDropDown();
    $('.home_bg').addClass('remove_home_bg');
    $('.home_bg').removeClass('home_bg');
    $("#CompanyView").css("display", "block");
    $("#welcomeContentTiles").css("display", "none");
   // Start  Search Opration
   $("#btnsubmit").click(function ()
     {
                     if($('#ddlCompanyName').val()=='Select')
                     {
                             alert('Please select right option!!');
                                                 $('#responsiveGrid').hide()
                                                 $('.loader').hide();
                                                 return false;
                     }
                     else
                     {
                      $('.loader').show();
                      getFolderAllDocumentsItems($('#ddlCompanyName').val());
                     }
     });
// End  Search Opration
                $('#txtSearch').keyup(function () {
                                SearchGridData();
                            });
                });
//ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
function updateClock() {
    var vrDate = new Date();
    var count = 0;
    $('#clock_digital1').jClocksGMT({
        offset: (vrDate.getTimezoneOffset() / 60) * (-1),
        digital: true
    });
    $('#clock_analog1').jClocksGMT({
        offset: (vrDate.getTimezoneOffset() / 60) * (-1),
        analog: true
    });
}
 
function BindDropDown() {
    var glbData = '';
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('NGO/')/Folders/?$filter=Name ne 'Forms'",
        type: "Get",
        async: false,
        headers: {
           "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        data: JSON.stringify({
            query: {
                __metadata: {
                    type: "SP.CamlQuery"
                },
                ViewXml: "<View><Query><Where><Neq><FieldRef Name='FileLeafRef' /><Value Type='File'>Forms</Value></Neq></Where></Query><ViewFields /><QueryOptions /></View>"
            }
        }),
        success: function(data) {
     
        $.each(data.d.results, function(key, value) {
          $("#ddlCompanyName").append("<option value=" +   value.Name + ">" + value.Name+ "</option>");
         
        });
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });
   
/* $("#ddlCompanyName").change(function(){
     $('#responsiveGrid').show()
                var  companyname = this.value;
                if(companyname=='Select')
                {
                                alert('Please select right option!!');
                                 $('#responsiveGrid').hide()
                                return false;
                }
                else
                {
                                getFolderAllDocumentsItems(companyname)
                }
               
    });*/
}
function getFolderAllDocumentsItems(folderName) {
   $('.loading').show();
        var glbData = '';
        var resultGridHtml = '';
        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('NGO/" + folderName +"')/Folders?$orderby=Name&$expand=ListItemAllFields,ListItemAllFields/ParentList",
            type: "Get",
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "content-Type": "application/json;odata=verbose"
            },
            success: function(data) {
              
                glbData = data;
                BindFolderAllDocumentsItems(glbData, folderName);
               
            },
            error: function(error) {
                alert(JSON.stringify(error));
            }
        });
    }
    /************************************************************************************************************************************************/
function BindFolderAllDocumentsItems(data, folderName) {
    var resultGridHtml = '';
    var vrListGUID = '';
    var vrShowIndex = 1;
    var vrAuthorId = '';
    var vrEditorId = '';
    var vrSrNo = 1;
      $.each(data.d.results, function(key, value) {
        if (value.Name != "Forms") {
                var FolderPath=value.ServerRelativeUrl.substring(15) + '/' + $('#ddlYear').val();
                var LastFolderName= GetAllFoldersofRootFolders(FolderPath);
                var splitLastFolderName=LastFolderName.split('/');
               if(splitLastFolderName.length>=9)
               {
                var Col1=FolderPath+ "/" + splitLastFolderName[0];
                var Col2=FolderPath+ "/" + splitLastFolderName[1];
                var Col3=FolderPath+ "/" + splitLastFolderName[2];
                var Col4=FolderPath+ "/" + splitLastFolderName[3];
                var Col5=FolderPath+ "/" + splitLastFolderName[4];
                var Col6=FolderPath+ "/" + splitLastFolderName[5];
                var Col7=FolderPath+ "/" + splitLastFolderName[6];
                var Col8=FolderPath+ "/" + splitLastFolderName[7];
                var Col9=FolderPath+ "/" + splitLastFolderName[8];
                resultGridHtml += '<tr>';
                resultGridHtml += '<td align="center" valign="middle"><span title="Sr.No."><b>' + vrSrNo + '</b></span></td>';
                resultGridHtml += '<td valign="middle" folderPath=\'' + value.ServerRelativeUrl.substring(1) + '\'>'+ value.Name +'</td>';
                resultGridHtml += '<td valign="middle">India</td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col1" class="FolderName" folderPath=\'' + Col1 + '\' align="center" valign="middle"></td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col2" class="FolderName" folderPath=\'' + Col2 + '\' align="center" valign="middle"></td>';              
                resultGridHtml += '<td id="row'+vrSrNo+'col3" class="FolderName" folderPath=\'' + Col3 + '\' align="center" valign="middle"></td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col4" class="FolderName" folderPath=\'' + Col4 + '\' align="center" valign="middle"></td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col5" class="FolderName" folderPath=\'' + Col5 + '\' align="center" valign="middle"></td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col6" class="FolderName" folderPath=\'' + Col6 + '\' align="center" valign="middle"></td>';               
                resultGridHtml += '<td id="row'+vrSrNo+'col7" class="FolderName" folderPath=\'' + Col7 + '\' align="center" valign="middle"></td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col8" class="FolderName" folderPath=\'' + Col8 + '\' align="center" valign="middle"></td>';
                resultGridHtml += '<td id="row'+vrSrNo+'col9" class="FolderName" folderPath=\'' + Col9 + '\' align="center" valign="middle"></td>';                 
                resultGridHtml += '</tr>';
                vrSrNo++;
                }
        }
    });
      if (resultGridHtml.length == 0) {
            var resultGridHtml = '';
            resultGridHtml += '<tr>';
            resultGridHtml += '<td  colspan="12" align="center" valign="middle">' + NoRecord + '</td>';
            resultGridHtml += '</tr>';
        }
        $("#tbodycontent").html(resultGridHtml);
        $("#CompanyView").css("display", "block");
        $("#welcomeContentTiles").css("display", "none");
        $('#responsiveGrid').show()
        $('.loader').hide();
        // Code For File Count in Folder
        $('#tablepaging tr td.FolderName').each(function() {
                var path=$(this).attr('folderPath')            //Do your work 
                //var totalCount=GetAllFileCountInParticularFolder(path,this);
                GetAllFileCountInParticularFolder(path,this);
                                })
}
function GetAllFoldersofRootFolders(FolderPath)
     {        
                var lastFoltehrPath="";
                //alert(FolderPath);
                $.ajax(
                {
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('NGO/" + FolderPath +"')/Folders?$orderby=Name&$expand=ListItemAllFields,ListItemAllFields/ParentList",
                method: "GET",
                async: false,
                headers: {
                    "ACCEPT": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose"                        
                },
                success: function (data)
                {
                    $.each(data.d.results, function(){
                    if(lastFoltehrPath=="")
                    {
                     lastFoltehrPath=this.Name;
                    }
                    else
                    {
                     lastFoltehrPath=lastFoltehrPath + "/" + this.Name;
                    }
                    });
                },
                error: function (data)
                
                {
                  //alert("Error occured." + data);
                }
              
     }); 
     return lastFoltehrPath;                                              
}
/************************************************************Start Getting  Approved File count  ************************************************************************************/
function GetAllFileCountInParticularFolder(folderName,element)
{  debugger;
    var TotalfileCountApprval=0;
    var TotalfileCountPending=0;
    var dataFlagApprval=true;
    var dataFlagPending=true;
    var NoRecord=true;   
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('NGO/" + folderName + "/')/Files?$orderby=Title&$expand=ListItemAllFields,ListItemAllFields/ParentList", //?$expand=Files",
        type: "Get",
        async: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        success: function(dataresult) {
            $.each(dataresult.d.results, function(key, value) {
            NoRecord=false;
            if (value.Name != "Forms")
            {
            if(value.ListItemAllFields["OData__ModerationStatus"] == 0)
            {
             dataFlagApprval=false;
             TotalfileCountApprval+=1;
            }
            else if(value.ListItemAllFields["OData__ModerationStatus"] == 2)
            {
             dataFlagPending=false;
             TotalfileCountPending+=1;
            }
            }
            });
            if((dataFlagApprval==false)||(dataFlagPending==false))
            {
               var strApp='<span title="' + statusApproved + '"  class="' + statusApproved .toLowerCase() + '-icon"><b>' + statusApproved + '</b></span>&nbsp;<span style="position: absolute;">('+TotalfileCountApprval+')</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="' + statusPending + '" class="' + statusPending .toLowerCase() + '-icon"><b>' + statusPending + '</b></span>&nbsp;<span style="position: absolute;">('+TotalfileCountPending+')</span>';
               $(element).append(strApp);
            }
        },
        error: function(error) {
        }
      });
                                if(NoRecord==true)
                                {
                                var strApp='<span><b>--</b></span>';
                                $(element).append(strApp);
                                }
}
function fnExcelReport()
    {
         var tab_text="<table border='2px'><tr bgcolor='#D1D3D4'>";
         var textRange; var j=0;
                 tab = document.getElementById('tablepaging'); // id of table
         for(j = 0 ; j < tab.rows.length ; j++)
          {    
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }
          tab_text=tab_text+"</table>";
          tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
          tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
          var ua = window.navigator.userAgent;
         var msie = ua.indexOf("MSIE ");
          if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
             {
                   txtArea1.document.open("txt/html","replace");
                   txtArea1.document.write(tab_text);
                   txtArea1.document.close();
                   txtArea1.focus();
                   Ram=txtArea1.document.execCommand("SaveAs",true,"NGO_Report.xls");
             } 
          else                 //other browser not tested on IE 11
                   Ram= window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); 
                   return (Ram);
}
function PrintDocument(divName) {
     var printcontents = document.getElementById(divName).innerHTML;
     var originablecontents = document.body.innerHTML;
     document.body.innerHTML = printcontents;
     window.print();
     document.body.innerHTML = originablecontents;
}
 
function SearchGridData() {
            var counter = 0;
           //Get the search text
            var searchText =  $('#txtSearch').val().toLowerCase();
             //Hide No record found message
            $('#lblMessage').hide();
             //Hode all the rows of gridview
             $('#tablepaging tr:has(td)').hide();
             if (searchText.length > 0) {
                 //Iterate all the td of all rows
                 $('#tablepaging tr:has(td)').children().each(function () {
                    var cellTextValue = $(this).text().toLowerCase();
                    //Check that text is matches or not
                    if (cellTextValue.indexOf(searchText) >= 0) {
                        $(this).parent().show();
                        counter++;
                    }
                });
                if (counter == 0) {
                    //Show No record found message
                   // alert('No Record Found');
                    $('#lblMessage').show();
                }
            }
            else {
                //Show All the rows of gridview
                $('#tablepaging tr:has(td)').show();
            }
        }

Get Folder and File Using JSOM Bind Dynamic Table

$
0
0
Call On Document ready Function
 
  //GetFolders("NGO",1);
 
function GetFolders(folderName)
{
                //checkPermissions(folderName,selectedLink);
                this.folderName=folderName;
                //this.selectedLink=selectedLink;
                var context = new SP.ClientContext.get_current();
                var web = context.get_web();
                var list = web.get_lists().getByTitle(LibraryNameForUpdate);
                var query = new SP.CamlQuery();
                query.set_folderServerRelativeUrl(folderName);
                var q = '<View><Query><OrderBy><FieldRef Name=\'ID\' Ascending=\'True\' /></OrderBy></Query></View>';
                query.set_viewXml(q);
                allItems = list.getItems(query);
                this.listInfoArray=context.load(allItems);
                context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success()
{
   //checkPermissions(this.folderName,this.selectedLink);
                var resultGridHtml='';
                var vrSrNo = 1;
                var noRecords='true';
                var ListEnumerator = this.allItems.getEnumerator();
               
                while(ListEnumerator.moveNext())
                {
                var currentItem = ListEnumerator.get_current();
                                var _contentType = currentItem.get_fileSystemObjectType();
                     if(currentItem.get_fileSystemObjectType() == '1')
                                {
                                                               
                                                                if(vrSrNo==1)
                                                                {
                                                                                resultGridHtml +='<table width="100%" id="tablepaging" class="table">';
                                                                                resultGridHtml +=FolderHeader();
                                                                               
                                                                }
                                                                noRecords='false';
                                                                var selectedLink=1;
                                                                var fieldUserValueCreatedBy = currentItem.get_item("Author");
                var fieldUserValueModifiedBy = currentItem.get_item("Editor");
                var dateCreated = new Date(currentItem.get_item('Created'));
                                                                resultGridHtml += '<tr>';
                resultGridHtml += '<td>'+ currentItem.get_item('Title')+'</td>';
                resultGridHtml += '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() +  '</td>';
                resultGridHtml += '<td>' + fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                resultGridHtml += '<td>' + fieldUserValueModifiedBy.get_lookupValue() + '</td>';
                resultGridHtml += '</tr>';           
                vrSrNo =vrSrNo + 1;
                
 
                                                //FolderNames  += currentItem.get_item('Title')+ '\n';
                                }
                                if(currentItem.get_fileSystemObjectType() == '0')
                                {
                                                               
                                                                var dateCreated = new Date(currentItem.get_item('Created'));
                                                                var selectedLink=1;
                                                                var fieldUserValueCreatedBy = currentItem.get_item("Author");
                var fieldUserValueModifiedBy = currentItem.get_item("Editor");
                noRecords='false';
                                                     if(vrSrNo==1)
                                                                                {
                                                                    resultGridHtml +='<table width="100%" id="tablepaging" class="table">';
                                                                                resultGridHtml +=FileHeader();
                                                                    }
                                                                                resultGridHtml += '<tr>';
                                                                                resultGridHtml += '<td>'+ currentItem.get_item('Title')+'</td>';
                                                                                resultGridHtml += '<td>' + dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear() + '</td>';                    
                                                                                resultGridHtml += '<td>' + fieldUserValueCreatedBy.get_lookupValue() + '</td>';
                                                                                resultGridHtml += '<td>' + fieldUserValueModifiedBy.get_lookupValue() + '</td>';
                                resultGridHtml += '</tr>';
                                vrSrNo =vrSrNo + 1;
               
            }
    }
   
                                                                if(noRecords=='true')
                                                                {
                                                                                resultGridHtml +='<table width="100%" id="tablepaging" class="table">';
                                                                                resultGridHtml +=FileHeader();
                                                                    resultGridHtml +='<tr><td colspan="9">No records found</td><tr>';
                                                                   
                                                                }                                                                                             
                resultGridHtml +='<table>';
    $('#responsiveGrid').html(resultGridHtml);
}
function failed(sender, args)
{
                //alert("failed. Message:" + args.get_message());
}
 
function FileHeader()
{
                var vHeaderFile='';
                vHeaderFile +='<thead>';
                vHeaderFile +='<tr  valign="top">';
    vHeaderFile +='<th align="left">Name</th>';
    vHeaderFile +='<th align="left">Created On</th>';
    vHeaderFile +='<th align="left">Created By</th>';
    vHeaderFile +='<th align="left">Modified By</th>';
    vHeaderFile +='</tr>';
    vHeaderFile +='</thead>';
    return vHeaderFile;
 
}
function FolderHeader()
{
                var vHeaderFolder='';
                vHeaderFolder +='<thead>';
                vHeaderFolder +='<tr valign="top">';
    vHeaderFolder +='<th align="left">Name</th>';
    vHeaderFolder +='<th  align="left">Created On</th>';
    vHeaderFolder +='<th  align="left">Created By</th>';
    vHeaderFolder +='<th  align="left">Modified By</th>';
    vHeaderFolder +='</tr>';
    vHeaderFolder +='</thead>';
    return vHeaderFolder;
}

Return function in Jquery

$
0
0
Call Function :

Var strbname= GetAllFileCountInParticularFolder(“NGO/Ram”,element);


Function :
function GetAllFileCountInParticularFolder(folderName,element)
{
    var TotalfileCount=0; 
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderName + "/')/Files?$orderby=Title&$expand=ListItemAllFields,ListItemAllFields/ParentList", //?$expand=Files",
        type: "Get",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        success: function(dataresult) {
            $.each(dataresult.d.results, function(key, value) {
            if (value.Name != "Forms") {
            if(value.ListItemAllFields["OData__ModerationStatus"] == 0)
            {
               
              TotalfileCount+=1;
             $(element).append( "<strong>( "+TotalfileCount+" )</strong>" );
            }
            }
            });
         
        },
        error: function(error) {
            //                                                alert(JSON.stringify(error));
        }
    });
   
  return TotalfileCount;
}

Get Folder count

$
0
0
function GetAllFileCountInParticularFolder(folderName,element)
{
    var TotalfileCount=0; 
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + folderName + "/')/Files?$orderby=Title&$expand=ListItemAllFields,ListItemAllFields/ParentList", //?$expand=Files",
        type: "Get",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        success: function(dataresult) {
            $.each(dataresult.d.results, function(key, value) {
            if (value.Name != "Forms") {
            if(value.ListItemAllFields["OData__ModerationStatus"] == 0)
            {
               
              TotalfileCount+=1;
             $(element).append( "<strong>( "+TotalfileCount+" )</strong>" );
            }
            }
            });
         
        },
        error: function(error) {
            //                                                alert(JSON.stringify(error));
        }
    });
   
    
}
Viewing all 542 articles
Browse latest View live