Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Monday, September 19, 2016

Validating SharePoint list data by using PreSaveAction involving JSOM Asynchronous call

In the previous post I had shared validating SharePoint list data that invlolved JSOM asynchronous call by overriding the PreSaveAction . The same requirement can also be accomplished without over riding the presaveaction.

Approach would be when the call is succeded or failed I am creating delegate on executeQueryAsync call with call back. On success we will posting the data manually to SharePoint list or on failure I willnt post any data to SharePoint list by returning false.



Output


Friday, September 16, 2016

Validating SharePoint list data by overriding PreSaveAction involving JSOM Asynchronous call

SharePoint supports ExecuteQueryAsync and when we call ExecuteQueryAsync it executes the object model code declared and carries on and returns the ouput at some point in future without waiting for subsequent code. Most of the time we would expect our code to act on result of call.

This is challenging particular when we use it with presaveaction that would expect true or false and ExecuteQueryAsync returns output infuture. PreSaveAction in SharePoint does validation before submitting an item to SharePoint list.

Solution: By using jquery I had added custom OnClick fumction to the existing Save button. The custom function does the validation and once it is completed I had called orginial Save function to complete the saving process.

In below code I am using JSOM ExecuteQueryAsync to fetch status of SharePoint list item field. Based on status of field and I am comparing it other field as part of business validation. During the validation I decide whether to save the item or not. If the item is valid I am calling orginal save function or else just an alert will be displayed to user that there is problem with request. I had used this code in editform.aspx.




Output


Monday, June 20, 2016

LINQ to SharePoint - SPMetal

In SharePoint, We can query list data using LINQ or CAML. Below example I had created windows application that uses CAML to SharePoint for quering SharePoint list data.  I had created empty SharePoint project with farm solution with button and Datagrid to display the data.

[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private string siteUrl = "http://stapvsp9007.gcm.com/sites/testsite";
        private void LINQSP_Click(object sender, EventArgs e)
        {          
            var ctx = new SPTestList.SPTestListDataContext(siteUrl);
            var query = from p in ctx.Testcalendar
                        where p.Title == "Test567$"
                        select p;
            dataGridView1.DataSource = query.ToList();           
        }
    }
}
[/code]
Using SPMetal.exe I had created LINQ to SharePoint Model class file and then queried the data



Project Structure


Result:

JavaScript in Application Pages - Farm Solution Deployment

Below examples shows deploying an application page that contains JavaScript using Farm solution deployment approach.

I am creating an empty SharePoint project in Visual Studio. Next I had added application page with Name 'JSDemo.aspx'. Below is the folder structure for the project.

 

 In Application page, I had created input button with click action, Essentially when I click the button I am loading all the lists present in the site that has an item count greater than 0.

I had used sp.js to create context for this specific site that is declared in ScriptLink tag in the application page. Below is the complete code.

[code]
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <SharePoint:ScriptLink Name="sp.js" LoadAfterUI="true" runat="server" Localizable="false" ></SharePoint:ScriptLink>

    <%--load intellisense for sp.js--%>
    <% #if ZZZZ %>
    <script type="text/javascript" src="/_layouts/SP.debug.js"></script>
    <% #endif %>

    <script type="text/javascript">
        var lists;
        function getLists() {
            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            context.load(web, "Title", "Description");
            lists = web.get_lists();
            context.load(lists, "Include(Title,ItemCount)");
            context.executeQueryAsync(onSuccess,onFail);
        }

        function onSuccess() {
            var ul = document.getElementById("listitems");
            var listsEnum = lists.getEnumerator();
            while (listsEnum.moveNext()) {
                var list = listsEnum.get_current();
                if (list.get_itemCount() > 0) {
                    var title = list.get_title();
                    var elem = document.createElement("li");
                    elem.innerText = title;
                    ul.appendChild(elem);
                }
            }
        }

        function onFail() {
            alert("Request Failed");
        }
    </script>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<input id="getListsButton" type="button" value="Get List items" onclick="getLists()" />
<br />
<br />
<ul id="listitems"></ul>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Application Page
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
My Application Page
</asp:Content>
[/code]

Result: For accessing the application page I am navigating to /_layout/JSApplicationPage/JSDemo.aspx page

Thursday, June 16, 2016

CSOM Managed code implementation on SharePoint Document Library

Below is an example of .net windows application application that performs creating a document library, uploading a text file, retrieving the data present in the file and finally deleting the text file using .Net managed code.
[code]using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientSideApplication
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        public Form1()
        {
            InitializeComponent();
        }   

        private void Upload_Click(object sender, EventArgs e)
        {
            ResultListBox.Items.Clear();
            var siteUrl = "http://stapvsp9007.gcm.com/sites/RRandCR/";
            using (var context = new ClientContext(siteUrl))
            {
                try
                {
                    var web = context.Web;
                    var list = web.Lists.GetByTitle("SharePoint Documents");
                    var filepath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\recurring.txt";
                    var fci = new FileCreationInformation();
                    fci.Content = System.IO.File.ReadAllBytes(filepath);
                    fci.Url = "recurring.txt";
                    fci.Overwrite = true;
                    var file = list.RootFolder.Files.Add(fci);
                    context.ExecuteQuery();
                    ResultListBox.Items.Add("Document Uploaded!");
                }
                catch (Exception ex)
                {
                    ResultListBox.Items.Add(ex.Message);
                }
            }
        }

        private void createLibrary_Click(object sender, EventArgs e)
        {
            ResultListBox.Items.Clear();
            var siteUrl = "http://stapvsp9007.gcm.com/sites/RRandCR/";
            using (var context = new ClientContext(siteUrl))
            {
                try
                {
                    var web = context.Web;
                    var lci = new ListCreationInformation();
                    lci.Title = "SharePoint Documents";
                    lci.TemplateType = (int)ListTemplateType.DocumentLibrary;
                    var list = web.Lists.Add(lci);                  
                    context.ExecuteQuery();
                    ResultListBox.Items.Add("List Added!");
                }
                catch (Exception ex)
                {
                    ResultListBox.Items.Add(ex.Message);
                }
            }
        }

        private void retrieveDoc_Click(object sender, EventArgs e)
        {
            ResultListBox.Items.Clear();
            var siteUrl = "http://stapvsp9007.gcm.com/sites/RRandCR/";
            using (var context = new ClientContext(siteUrl))
            {
                try
                {
                    var web = context.Web;
                    var listName = web.Lists.GetByTitle("SharePoint Documents");                  
                  
                    context.Load(listName);
                    context.ExecuteQuery();

                    Folder folder = listName.RootFolder;
                    FileCollection files = folder.Files;
                    context.Load(files);
                    context.ExecuteQuery();

                    foreach (File f in files)
                    {
                        FileInformation fileInformation = File.OpenBinaryDirect(context, (string)f.ServerRelativeUrl);
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
                        {
                            string line = sr.ReadToEnd();
                            ResultListBox.Items.Add(line);
                        }
                    }                 
                }
                catch (Exception ex)
                {
                    ResultListBox.Items.Add(ex.Message);
                }
            }
        }
      
         private void retrieveDoc_Click(object sender, EventArgs e)
        {
            ResultListBox.Items.Clear();
            var siteUrl = "http://stapvsp9007.gcm.com/sites/RRandCR/";
            using (var context = new ClientContext(siteUrl))
            {
                try
                {
                    var web = context.Web;
                    var listName = web.Lists.GetByTitle("SharePoint Documents");                  
                  
                    context.Load(listName);
                    context.ExecuteQuery();

                    Folder folder = listName.RootFolder;
                    FileCollection files = folder.Files;
                    context.Load(files);
                    context.ExecuteQuery();

                    foreach (File f in files)
                    {
                        FileInformation fileInformation = File.OpenBinaryDirect(context, (string)f.ServerRelativeUrl);
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
                        {
                            string line = sr.ReadToEnd();
                            ResultListBox.Items.Add(line);
                        }
                    }                 
                }
                catch (Exception ex)
                {
                    ResultListBox.Items.Add(ex.Message);
                }
            }
        }
    }
}[/code]