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

Add Feedback in any Area /Item

$
0
0






















Code  In  WebPart:
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
                <SharePoint:ListItemProperty Property="BaseName" maxlength="40" runat="server"/>
<ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><ZoneTemplate></ZoneTemplate><WebPartPages:WebPartZone runat="server" ID="__WebPartPageLibraryZone__"><ZoneTemplate><WebPartPages:TitleBarWebPart runat="server" HeaderTitle="Untitled_1" Title="Web Part Page Title Bar" FrameType="None" SuppressWebPartChrome="False" Description="" IsIncluded="True" ZoneID="__WebPartPageLibraryZone__" PartOrder="1" 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_72a98a1d_b438_4292_bffa_fa3540ee16ea" AllowClose="False" ChromeType="None" ExportMode="All" __MarkupType="vsattributemarkup" __WebPartId="{72A98A1D-B438-4292-BFFA-FA3540EE16EA}" WebPart="true" Height="" Width=""></WebPartPages:TitleBarWebPart>

                </ZoneTemplate></WebPartPages:WebPartZone></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 = "WSSEndUser";
                </SharePoint:ScriptBlock>
<style type="text/css">
.Empty
    {
     
       /* background:url("../SiteAssets/StarFeedbackImages/Empty.jpg") no-repeat top left;*/
       /* background-image:url('../SiteAssets/StarFeedbackImages/Empty.jpg');*/
       background: url("../SiteAssets/StarFeedbackImages/Empty.jpg") !important;
       min-width:2em !important;
       padding:3px 10px !important;
      
              
     }
   
        .Empty:hover
    {
                       background-image: url("../SiteAssets/StarFeedbackImages/Filled.png") !important;
                        min-width:2em !important;
                        padding:3px 10px !important;


                      /*  background: url('/SiteAssets/StarFeedbackImages/Filled.png');*/

    }
    .Filled
    {
                       background-image: url("../SiteAssets/StarFeedbackImages/Filled.png") !important;
                        min-width:2em !important;
                        padding:3px 10px !important;


                       
                               
        /*background: url('/SiteAssets/StarFeedbackImages/Filled.png') no-repeat top left;*/

    }
   
    input[type=button]button
    {
                min-width:2em!important;
}

.btnSubmitCss
{
/*background-color:gray!important;
color:white!important;*/
position:absolute;
margin-left:520px;
margin-top:-30px;
}

.ms-dlgTitle
{
                background:lightgray!important;
}

.ms-cui-topBar2
{
                display:none;
}
</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 src="../SiteAssets/Script/jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Decide(option) {
    //alert('Hi');
        var temp = "";
        document.getElementById('lblRate').innerText = "";
        if (option == 1) {
            document.getElementById('Rating1').className = "Filled";
            document.getElementById('Rating2').className = "Empty";
            document.getElementById('Rating3').className = "Empty";
            document.getElementById('Rating4').className = "Empty";
            document.getElementById('Rating5').className = "Empty";
            temp = "1-Poor";
        }
        if (option == 2) {
            document.getElementById('Rating1').className = "Filled";
            document.getElementById('Rating2').className = "Filled";
            document.getElementById('Rating3').className = "Empty";
            document.getElementById('Rating4').className = "Empty";
            document.getElementById('Rating5').className = "Empty";
            temp = "2-Ok";

        }
        if (option == 3) {
            document.getElementById('Rating1').className = "Filled";
            document.getElementById('Rating2').className = "Filled";
            document.getElementById('Rating3').className = "Filled";
            document.getElementById('Rating4').className = "Empty";
            document.getElementById('Rating5').className = "Empty";
            temp = "3-Fair";
        }
        if (option == 4) {
            document.getElementById('Rating1').className = "Filled";
            document.getElementById('Rating2').className = "Filled";
            document.getElementById('Rating3').className = "Filled";
            document.getElementById('Rating4').className = "Filled";
            document.getElementById('Rating5').className = "Empty";
            temp = "4-Good";
        }
        if (option == 5) {
            document.getElementById('Rating1').className = "Filled";
            document.getElementById('Rating2').className = "Filled";
            document.getElementById('Rating3').className = "Filled";
            document.getElementById('Rating4').className = "Filled";
            document.getElementById('Rating5').className = "Filled";
            temp = "5-Nice";
        }
        document.getElementById('lblRate').innerText = temp;
        return false;
    }
   
    
    function AddFeedbacInList()
{
   var siteurl=_spPageContextInfo.siteAbsoluteUrl;
    var clientContext = new SP.ClientContext(siteurl);
    var web=clientContext.get_web();
    var oList = web.get_lists().getByTitle('Feedback');
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    var feedback=$('#txtfeedback').val();
    if (feedback.length<1)
    {
     alert('Comment cannot be blank');
     return false;
    }
  
    var feedbackRatingVal=$('#lblRate').text();
    oListItem.set_item('Title', feedback);
    oListItem.set_item('feedback',feedback);
    oListItem.set_item('FeedbackRating',feedbackRatingVal);
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}

function onQuerySucceeded() {
   alert('Submitted Successfully!!');
   $('#txtfeedback').val('');
   window.frameElement.commitPopup();


}

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



</script>
<!--<table id="tblfeedback" style="position:relative;"><tr><td style="padding-top:45px;"><b>Feedback:</b></td><td><div id="Divfeedbackdiv" style="padding-top:13px;position:absolute;"><textarea id="txtfeedback" maxlength="500" placeholder="Please Type your feedback here" style="width:400px;height:200px;border:1px solid black;padding-top:0px;"></textarea></div></td></tr>-->
<table id="tblfeedback" style="position:relative;"><tr><td><div id="divFeedback" style="position:absolute;padding-top:3px;"><b>Feedback:</b></div></td><td><div id="Divfeedbackdiv" style="padding-top:0px;position:absolute;"><textarea id="txtfeedback" maxlength="500" placeholder="Please Type your feedback here" style="width:400px;height:200px;border:1px solid black;padding-top:0px;"></textarea></div></td></tr>
<tr><div id="divfeedbackRating"><td style="padding-top:230px;"><b>Please give an overall rating :</b></td><td style="padding-top:226px;"><label id="lblRate"></label>
<input type="button"  ID="Rating1" class="Empty"  onclick="return Decide(1);" style="border:none;" width="20px" height="20px"/>
<input type="button"  ID="Rating2" class="Empty"   onclick="return Decide(2);" style="border:none;"/>
<input type="button"  ID="Rating3"  class="Empty"   onclick="return Decide(3);" style="border:none;"/>
<input type="button"  ID="Rating4"  class="Empty"   onclick="return Decide(4);" style="border:none;"/>
<input type="button"  ID="Rating5" class="Empty"  onclick="return Decide(5);" style="border:none;"/>
</td></div></tr>
<tr><td><div class="btnSubmitCss"><input type="button" value="Submit" id="btnSubmit" onclick="AddFeedbacInList();" style="background:lightgray;color:black;font-weight:bold"></div></td></tr>
</table>
</asp:Content>


Explain webpart life cycle.

$
0
0
Q. Explain webpart life cycle.

Ans. protected override void OnInit(EventArgs e)

  1. protected override void OnLoad(EventArgs e)
  2. protected override void CreateChildControls()
  3. protected override void LoadViewState(object savedState) //Only at Postback
  4. protected override void OnPreRender(EventArgs e)
  5. protected override void Render(System.Web.UI.HtmlTextWriter writer)
  6. protected override void OnUnload(EventArgs e)
  7. public override void Dispose()

Get LookUp and Author Name Using REST API + SharePoint 2013

$
0
0
How to get Author/Title or Name from AuthorID = dataResults.Title

function getUser(id, tdHtml){


   var returnValue;
     jQuery.ajax({
      url: "https://YourSite/_api/Web/GetUserById(" + id + ")",
      type: "GET",
      headers: { "Accept": "application/json;odata=verbose" },
      success: function(data) {
             var dataResults = data.d;
          alert(dataResults.Title);
       
      }
    });
  }

How to get Author/Title or Name from AuthorID in one single Rest call / query


/_api/web/lists/getbytitle('KhaitanDocLib')/items?$select=Author/Title,PracticeArea/Title&$expand=Author/Id,PracticeArea

How to get permission of a sharepoint list for a user using REST api

$
0
0
Use EffectiveBasePermissions to get permissions of the user on a list. Example:
http://aissp2013/sites/Team/_api/web/lists/getbytitle('L2')/EffectiveBasePermissions
Note that this will give the permissions of the logged in user. However, if the need is to check for other users permission while being logged in using as a different user then as suggested by @Amit, use getusereffectivepermissions. In any case the end result is high and low permission masks which don’t make much sense and a way to decipher what permissions a user has is to use SP.BasePermissions().has as can be seen in below example:
function checkPermissions() {
var call = jQuery.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/effectiveBasePermissions",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});

call.done(function (data, textStatus, jqXHR) {
var manageListsPerms = new SP.BasePermissions();
manageListsPerms.initPropertiesFromJson(data.d.EffectiveBasePermissions);

var manageLists = manageListsPerms.has(SP.PermissionKind.manageLists);

var message = jQuery("#message");
message.text("Manage Lists: " + manageLists);
});
}

Code In Rest API To  Check Permission  in Item Level:(Implemented Code)





function checkPermissions(folderName,selectedLink) {


                $.ajax({


        url: _spPageContextInfo.webAbsoluteUrl +


            "/_api/web/GetFolderByServerRelativeUrl('"+folderName+"')/ListItemAllFields/effectiveBasePermissions",


        type: "GET",


        dataType: "json",


        headers: {


            Accept: "application/json;odata=verbose"


        },


        success: function(data,status,xhr){


       


        var manageListsPerms = new SP.BasePermissions();


        manageListsPerms.initPropertiesFromJson(data.d.EffectiveBasePermissions);


                                var manageLists = manageListsPerms.has(SP.PermissionKind.editListItems);


                                //console.log(manageLists);


                                if(manageLists==true)


                                {


                                                                                var ht='<a title="Add a new item to this list or library." href="javascript:void(0);" onclick="AddNewDocument(\''+folderName+'\',\''+selectedLink+'\')" target="_self"><i class="add-new">+</i> New Document</a>';


                                $('#pAddNewDocument').html(ht);


                                $('#pAddNewDocument').show();


                                                $('#pAddNewDocument').show();


                                }else


                                {


                                                $('#pAddNewDocument').hide();


                                }


 


               


    },


    error: function(xhr, status, error){


                $('#pAddNewDocument').hide();


        //alert("Error!" + xhr.status);


    }


    });


                /*           call.done(function (data, textStatus, jqXHR) {


        var manageListsPerms = new SP.BasePermissions();


        manageListsPerms.initPropertiesFromJson(data.d.EffectiveBasePermissions);


                                var manageLists = manageListsPerms.has(SP.PermissionKind.editListItems);


                                if(manageLists==true)


                                {


                                                $('#pAddNewDocument').show();


                                }else


                                {


                                                $('#pAddNewDocument').hide();


                                }*/


}






Using SP.PermissionKind ECMAScript\Javascript Client Object model





With SP.PermissionKind you can check if th ecurrent user has permissions of a specfic permission type. See an example where we check if the current user has ListEdit permissions

Lets Look at the Specifies permissions that are used to define user roles

Permission Name emptyMask - Has no permissions on the Web site. Not available through the user interface.

viewListItems - View items in lists, documents in document libraries, and Web discussion comments.

addListItems - Add items to lists, add documents to document libraries, and add Web discussion comments.

editListItems - Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.

deleteListItems - Delete items from a list, documents from a document library, and Web discussion comments in documents.

approveItems - Approve a minor version of a list item or document.

openItems - View the source of documents with server-side file handlers.

viewVersions - View past versions of a list item or document.

deleteVersions - Delete past versions of a list item or document.

cancelCheckout - Cancel or check in a document that is checked out to another user.

managePersonalViews - Create, change, and delete personal views of lists.

manageLists -
 Create and delete lists, add or remove columns in a list, and add or remove public views of a list.

viewFormPages - 
View forms, views and application pages, and enumerate lists.

open - Open a Web site, list, or folder to access items inside the container.

viewPages - 
View pages in a Web site.

addAndCustomizePages - Add, change, or delete HTML pages, and edit the Web site using an editor that is compatible with Microsoft SharePoint Server 2010.

applyThemeAndBorder - Apply a theme or borders to the Web site.

applyStyleSheets - Apply a style sheet (.css file) to the Web site.

viewUsageData - View reports on Web site usage.

createSSCSite - Create a Web site using Self-Service Site Creation.

manageSubwebs - Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.

createGroups - Create a group of users that can be used anywhere within the site collection.

managePermissions - Create and change permission levels on the Web site and assign permissions to users and groups.

browseDirectories - Enumerate files and folders on a site using Microsoft SharePoint Designer and WebDAV interfaces.

browseUserInfo - View information about the users of the Web site.

addDelPrivateWebParts - Add or remove personal Web Parts on a Web Part Page.

updatePersonalWebParts - Update Web Parts to display personalized information.

manageWeb -
 Grant the ability to perform all administration tasks for the Web site and manage Web site content.

useClientIntegration - Launch client applications on the server. Otherwise, users must work on documents locally and upload changes.

useRemoteAPIs - Use SOAP, WebDAV, or Microsoft SharePoint Designer interfaces to access the Web site.

manageAlerts - Manage alerts for all users of the Web site.

createAlerts - Create e-mail alerts.

editMyUserInfo - Change user information, such as adding a picture.

enumeratePermissions - Enumerates permissions on the Web site, list, folder, document, or list item.

fullMask - Has all permissions on the Web site. Not available through the user interface. 








Get All File in Folder Using JSOM

$
0
0
function ViewAllFiles()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('NGO-Document');
var query = SP.CamlQuery.createAllItemsQuery();
query.set_folderServerRelativeUrl('/NGO-Document/NGOFolder');
allItems = list.getItems(query);
context.load(allItems, 'Include(Title, ContentType, File)');
context.executeQueryAsync(Function.createDelegate(this, this.success),   Function.createDelegate(this, this.failed));
}
 
function success()
{
debugger;
  var fileUrls = "";
  var ListEnumerator = this.allItems.getEnumerator();
   while(ListEnumerator.moveNext())
   {
    var currentItem = ListEnumerator.get_current();
    var _contentType = currentItem.get_contentType();
     if(_contentType.get_name() != "Folder")
       {
        var File = currentItem.get_file();
        if(File != null)
          {
           fileUrls += File.get_serverRelativeUrl() + '\n';
          }
       }
   }
  alert(fileUrls);
}
function failed(sender, args) {
  alert("failed. Message:" + args.get_message());
}
 

Get All Item Of Library or List in All Folder Using Rest Api (recursivily)/ Using Caml query

$
0
0
function GetAllFoldersofRam()
{
var thisUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('NGO-DCUMENT)/GetItems"; 
var caml = '<View Scope="Recursive"><Query><ViewFields><FieldRef Name="Name" /></ViewFields> </Query></View>'; 
$.ajax({ 
    url: thisUrl, 
    type: "POST",
    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": caml}}),           
    success: function (data){ 
    alert(data.d.results.length);
        // data.d will yield the required results 
    }, 
    error: function (data){ 
        console.log("Error in query");           
    } 
}); 
}

Useful Link:
https://platinumdogs.me/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/
http://www.c-sharpcorner.com/blogs/filter-documents-from-sharepoint-libraries-by-metadata-using-rest-api 

Dum File in Network Location or Drive Location (Site/SubSite)

$
0
0
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
using System.Collections.Specialized;
namespace NGOFileDumpProcess
{
    class NGOFileDumpTimmerJobSPJobDefinition
    {
       
        public NGOFileDumpTimmerJob() : base()
        { }
        public NGOFileDumpTimmerJob(string jobName, SPService service) : base(jobName, service,nullSPJobLockType.None)
        {
            this.Title = "NGO File Dump Process";
        }
        public NGOFileDumpTimmerJob(string jobName, SPWebApplication webapp) : base(jobName, webapp, nullSPJobLockType.ContentDatabase)
        {
            this.Title = " NGO File Dump Process";
        }
        #region Excute Method Of Timer Jobs
        // string qq=System.Configuration.ConfigurationManager.AppSettings["siteURL"];
        string siteurl1 = "";
        string UrlandDumpLocation = string.Empty;
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                SPWebApplication webApplication = this.Parent as SPWebApplication;
                // get a reference to the current site collection's content database
                SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];
                // get a reference to the "site" list in the RootWeb of the first sitecollection in the content database
                string weburl = contentDb.Sites[0].RootWeb.Url;
                //Getting the List from the Current All Webs
                SPList timeerJobList = webApplication.Sites[0].AllWebs["/GET"].Lists["FileDumpConfigurationSettings"];
                //Getting the SPListItemCollection
                SPListItemCollection itemcollection = timeerJobList.GetItems();
                foreach (SPListItem spListItem in itemcollection)
                {
                    if (UrlandDumpLocation == "")
                    {
                        UrlandDumpLocation = spListItem["Title"].ToString().Trim() + "|" + spListItem["DumpLocationPath"].ToString().Trim() + "|" + spListItem["LibraryName"].ToString().Trim();

                    }
                }
              
               SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    DownLoadFiles(UrlandDumpLocation);
                });
            }
            catch (IOException ex)
            {
                WriteLog(UrlandDumpLocation, " Error in Function Execute :" + ex.Message);
            }
        }
        public void DownLoadFiles(string UrlandDumpLocation)
        {
            if (UrlandDumpLocation!="")
            {
                string siteUrl = UrlandDumpLocation.Split('|')[0].ToString();
                string filePath = UrlandDumpLocation.Split('|')[1].ToString();
                string LibraryName = UrlandDumpLocation.Split('|')[2].ToString();
                // getting Record of Curret month
               // string Month = DateTime.Now.AddMonths(-1).ToString("MM");
                string Month = DateTime.Now.ToString("MM");
                string Year = DateTime.Now.ToString("yyyy");
                //
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                using (SPSite site = new SPSite(siteUrl))
                {
                  using (SPWeb web = site.OpenWeb())
                    {
                      // get the required document library
                      SPList docLib = web.Lists[LibraryName];
                      SPListItemCollection items = docLib.GetItems();
                      // code to download documents
                     // loop through each item or document in the document library
                       Boolean Varicreatefile = false;
                        if(items.Count>0)
                        {
                            foreach (SPListItem item in items)
                            {
                                string FolderPathLocation = "";
                                // Access the file
                                SPFile file = item.File;
                                string fileCreationdateMonth =Convert.ToDateTime(item["Created"].ToString()).ToString("MM");
                                string fileCreationdateYear =Convert.ToDateTime(item["Created"].ToString()).ToString("yyyy");
                                if (Month == fileCreationdateMonth && Year == fileCreationdateYear)
                                {
                                   if (file != null)
                                    {
                                        // retrieve the file as a byte array
                                        try
                                        {
                                            //SPFieldLookupValueCollection values = new SPFieldLookupValueCollection(item["Location"].ToString());
                                           // foreach (SPFieldLookupValue value in values)
                                           // {
                                               
                                                Varicreatefile = true;
                                                //Directory.CreateDirectory(filePath + value.LookupValue);
                                                Directory.CreateDirectory(filePath);
                                                byte[] bArray = file.OpenBinary();
                                                // FolderPathLocation = Path.Combine(filePath + value.LookupValue, file.Name);
                                                FolderPathLocation = Path.Combine(filePath, file.Name);
                                                //open the file stream and write the file
                                                using (FileStream fs = newFileStream(FolderPathLocation, FileMode.Create, FileAccess.ReadWrite))
                                                {
                                                    fs.Write(bArray, 0, bArray.Length);
                                                   
                                               }
                                               // }
                                        }
                                        catch (IOException ex)
                                        {
                                            WriteLog(UrlandDumpLocation, " Error in DownLoadFiles()" + ex.Message);
                                        }
                                    }
                                }
                            }
                            if (Varicreatefile == true)
                            {
                             
                                WriteLog(UrlandDumpLocation,"File Dump Process is Successfully");
                            }
                            else
                            {
                                WriteLog(UrlandDumpLocation, "No Item for File Dumpimg  Process");
                              
                            }
                           
                        }
                        else
                        {
                            WriteLog(UrlandDumpLocation, "No Item for File Dumpimg  Process");
                          
                        }
                       
                    }
                }
              });
            }
        }

        public void WriteLog(string UrlandDumpLocation, string strLog)
        {
            if (UrlandDumpLocation != "")
            {
               string siteurl = UrlandDumpLocation.Split('|')[0].ToString();
                // Added Code by Ram Vinay Singh on 1 Aug 2016
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSPsite = new SPSite(siteurl))
                    {
                        // WriteLog("oSPsite", "oSPsite For  WriteLog()  Method ");
                        using (SPWeb oSPWeb = oSPsite.OpenWeb())
                        {
                            // WriteLog("oSPWeb", "oSPWeb For  WriteLog()  Method ");
                            oSPWeb.AllowUnsafeUpdates = true;
                            // Fetch the List
                            SPList list = oSPWeb.Lists["ErrorLogList"];
                            //Add a new item in the List
                            // WriteLog("Before Add", "Site Url For  WriteLog()  Method ");
                            SPListItem itemToAdd = list.Items.Add();
                            itemToAdd["Title"] = "ErrorLog _" + System.DateTime.Today.ToString("dd-MM-yyyy");
                            itemToAdd["ErrorDescription"] = strLog;
                            itemToAdd.Update();
                            //WriteLog("After Update", "Site Url For  WriteLog()  Method ");
                            oSPWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
        }
    }
}

    #endregion






Add Event Reciever in Feature


using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace NGOFileDumpProcess.Features.NGOFileDumpProcessTimmerJob
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid("d38cdefb-0535-410c-bcc8-d515748fc7e4")]
    public class NGOFileDumpProcessTimmerJobEventReceiver : SPFeatureReceiver
    {
        const string JobName = "NGO File Dump Process";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                    SPSite site = properties.Feature.Parent as SPSite;
                    CreateJob(parentWebApp);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private bool CreateJob(SPWebApplication site)
        {
            bool jobCreated = false;
            try
            {
                NGOFileDumpTimmerJob job = new NGOFileDumpTimmerJob(JobName, site);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 15;
                job.Schedule = schedule;
                job.Update();
            }
            catch (Exception)
            {
                return jobCreated;
            }
            return jobCreated;
        }
        public bool DeleteExistingJob(string jobName, SPWebApplication site)
        {
            bool jobDeleted = false;
            try
            {
                foreach (SPJobDefinition job in site.JobDefinitions)
                {
                    if (job.Name == jobName)
                    {
                        job.Delete();
                        jobDeleted = true;
                    }
                }
            }
            catch (Exception)
            {
                return jobDeleted;
            }
            return jobDeleted;
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {

            lock (this)
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate ()
                    {
                        SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                        DeleteExistingJob(JobName, parentWebApp);
                    });
                }
                catch (Exception ex)
                {
                    throw ex;
                }
           }
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        //public override void FeatureActivated(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}



Inscription and description Password

$
0
0
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
            string strVal= Decrypt(@"fgfgfgfgm""Pas5pr@se""s@1tValue""MD5", 2,"@1B2c3D4e5F6g7H8", 256);
 
            Console.ReadLine();
 
        }
 
        static public string Decrypt(string cipherText,
                                       string passPhrase,
                                       string saltValue,
                                       string hashAlgorithm,
                                       int passwordIterations,
                                       string initVector,
                                       int keySize)
        {
 
            //' Convert strings defining encryption key characteristics into byte
            //' arrays. Let us assume that strings only contain ASCII codes.
            //' If strings include Unicode characters, use Unicode, UTF7, or UTF8
            //' encoding.
            byte[] initVectorBytes;
            initVectorBytes = Encoding.ASCII.GetBytes(initVector);
 
            byte[] saltValueBytes;
            saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
 
            //' Convert our ciphertext into a byte array.
            byte[] cipherTextBytes;
            cipherTextBytes = Convert.FromBase64String(cipherText);
 
            //' First, we must create a password, from which the key will be
            //' derived. This password will be generated from the specified
            //' passphrase and salt value. The password will be created using
            //' the specified hash algorithm. Password creation can be done in
            //' several iterations.
            PasswordDeriveBytes password;
            password = new PasswordDeriveBytes(passPhrase,
                                               saltValueBytes,
                                               hashAlgorithm,
                                               passwordIterations);
 
            //' Use the password to generate pseudo-random bytes for the encryption
            //' key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes;
            keyBytes = password.GetBytes(keySize / 8);
 
            //' Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey;
            symmetricKey = new RijndaelManaged();
 
            //' It is reasonable to set encryption mode to Cipher Block Chaining
            //' (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;
 
            //' Generate decryptor from the existing key bytes and initialization
            //' vector. Key size will be defined based on the number of the key
            //' bytes.
            ICryptoTransform decryptor;
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
 
            //' Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream;
            memoryStream = new MemoryStream(cipherTextBytes);
 
            //' Define memory stream which will be used to hold encrypted data.
            CryptoStream cryptoStream;
            cryptoStream = new CryptoStream(memoryStream,
                                            decryptor,
                                            CryptoStreamMode.Read);
 
            //' Since at this point we don't know what the size of decrypted data
            //' will be, allocate the buffer long enough to hold ciphertext;
            //' plaintext is never longer than ciphertext.
            byte[] plainTextBytes;
            plainTextBytes = new byte[cipherTextBytes.Length];
 
            //' Start decrypting.
            int decryptedByteCount;
            decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                   0,
                                                   plainTextBytes.Length);
 
            //' Close both streams.
            memoryStream.Close();
            cryptoStream.Close();
 
            //' Convert decrypted data into a string.
            //' Let us assume that the original plaintext string was UTF8-encoded.
            string plainText;
            plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                0,
                                                decryptedByteCount);
 
            //' Return decrypted string.
            return plainText;
        }
 
     
 
    }
}

HTML 5 Video Player Remove Download

$
0
0
<div id="videoframe" style="background: none;border: 1px solid #939598; border-width: 1px 1px; width:175px;">
<video id="cmmivideo" width="173px" height="140px" style="height:140px;"controls="" controlslist="nodownload">

<source src="http://intranet.NGO-infotech.com/NGO/NGOHomePageVideos/NGO.mp4">

</video></div>


Check Current user is an Admin or not

$
0
0

SPUser.IsSiteAdmin Property

SP.User.isSiteAdmin property (sp.js)


if(currUser.get_isSiteAdmin)
{
console.log("Current user is site Admin");
}
else{
console.log("Current user is not site Admin");
}

Renamed Project, WSP name doesn't change

$
0
0


changed project name, still i'm getting wsp name visual studio

Open The Package.Package file and change then Name attribute.
Example
<packagexmlns:dm0="http://schemas.microsoft.com/VisualStudio/2008/DslTools/Core"
dslVersion="1.0.0.0"Id="d3150724-5644-479c-99f3-fc99af5bfdc6"
solutionId="d3150724-5644-479c-99f3-fc99af5bfdc6"resetWebServer="true"
sharePointProductVersion="15.0"
name="NEWNAME"
xmlns="http://schemas.microsoft.com/VisualStudio/2008/SharePointTools/PackageModel">

Image Slider - SharePoint Picture lilbrary using jquery.bxslider.js

$
0
0



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="/sites/eDMS/Style%20Library/ImageCarousel/jquery.bxslider.js"></script><link href="/sites/eDMS/Style%20Library/ImageCarousel/jquery.bxslider.css" rel="stylesheet" runat="server" />
<script type="text/javascript">
    var clientContext;
    var siteCollection;
    var imgLoc
    var appendString = '';
    var totalSiteCount = 0;
    var siteCount = 0;
    var asyncCallbacks = [];
    var siteCollUrl = '';
    var webHost = '';
    var isIE = false;

    $(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
            $("#sliderplaceholder").html('');
            showProperties();
        });
    });

    function showProperties() {
        if (msieversion()) {
            //alert($.browser.version);
            siteCollUrl = _spPageContextInfo.siteAbsoluteUrl + "/";
            webHost = siteCollUrl ;
        }
        else {
            siteCollUrl = _spPageContextInfo.siteAbsoluteUrl;
            webHost = siteCollUrl + "/";
        }

        getWebPartProperties('Local');
    }

    function msieversion(str) {

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

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
        {
            //alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            //return true;
            isIE = true;
            return true;
        }
        else  // If another browser, return 0
        {
            //alert('otherbrowser');
        }

        return str;
    }

    function getWebPartProperties(imageLoc) {

        switch (imageLoc) {

            case 'Local':
                clientContext = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
                this.oSite = clientContext.get_site();
                this.oWebsite = this.oSite.get_rootWeb();
                this.list = this.oWebsite.get_lists().getByTitle("AAGBanners");
                var query = "<View><Query><Where><Eq><FieldRef Name='Region' /><Value Type='Choice'>CoastalMarine</Value></Eq></Where></Query><ViewFields><FieldRef Name='BannerLinkURL' /><FieldRef Name='FileRef' /><FieldRef Name='Title' /></ViewFields></View>";
                var camlQuery = new SP.CamlQuery();
                camlQuery.set_viewXml(query);
                this.productcollection = this.list.getItems(camlQuery);

                clientContext.load(this.productcollection, 'Include(BannerLinkURL, Title, FileRef)');
                clientContext.executeQueryAsync(Function.createDelegate(this, function () {
                    var appendString = "<ul class='bxslider'>";
                    console.log('hi');
                    var ListEnumerator = this.productcollection.getEnumerator();

                    while (ListEnumerator.moveNext()) {
                        var currentItem = ListEnumerator.get_current();

                        if (currentItem.get_item('FileRef') != null) {
                            console.log(currentItem.get_item('FileRef'));
                            //alert(currentItem.get_item('ImageURL'));
                            var url = $("<a href='" + currentItem.get_item('FileRef') + "'>").prop("pathname");
                            if (isIE)
                                url = url.substr(1, url.length);
                            appendString += "<li style='position: absolute; top: 0px; z-index: 5; display: block;'><a href='" + currentItem.get_item('BannerLinkURL') + "'><img  src='" + url + "' title='" + currentItem.get_item('Title') + "' width='100%' height='284px' /></a></li>";
                        }
                    }
                    console.log(appendString);
                    appendString += "</ul>"
                    $("#sliderplaceholder").append(appendString);
                    invokeSlider();
                    //alert("Success");
                }), Function.createDelegate(this, function (sender, args) {
                    console.log(args.get_message());
                }));
                break;
        }
    }

    function invokeSlider() {
        /*$('.bxslider').bxSlider({
          captions: true
        });*/
        $('.bxslider').bxSlider({
            mode: 'fade',
            infiniteLoop: true,
            slideWidth: 600,
            auto: true,
            autoStart: true,
            autoDirection: 'next',
            adaptiveHeight: false,
            autoHover: true,
            pause: 3000,
            autoControls: false,
            pager: true,
            pagerType: 'full',
            controls: true,
            captions: true,
            speed: 500
        });
    }
</script>
<div id="sliderplaceholder"></div>

Custom Document Preview on Click of Document Link in GRID ( Data Table)

$
0
0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jquery-3.1.1.js"></script>
    <script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jeditable.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css" />
    <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script>

    <script type="text/javascript" src="https://gkms.sharepoint.com/sites/Khaitan/SiteAssets/jquery.SPServices-2014.02.js"></script>

    <script type="text/javascript" charset="utf-8">
         $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
            ExecuteOrDelayUntilScriptLoaded(CallOut, "callout.js");
            var aHtml="";
            var rowID;        
            var siteUrl = "https://gkms.sharepoint.com/sites/Khaitan/";
            var restUrl="";
         
            function retrieveListItems() {
             // This piece of code retrieves list items from the list called "Resources"
                // you can change the name of the list in the variable 'listName'
                // Also, the fields revieved are 'ows_Title' and 'ows_Cost', you can change those too
                $().SPServices({
                    operation: "GetListItems",
                    async: false,
                    listName: "KhaitanDocLib",
                    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='EncodedAbsUrl'/></ViewFields>",
                    completefunc: function (xData, Status) {
                        //alert(xData.responseText);
                        $(xData.responseXML).SPFilterNode("z:row").each(function () {
                            var aHtml = "<a href=" + $(this).attr("ows_EncodedAbsUrl") + ">" + $(this).attr("ows_Title") + "</a>";
                            var tdHtml = "<tr class='gradeX' id='" + $(this).attr("ows_ID") + "'> <td class='DocLinkID'>" + aHtml + "</td>";
                            tdHtml += "<td class='two'>" + $(this).attr("ows_PracticeArea") + "</td>";
                            $(".tablebodyresources").append(tdHtml);
                        });
                    }
                });

                // the table is constructed dynamically where results are going to be placed
                var nCloneTh = document.createElement('th');
                var nCloneTd = document.createElement('td');
                nCloneTd.innerHTML = '<img class="editRowIMG" src="https://gkms.sharepoint.com/sites/Khaitan/Style Library/details_open.png" height="25" width="25" alt="EDIT"><img class="delItemImg" src="https://gkms.sharepoint.com/sites/Khaitan/Style Library/Delete.png" height="25" width="25" alt="Delete">';
                nCloneTh.innerHTML = 'Actions';
                nCloneTd.className = "center";
                // this is an 'Add' image  inserted in front of each row
                $('#resourcepool thead tr').each(function () {
                    //this.insertBefore( nCloneTh, .childNodes[0]);
                    $(this).append(nCloneTh);
                });

                $('#resourcepool tbody tr.gradeX').append(nCloneTd);
                var resourceTable = $('#resourcepool').dataTable();
                //this is an event handler to handle users clicking on the 'Add' image in front of each row
             
                $('#resourcepool').on( 'click', 'tbody tr .DocLinkID', function () {
                    rowID=this.parentElement.id;
     //alert(rowID);    
     restUrl = "https://gkms.sharepoint.com/sites/Khaitan/_api/web/lists/getbytitle('KhaitanDocLib')/items("+rowID+")";
     $.ajax({
                    url: restUrl,
                    method: "GET",                
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: function (data) {
                    
var metaDataCols ="";
                    
$("#metadatav").html(metaDataCols);
                     
alert("success");
                        $("#frame").attr("src", data.d.ServerRedirectedEmbedUrl);
                        metaDataCols="<table><tr><td>Practice Area:</td><td>"+data.d.PracticeArea+"</td><td>Sub Practice Area:</td><td>"+data.d.SubPracticeArea+"</td></tr>";
                        metaDataCols +="<tr><td>Comments</td><td>"+data.d.Comments+"</td></tr><table>";
                        $("#metadatav").append(metaDataCols);
                        $("#openDocID").attr("href", data.d.ServerRedirectedEmbedUrl);
                        GetDocNameLinkURL();
                                         
                    },
                    error: function (data) {
                        alert("error");
                    }  
                });//onclick of row             
   
    
   });
             
            }//retrieve item method
       
   function GetDocNameLinkURL(){
    restUrl="https://gkms.sharepoint.com/sites/Khaitan/_api/web/lists/getbytitle('KhaitanDocLib')/items("+rowID+")/File";
       $.ajax({
       url: restUrl,
                    method: "GET",                
                    headers: { "Accept": "application/json; odata=verbose" },
           success: function(results){
     //alert(results);
     var docURL = results.d.LinkingUrl.split('?');
          $("#downloadDocID").attr("href",docURL[0]);
          var arr = results.d.Name.split('.');
          $("#DocNameID").text(arr[0]);

           }
       });
   }
       function myFunction(){
          alert("Document downloaded");
        }// download completes
    
 
        });//DOCUMENT.READY    
     
   
 
 
     </script>

    <style type="text/css">
 
        .edit-row-modal {
            display: none;
        }
     
     
    </style>

</head>
<body id="dt_example">
    <table cellpadding="0" cellspacing="0" border="0" class="display" id="resourcepool">
        <thead>
            <tr>
                <th>Name Of Document</th>
                <th>Practice Area</th>
            </tr>
        </thead>
        <tbody class="tablebodyresources"></tbody>
    </table>

 
  <div id="mydiv" width="100%" height="100%">
 
  <h1 id="DocNameID"></h1>
    <iframe Id="frame" height="440px"></iframe>
 
  <div id="metadatav"></div>  
   <a id="openDocID"><input type="button" value="Open"></a>
   <a id="downloadDocID" onclick="myFunction()"><input type="button" value="Download"></a>
  </div>
 
</body>
</html>


SharePoint 2013: Showing Page Views within a SharePoint Page

$
0
0


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
    var clientContext;
    var siteCollection;
    var hitCount='';
    var siteCollUrl = '';
    var webHost = '';
    var isIE = false;
    var siteUrl = '';
    var date = '';
    var uname = '';
    var hitCountplaceholder = '#hitCountplaceholder';
    var listName = 'Statistics';
 
    $(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
            $(hitCountplaceholder).html('Count: ');
            SetPageVisitCount();
        });
    });

    function showProperties() {
        if (msieversion()) {
            alert($.browser.version);
            siteCollUrl = _spPageContextInfo.siteAbsoluteUrl + "/";
            webHost = siteCollUrl;
        }
        else {
            siteCollUrl = _spPageContextInfo.siteAbsoluteUrl;
            webHost = siteCollUrl + "/";
            alert(siteCollUrl);
        }

        SetPageVisitCount();
    }
    function SetPageVisitCount() {
        siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        date = new Date();
        console.log(date);
        clientContext = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
        uname = clientContext.get_web().get_currentUser();
        clientContext.load(uname);
        var oList = clientContext.get_web().get_lists().getByTitle(listName);
        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);
        oListItem.set_item('Title', 'No Title');
        oListItem.set_item('url', siteUrl);
        oListItem.set_item('date', date);
        oListItem.set_item('uname', uname);
        oListItem.update();
        clientContext.load(oListItem);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }

    function onQuerySucceeded() {
        // alert('Item created: ' + oListItem.get_id());
        hitCount = oListItem.get_id();
        $(hitCountplaceholder).append(hitCount);
    }

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

    function GetPageVisitCount() {
        appendString = '';
        $(hitCountplaceholder).append(appendString);
    }
</script>
<div id="hitCountplaceholder"></div>


MORE REFERENCES

http://spdeveloper.co.in/sharepoint2013/page-views-hit-counter-on-a-sharepoint-page.aspx


Create WCF Service in C# using SQL server


To Get File And Folder From Document Library Using JSOM From To Way

$
0
0


1- Without Caml Querry
2- With Caml Query


var LibraryNameForUpdate='NGODocument';
1-  Without Caml Querry

function FileWithContentTypeNotUsedCAMLQuery(folderName, selectedLink)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(LibraryNameForUpdate);
var query = SP.CamlQuery.createAllItemsQuery();
query.set_folderServerRelativeUrl(folderName);
allItems = list.getItems(query);
context.load(allItems, 'Include(Title,ContentType,File,Author,Editor,Modified)'); // If You want Specific column is Loaded Then write This
//context.load(allItems, 'Include(ID,Title,Description0,File,Author,Editor,Modified,_ModerationStatus,Created)');
//context.load(allItems);  If You want All  column is Loaded Then write This

context.executeQueryAsync(Function.createDelegate(this, this.successGetViewAllFileApprovedReject),   Function.createDelegate(this, this.failedsuccessGetViewAllFileApprovedReject));

}

function successGetViewAllFileApprovedReject()
{

  var fileUrls = "";
  var ListEnumerator = this.allItems.getEnumerator();
   var count = 0;
   while(ListEnumerator.moveNext())
   {
    var currentItem = ListEnumerator.get_current();
    var _contentType = currentItem.get_contentType();
   
     if(_contentType.get_name() != "Folder")
       {
         debugger;
      // count = count + 1;
        var File = currentItem.get_file();
        var fieldUserValueCreatedBy = currentItem.get_item("Author");
        var fieldUserValueModifiedBy = currentItem.get_item("Editor");
        var currentdate = new Date();
        var modifiednumberofDaysago = showDays(currentdate.toISOString(), currentItem.get_item('Modified'));
        if(File != null)
          {
         debugger;
          fileUrls += File.get_serverRelativeUrl() + '\n';
         
          }
       }
   }
//alert(fileUrls);
  //alert(count);
}
function failedsuccessGetViewAllFileApprovedReject(sender, args) {
  alert("failed. Message:" + args.get_message());
}



1-  With Caml Querry (It best Way To Use )


function FileWithCAMLQuery(folderName, selectedLink)
{
   debugger;
    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 Scope=\'Recursive\'><Where><Eq><FieldRef Name=\'FSObjType\'/><Value Type=\'Number\'>0</Value></Eq></Where></View>';
                query.set_viewXml(q);
                allItems = list.getItems(query);
                //this.listInfoArray=context.load(allItems);If You want All  column is Loaded Then write This
                context.load(allItems, 'Include(ID,Title,Description0,File,Author,Editor,Modified,_ModerationStatus,Created)'); // If You want Specific column is Loaded Then write This

                context.executeQueryAsync(Function.createDelegate(this, this.successFileWithCAMLQuery), Function.createDelegate(this, this.failedsuccessFileWithCAMLQuery));

}

function successFileWithCAMLQuery()
{
debugger;
  var fileUrls = "";
  var ListEnumerator = this.allItems.getEnumerator();
   var count = 0;
   while(ListEnumerator.moveNext())
   {
       var currentItem = ListEnumerator.get_current();
      //  debugger;
         count = count + 1;
         var File = currentItem.get_file();
         var fieldUserValueCreatedBy = currentItem.get_item("Author");
         var fieldUserValueModifiedBy = currentItem.get_item("Editor");
         var currentdate = new Date();
         var modifiednumberofDaysago = showDays(currentdate.toISOString(), currentItem.get_item('Modified'));
         var dateCreated = new Date(currentItem.get_item('Created'));
         console.log(dateCreated.getDate() + "-" + monthNames[dateCreated.getMonth()] + "-" + dateCreated.getFullYear());
         console.log(fieldUserValueCreatedBy.get_lookupValue());
         console.log(fieldUserValueModifiedBy .get_lookupValue());
         console.log(currentItem.get_item('Title'));
         console.log(currentItem.get_item('Description0'));
         console.log(currentItem.get_item('ID'));
         console.log(currentItem.get_item('_ModerationStatus'));
      
   }
    //alert(modifiednumberofDaysago);
     alert(count);
}
function failedsuccessFileWithCAMLQuery(sender, args) {
  alert("failed. Message:" + args.get_message());
}


****************************All Field Get By this Internal Name*********************************
LIST OF INTERNAL NAMES FOR SHAREPOINT FIELDS

In order to reference a column or field using the the SharePoint object model, you often need to know its internal name. For example, when creating a CAML query, you can specify the field on which to search by providing its internal name. As opposed to the display name, which can be changed in the UI, the internal name is immutable. While the default display name and the internal name are often identical or similar, they can also be very different. The difference isn’t always consistent. For example, spaces in the display name can be removed, such as IsCheckedoutToLocal, or replaced with the hexadecimal equivalent, such as HTML_x0020_File_x0020_Type. Furthermore, the display name can be the same for more than one fields, so the internal name is the only way to distinguish between them.
You can quickly determine the internal name of a field using the UI:
1.      Open the List Settings page
2.      Under the Columns section, select a column to view the Edit Column page
3.      The URL of this page includes the internal name in the query string. For example, the URL for the Created By field includes the following query string List=%7BF641CEF1%2DCDE2%2D49E1%2D9800%2D861A408EF890%7D&Field=Author. The value for the Field parameter, Author, is the internal name for Created By.
However, this approach isn’t always convenient. If the column you want doesn’t already belong to the list, you’d have to first add it.
For reference purpose, below is the list of the display name and corresponding internal name for the default fields of a Document Library.
TITLE
INTERNAL NAME
Approval Status
_ModerationStatus
Approver Comments
_ModerationComments
Check In Comment
_CheckinComment
Checked Out To
CheckoutUser
Checked Out To
CheckedOutTitle
Checked Out To
LinkCheckedOutTitle
Content Type
ContentType
Content Type ID
ContentTypeId
Copy Source
_CopySource
Created
Created
Created
Created_x0020_Date
Created By
Author
Document Created By
Created_x0020_By
Document Modified By
Modified_x0020_By
Edit
Edit
Edit Menu Table End
_EditMenuTableEnd
Edit Menu Table Start
_EditMenuTableStart
Effective Permissions Mask
PermMask
Encoded Absolute URL
EncodedAbsUrl
File Size
File_x0020_Size
File Size
FileSizeDisplay
File Type
File_x0020_Type
GUID
GUID
Has Copy Destinations
_HasCopyDestinations
Html File Link
xd_ProgID
HTML File Type
HTML_x0020_File_x0020_Type
ID
ID
ID of the User who has the item Checked Out
CheckedOutUserId
Instance ID
InstanceID
Is Checked out to local
IsCheckedoutToLocal
Is Current Version
_IsCurrentVersion
Is Signed
xd_Signature
Item Type
FSObjType
Level
_Level
Merge
Combine
Modified
Modified
Modified
Last_x0020_Modified
Modified By
Editor
Name
FileLeafRef
Name
LinkFilenameNoMenu
Name
LinkFilename
Name
BaseName
Order
Order
owshiddenversion
owshiddenversion
Path
FileDirRef
ProgId
ProgId
Property Bag
MetaInfo
Relink
RepairDocument
ScopeId
ScopeId
Select
SelectTitle
Select
SelectFilename
Server Relative URL
ServerUrl
Shared File Index
_SharedFileIndex
Source Name (Converted Document)
ParentLeafName
Source Url
_SourceUrl
Source Version (Converted Document)
ParentVersionString
Template Link
TemplateUrl
Title
Title
Type
DocIcon
UI Version
_UIVersion
Unique Id
UniqueId
URL Path
FileRef
Version
_UIVersionString
Virus Status
VirusStatus
Workflow Instance ID
WorkflowInstanceID
Workflow Version
WorkflowVersion
In my case, I’m interested in the Name field. I wouldn’t have guessed that it would be mapped to FileLeafRef.

USEFUL REFERENCE FOR SHAREPOINT INTERNAL FIELDS NAME
There are few common and important sharepoint internal fields name which will help to access data in your Web application.
Document Library Fields:
Display Name             Internal Name
Name                                  FileLeafRef
Name                                  LinkFilenameNoMenu
Name                                  LinkFilename
Name                                  BaseName
URL Path                          FileRef
Path                                    FileDirRef
File Size                             File_x0020_Size
File Type                           File_x0020_Type
Source Url                       _SourceUrl
Type                                  DocIcon
Custom List Fields:
Display Name                Internal Name
Name                                     FileLeafRef
Title                                        Title
Order                                     Order
HTML File Type                 HTML_x0020_File_x0020_Type
URL Path                              FileRef
Created                                 Created_x0020_Date
File Size                                 File_x0020_Size
File Type                               File_x0020_Type
File Name                              BaseName
Created By                            Author
Modified By                          Editor

References:
1-http://blog.softartisans.com/2009/12/08/list-of-internal-names-for-sharepoint-fields/
2-https://dipansaha.wordpress.com/2012/07/23/useful-reference-for-sharepoint-internal-fields-name/


Working with CAML Query using Server OM, CSOM .NET, CSOM REST (JSON/ATOM), WEB Services, Powershell

$
0
0

CAML:-

---------
   <Where>
      <IsNotNull>
         <FieldRef Name='ID' />
      </IsNotNull>
   </Where>
   <ViewFields>
      <FieldRef Name='Title' />
   </ViewFields>

Server OM:-
---------------
try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                using (SPWeb spWeb = site.OpenWeb())
                {
                    SPList spList = spWeb.Lists.TryGetList("Site Pages");
                    if (spList != null)
                    {
                        SPQuery qry = new SPQuery();
                        qry.Query = "<Where><IsNotNull><FieldRef Name=\"ID\" /></IsNotNull>
                       </Where>";
                        qry.ViewFields = "<FieldRef Name=\"Name\" />";
                        SPListItemCollection listItems = spList.GetItems(qry);
                        foreach (SPListItem listItem in listItems)
                        {
                            if (listItem != null & listItem["Name"] != null)
                            {
                                lblTitle.Text += listItem["Name"].ToString() + ", ";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
            finally
            { }

Client Side Object Model .NET (CSOM .NET):-
------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using spClient = Microsoft.SharePoint.Client;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                
spClient.ClientContext clientContext = new spClient.ClientContext("http://<server_name>:6677/");
Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Pages");
                
                clientContext.Load(spList);
                clientContext.ExecuteQuery();

                if (spList != null && spList.ItemCount > 0)
                {
spClient.CamlQuery camlQuery = new spClient.CamlQuery();
camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where>
</Query><ViewFields><FieldRef Name='ID' /></ViewFields></View>";

                    spClient.ListItemCollection listItems = spList.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();
                    foreach (spClient.ListItem listItem in listItems)
                    {
                        if (listItem != null && listItem["ID"] != null)
                        {
                            lblTitle.Text += listItem["ID"].ToString() + ", ";
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
            finally
            { }
        }
    }
}


Client Side Object Model ECMA Script:-

----------------------------------------------------------
1. Create a test ASPX page in the Pages library.
2. Add the Content Editor web part and add the following script in it.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
       <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js">
</script>
    <script type="text/javascript" src="/_layouts/15/init.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            createList();
        });
    </script>
    <script type="text/ecmascript">
        function createList() {
            var clientContext = new SP.ClientContext.get_current();
            var oWebsite = clientContext.get_web();
            var listCreationInfo = new SP.ListCreationInformation();
            listCreationInfo.set_title('CustomList2'); // list name
            listCreationInfo.set_description('description'); // list description
            listCreationInfo.set_templateType(SP.ListTemplateType.genericList); //list type
            oWebsite.get_lists().add(listCreationInfo);
            clientContext.executeQueryAsync(
                Function.createDelegate(thisthis.onQuerySucceeded),// when success
                Function.createDelegate(thisthis.onQueryFailed) // when failed
                );
        }
        function onQuerySucceeded() {
            alert("List Created");
        }
        function onQueryFailed(sender, args) {
            alert("List Failed");
        }
    </script>
</asp:Content>

 -----------------------------------------------------------------------------------------------------
Client Side Object Model ECMA Script:-
--------------------------------------------------
1. Create a test ASPX page in the Pages library.
2. Add the Content Editor web part and add the following script in it.
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>    
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/init.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript">
if(typeof jQuery=="undefined"){
var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/";
document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
</script>
    <script type="text/javascript">
        $(document).ready(function () {             
retrieveListItems();
        });
    </script>
    <script type="text/ecmascript">
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<ViewFields><FieldRef Name=\'ID\' /><FieldRef Name=\'Title\' /></ViewFields>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
 Function.createDelegate(this, this.onQueryFailed));        
}
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() + 
'\nTitle: ' + oListItem.get_item('Title');
    }
    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Client Side Object Model Rest (CSOM REST) using JSON:-
--------------------------------------------------------------------------------------
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead"
 runat="server">
    <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            CSOMRestJson();
        });
        function CSOMRestJson() {
            $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('CustomField')/Items?$select=Title",
                type: "GET",
                headers: { "accept""application/json;odata=verbose" },
                success: function (data) {
                    if (data.d.results) {
                        var results = data.d.results;
                        var html = "<table>";
                        for (var i = 0; i < results.length; i++) {
                            html += "<tr><td>";
                            html += results[i].Title;
                            html += "</td><td>";
                            html += "</td><tr>";
                        }
                        html += "</table>";
                        alert(html);
                        $("lblText").text(html);
                        $('#<%= lblText.ClientID %>').text(html);
                    }
                },
                error: function (xhr) {
                    alert(xhr.status + ': ' + xhr.statusText);
                }
            });
            function onDataReturned(data) {
                // TODO: handle the data
            }
            function onError(err) {
                // TODO: handle the error
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="lblText" runat="server"></asp:Label>
</asp:Content>

Client Side Object Model Rest (CSOM REST) using ATOM:- (but it is not working)
---------------------------------------------------------------------------------------------------------------------------------
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            CSOMRestJson();
        });
        function CSOMRestJson() {
            $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('CustomField')/Items?$select=Title",
                type: "GET",
                contentType: "application/atom+xml;type=entry",
                headers: { "accept""application/atom+xml" },

                success: function (data) {
                    if (data.d.results) {
                        var results = data.d.results;
                        var html = "<table>";
                        for (var i = 0; i < results.length; i++) {
                            html += "<tr><td>";
                            html += results[i].Title;
                            html += "</td><td>";
                            html += "</td><tr>";
                        }
                        html += "</table>";
                        alert(html);
                        $("lblText").text(html);
                        $('#<%= lblText.ClientID %>').text(html);
                    }
                },
                error: function (xhr) {
                    alert(xhr.status + ': ' + xhr.statusText);
                }
            });
            function onDataReturned(data) {
                // TODO: handle the data
            }
            function onError(err) {
                // TODO: handle the error
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label ID="lblText" runat="server"></asp:Label>
</asp:Content>

WEB Services:-
----------------------
Web_Reference.Lists listsWS = new Web_Reference.Lists();
            listsWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
            listsWS.Url = "http://<server_name>:6677/_vti_bin/Lists.asmx";

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            XmlNode queryNode = doc.CreateElement("Query");
            queryNode.InnerXml = "<Where><IsNotNull><FieldRef Name=\"ID\" /></IsNotNull></Where>";

            XmlNode viewfieldsNode = doc.CreateElement("ViewFields");
            viewfieldsNode.InnerXml = "<FieldRef Name=\"Title\" /><FieldRef Name=\"ID\" />";

            XmlNode queryOptionsNode = doc.CreateElement("QueryOptions");
            queryOptionsNode.InnerXml = "";

            string rowLimit = "150";

System.Xml.XmlNode items = listsWS.GetListItems("CustomField"null, queryNode, viewfieldsNode, rowLimit, queryOptionsNode, null);
            foreach (System.Xml.XmlNode listItem in items)
            {
                lblTitle.Text += listItem.OuterXml + ", ";
            }
Powershell:-
---------------
$spweb = Get-SPWeb http://<server_name>:6677/
$splist = $spweb.Lists.TryGetList("Site Pages")
if($splist -ne $null)
{
   $query = New-Object Microsoft.SharePoint.SPQuery;$query.Query =
"<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>";$query.ViewFields = "<FieldRef Name='Title' />";
$query.ViewFieldsOnly = $true;$items = $splist.GetItems($query);
}















Source: CAML Designer 2013.

Create Dynamic row on clock on button and save Record in Table

$
0
0


<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
                <!--<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" /> -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
   <!-- <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>--> 

                <script type="text/javascript">
                $(document).ready(function () { 
                 $(document).on("click", ".classAdd", function ()
                 {
      
           var rowCount = $('.data-contact-person').length + 1;
           var contactdiv = '<tr class="data-contact-person">' + 
               '<td><input type="text" name="f-name' +rowCount  + '" class="form-control f-name01"/></td>' +'<td><input type="text" name="l-name' + rowCount + '" class="form-control l-name01" /></td>' + 
               '<td><input type="text" name="email' + rowCount + '" class="form-control email01" /></td>' +'<td><select id="checkboxValues01"  name="checkboxValues' + rowCount + '" class="form-control checkboxValues01"><option class="form-control optionA"  value="B-Tech">B-Tech</option><option class="form-control optionB" value="MCA">MCA<option></select></td>'+
               '<td><input type="radio" name="radioValue01" value="Male" class="radioValue'+rowCount +'"/>Male<input type="radio" name="radioValue01" value="Female" class="radioValue'+rowCount+'"/>Female</td>' +
                '<td><button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>' + 
                '<button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' + 
                '</tr>'; 
            $('#maintable').append(contactdiv); // Adding these controls to Main table class 
        }); 
    });
    $(document).on("click", ".deleteContact", function () { 
            $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls  
}); 

    var siteUrl = 'http://NGO/sites/NGO/';
    function createListItem()
    {

        // alert('in function ');
         var clientContext = new SP.ClientContext(siteUrl);
         $('tr.data-contact-person').each(function ()
         {   
           var firstName = $(this).find('.f-name01').val();//Bind to the first name with class f-name01 
           var lastName = $(this).find('.l-name01').val();//Bind to the last name with class l-name01 
           var emailId = $(this).find('.email01').val();//Bind to the emailId with class email01
           var coursesval = $(this).find('select.checkboxValues01').val();
         //  alert(coursesval);
          // var radioVal = $(this).find('.radioValue01').val();
           // var radioVal=$('input[name=radioValue01]:checked').val();
           var radioVal = $('input:radio[name=radioValue01]:checked').val();
           alert(radioVal);
           var itemCreateInfo = new SP.ListItemCreationInformation();
           var oList = clientContext.get_web().get_lists().getByTitle('DynamicCustomList');
           var oListItem = oList.addItem(itemCreateInfo);
          oListItem.set_item('FName',firstName);
          oListItem.set_item('LName',lastName);
          oListItem.set_item('Email',emailId);
          oListItem.set_item('Courses',coursesval);
          oListItem.set_item('Sex',radioVal);
          oListItem.update();
          clientContext.load(oListItem);
          });
       
       
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        e.preventDefault();
    }

    function onQuerySucceeded()
      {
      alert('Item Created Succesfully');
       }

    function onQueryFailed(sender, args)
     {

        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     }
                </script>             
                                 
   <title>Demo</title> 
  
  
<head>
<meta name="WebPartPageExpansion" content="full" />
</head>
<body> 
   <head>
</head>
<form id="form1"> 
       <div class="container">              <h2>Basic Table</h2> 
           <table class="table" id="maintable"> 
                <thead> 
                   <tr> 
                     <th>First Name</th>          
                     <th>Last Name</th>                         
                     <th>Email</th>
                     <th>Courses</th>
                      <th>Sex</th>                
                      </tr> 
                </thead> 
                <tbody> 
                   <tr class="data-contact-person"> 
                      <td> 
                           <input type="text" name="f-name" class="form-control f-name01" /></td> 
                      <td> 
                          <input type="text" name="l-name" class="form-control l-name01" /></td> 
                      <td> 
                           <input type="text" name="email" class="form-control email01" /></td>
                             <td><select id="checkboxValues" name="checkboxValues" class="form-control checkboxValues01"><option class="form-control optionA01" value="B-Tech">
                                                                                                                                B-Tech</option><option class="form-control optionB01" value="MCA">
                                                                                                                                MCA</option></select></td>
                               <td><input type="radio" name="radioValue01" value="Male" class="radioValue" id="radioButon1" checked="true"/>Male<input type="radio" name="radioValue01" value="Female" class="radioValue" id="radioButon2"/>Female</td>
                          <td> <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">
                                                                                                                Add More</button> 
                      </td> 
                    
                  </tr> 
                             </tbody> 
        </table> 
           <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-right btn-sm" onclick="createListItem();">
                                                Submit</button> 
       </div> 
    </form> 
</body> 

</asp:Content>









Few tips to improve SharePoint site Performance

$
0
0
According to my practical experience, here are some tips to improve SharePoint site performance.
Note: covered only the area where we don’t need to write any code, there are also some more tips over the internet if you need to improve the site using C# code where one should follow the Best SharePoint development practices.
1) Web.Config changes
web.config file Path on Web server C:\inetpub\wwwroot\wss\VirtualDirectories
– stop debuging <compilation debug=”false”>
– enable blob cache <BlobCache enabled=”true”
– Custom errors mode ON <customErrors mode=”On” />
2) Implement caching, i use the HTML 5 local storage for our client. i have also add some code to refresh the cache after two Hours
– Store result set in the object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var storageKey = "EmployeesDataSaved"
localStorage.removeItem(storageKey);
var object = { StoredData: "YourResultSet", timestamp: new Date() }
localStorage.setItem(storageKey, JSON.stringify(object));
//To Get the data
var localStorageObj = JSON.parse(localStorage.getItem(storageKey));
        if (GetDateDiffInHours(localStorageObj) >= 2) {
            //codeto get data from the database to refresh cache
        }
         else
            localStorageObj.StoredData; //loading the data from cache
 
function GetDateDiffInHours(localStorageObj) {
    var savedDate = parseInt(new Date(localStorageObj.timestamp).getTime() / 1000);
    var currentDate = new Date().getTime() / 1000;
    var hoursDiff = (currentDate - savedDate) / 3600;
    return hoursDiff;
}
3) Managing Styles and Scripts
– remove all inline styles and scripts, put them in a separate file
– Minify all JS and CSS files
4) Reduce HTTP Number of requests
– Use CSS Sprite images for icons and small images
– use SVG for images as it will go to the server only once to load the one image and for the rest, we are just using the Hash # sign to get relevant image e.g /images/icons.svg#email, /images/icons.svg#phone etc
– Try to combine all CSS files into one file as much as possible
– Try to combine/merge all js files into one file
5) Optimize / compress Images
– Optimize all images that are being used in the site using online websites like tiny png
– reduce image size
– use the Progressive images intead of standard JPEG, for refernece click here

Test Your Site using the following sites

Batch Execution Jsom (Get record of multiple list in Single Query execution)

$
0
0
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
                <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="batchJSOM" 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_2122924d_336f_4255_84f3_f0b1a2263a0b" AllowClose="False" ChromeType="None" ExportMode="All" __MarkupType="vsattributemarkup" __WebPartId="{2122924D-336F-4255-84F3-F0B1A2263A0B}" 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>
                                <script type="text/javascript">
var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();


var list = web.get_lists().getByTitle("LyteBox Photos");
var camlQuery = new SP.CamlQuery();
var q = '<View/>';
camlQuery.set_viewXml(q);
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, 'Include(DisplayName,Id)');


var list = web.get_lists().getByTitle("Awards");
var camlQuery = new SP.CamlQuery();
var q = '<View/>';
camlQuery.set_viewXml(q);
this.listItems1 = list.getItems(camlQuery);
clientContext.load(listItems1, 'Include(DisplayName,Id)');


var list = web.get_lists().getByTitle("LyteBox Photos");
var camlQuery = new SP.CamlQuery();
var q = '<View/>';
camlQuery.set_viewXml(q);
this.listItems2 = list.getItems(camlQuery);
clientContext.load(listItems2, 'Include(DisplayName,Id)');


var list = web.get_lists().getByTitle("LyteBox Photos");
var camlQuery = new SP.CamlQuery();
var q = '<View/>';
camlQuery.set_viewXml(q);
this.listItems3 = list.getItems(camlQuery);
clientContext.load(listItems3, 'Include(DisplayName,Id)');


clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onListItemsLoadSuccess(sender, args) {
                var listEnumerator = this.listItems.getEnumerator();
                var listEnumerator1 = this.listItems1.getEnumerator();
                var listEnumerator2 = this.listItems2.getEnumerator();
                var listEnumerator3 = this.listItems3.getEnumerator();

                //iterate though all of the items
                var increment=1;
                while (listEnumerator.moveNext()) {
                    var item = listEnumerator.get_current();               
                    var title = item.get_displayName();
                    var id = item.get_id();
                    Temp(id);
                    console.log("imcrement"+increment+ "List title : " + title + "; List ID : "+ id);
                    increment = increment +1;
                  
            //alert("List title : " + title + "; List ID : "+ id);
        }
       
        function Temp(tempID)
        {
                console.log(tempID);
                //alert(tempID);
        }
       
        var increment1=1;
                                while (listEnumerator1.moveNext()) {
                    var item1 = listEnumerator1.get_current();               
                    var title1 = item1.get_displayName();
                    var id1 = item1.get_id();
                    console.log("imcrement"+increment1+ "List title : " + title1 + "; List ID : "+ id1);
                    increment1 = increment1 +1;
            //alert("List title : " + title + "; List ID : "+ id);
        }
       
        var increment2=1;
                                while (listEnumerator2.moveNext()) {
                    var item2 = listEnumerator2.get_current();               
                    var title2 = item2.get_displayName();
                    var id2 = item2.get_id();
                    console.log("imcrement"+increment2+ "List title : " + title2 + "; List ID : "+ id1);
                    increment2 = increment2 +1;
            //alert("List title : " + title + "; List ID : "+ id);
        }
       
        var increment3=1;
                                while (listEnumerator3.moveNext()) {
                                               
                    var item3 = listEnumerator3.get_current();
                    var title3 = item3.get_displayName();
                    var id3 = item3.get_id();
                    console.log("imcrement"+increment3+ "List title : " + title3 + "; List ID : "+ id3);
                    increment3 = increment3 +1;
            //alert("List title : " + title + "; List ID : "+ id);
        }
       
       

}
               
function onQueryFailed(sender, args) {
                alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}</script>​
</asp:Content>
Viewing all 542 articles
Browse latest View live