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

Friday, June 17, 2016

JavaScript in Sandbox Solutions

Below examples shows deployment of JavaScript files through Sand boxed solution approach. As we know, Sand boxed solutions cant deploy the files to layout directory of SharePoint, I am deploying JavaScript files to Style library and then going to consume in java script code using custom action. Please see the details below.

1. Create a empty SharePoint 2010 or 2013 Empty project with Sand boxed solution selection.

2. Create a module called as 'Scripts' by right clicking on VS project,  I am using module because I will be installing js files in Style library folder of the site.

3. Copy the java script files(jquery-1.8.3.js, jquery-1.8.3.min.js) under scripts also name the Feature appropriately.

Below is the folder structure of application after following the above steps.


In the Element.xml I am going to define the location of JavaScript file location with along Code.txt, The Code.txt contains the required java script that basically displays the site name.

I am using a custom action that would essentially load the 'jquery-1.8.3.min.js' when code.txt starts executing.  Below is how final Element.Xml will look.

[code]<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Scripts" Url="Style Library/Scripts" RootWebOnly="TRUE">
    <File Path="Scripts\jquery-1.8.3.js" Url="jquery-1.8.3.js" Type="GhostableInLibrary"/>
    <File Path="Scripts\jquery-1.8.3.min.js" Url="jquery-1.8.3.min.js" Type="GhostableInLibrary"/>
    <File Path="Scripts\Code.txt" Url="Code.txt" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" /> 
  </Module>
  <CustomAction
  Id="LoadQuery" ScriptSrc="~SiteCollection/Style Library/Scripts/jquery-1.8.3.min.js"
  Location="ScriptLink"
  Sequence="10">
  </CustomAction>
</Elements>
[/code]
Below is final copy of Code.txt file.

[code]<script type = "text/javascript">
    jQuery(document).ready(function() {
    //below code ensure client object is loaded prior to page execution
    ExecuteOrDelayUntilScriptLoaded(initialize,"sp.js");
    });

function initialize(){
    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    context.load(web, "Title");
    context.executeQueryAsync(success,fail);

function success(){
    var message = jQuery("#message");
    message.text("This site is named " + web.get_title());
}

function fail(sender, args){
    alert("Call failed. Error:" + args.get_message());
    }
}

</script>
<div id="message"></div>
[/code]

Once we deploy the solution, I am using a web part to test javascript code.