Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Call Server-side Code from Javascript

Sunday, February 08, 2015

6

Server-side code and postbacks already seem like remnants of a bygone era.  The next generation of SharePoint developers will likely know no more about them than punched tape computers.  Yet, there are still scenarios where you just can't avoid server-side operations.

I recently needed a way to asynchronously execute a block of server-side code from client-side Javascript.  It turns out there is an ICallbackEventHandler interface for precisely that purpose!

There's a detailed MSDN article on it, which I did not find very easy to digest.  In this post I'll try to boil it down to the essentials by going over a SharePoint example.

Background

I was building a visual webpart to let users update their Quick Links and other User Profile properties.  I stubbed out my methods, whipped up some JSOM to grab the properties, and threw in a snazzy jQuery drag-and-drop control.

Then, I tried to implement the Save button.  Disaster struck.  User profiles are read-only from all client-side APIs.

The Big Picture

This diagram illustrates the flow of execution from client to server and back.  I'll go over each piece in detail, but this is how they all fit together.



Client Side

We'll start from the Javascript side, as that is where the user action begins.  ICallbackEventHandler lets us asynchronously fire off a server side method, to which we can pass a single string parameter.

Let's say my Quick Links are stored in <div>s on the page:

<div class="link" data-title="Google" data-url="http://www.google.com" />
<div class="link" data-title="Bing" data-url="http://www.bing.com" />
<div class="link" data-title="MSDN" data-url="http://www.msdn.com" />

We can push this information into a JSON object, serialize it into a string, and pass it server-side to be saved.

Invoke server-side code


At this point, the ExecuteServerSide method below that will invoke our server-side code isn't defined yet. We will wire it up later from the code-behind.

function save() {
    var links = [];

    // Create JSON object with link data
    $('.link').each(function () {
        var title = $(this).data('title');
        var url = $(this).data('url');

        links.push({ 'Title': title, 'Url': url });
    });

    // Serialize the object to a string
    var strLinks = JSON.stringify(links);

    // Invoke server-side code.  Will wire up later.
    ExecuteServerSide(strLinks);
}

Completion Handler


Next, let's add the method that will be called when the server-side operation completes.  The server can return a single string back to the page.

function ServerSideDone(arg, context) {
    alert('Message from server: ' + arg);
}

Server Side

Begin by adding the ICallbackEventHandler interface to the webpart's code-behind.  This interface has two methods that need to be implemented: RaiseCallbackEvent and GetCallbackResult.

public partial class QuickLinksEditor : WebPart, ICallbackEventHandler

RaiseCallbackEvent


RaiseCallbackEvent( string eventArg ) is the entry point.  It's what's called by ExecuteServerSide in line #16 of the Javascript above.  eventArg is the string passed from the client side (e.g. the serialized link data)  In most scenarios, you would save this string in a class variable and use it later to perform whatever server-side operation.

We could parse out the links manually, but it's cleaner to make a simple data model class:

[DataContract]
public class QuickLink
{
    [DataMember]
    public string Title;

    [DataMember]
    public string Url;
}

Then we can take advantage of DataContractJsonSerializer to convert the JSON string to a List of QuickLink objects:

public void RaiseCallbackEvent(string eventArg)
{
    // Instantiate deserializer
    DataContractJsonSerializer serializer =
       new DataContractJsonSerializer(typeof(List<QuickLink>));

    // Deserialize
    MemoryStream stream =
       new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(eventArg));

    // Save input data to class variable for later processing
    this.Links = (List<QuickLink>)serializer.ReadObject(stream);
}

GetCallbackResult


This method is where we execute the server-side operation.

It returns a string, which is how information gets passed back to the client-side.  That return value is the ServerSideDone method's arg parameter in line #18 in the Javascript code above.

public string GetCallbackResult()
{
    try
    {
        // Get User Profile Manager and update Quick Links
        // Full code at bottom of article
    } 
    catch(Exception ex)
    {
        return ex.Message;
    }

    return "Success!";
}

Wire Up

Finally, we wire up the two client-side functions, ExecuteServerSide and ServerSideDone.  That is done from Page_Load in the code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    ClientScriptManager scriptMgr = Page.ClientScript;

    // Completion handler
    String callbackRef = scriptMgr.GetCallbackEventReference(this, 
        "arg", "ServerSideDone", "");

    // Invoke server-side call
    String callbackScript = 
        "function ExecuteServerSide(arg, context) {" + 
        callbackRef + 
        "; }";

    // Register callback
    scriptMgr.RegisterClientScriptBlock(this.GetType(), 
       "ExecuteServerSide", callbackScript, true);
}

Again, note that line #7 here defines the method signature in line #18 of the Javascript.  And line #11 here defines the method called in line #16 of the Javascript.

That's it!

Complete Code-behind


using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;

using Microsoft.SharePoint;

namespace SharePointificate.QuickLinksEditor
{
    [DataContract]
    public class QuickLink
    {
        [DataMember]
        public string Title;

        [DataMember]
        public string Url;
    }

    [ToolboxItemAttribute(false)]
    public partial class LegacyQuickLinks : WebPart
    {
        private List<QuickLink> Links;

        public LegacyQuickLinks()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScriptManager scriptMgr = Page.ClientScript;

            String callbackRef = scriptMgr.GetCallbackEventReference(this, 
                "arg", "ServerSideDone", "");

            String callbackScript = 
                "function ExecuteServerSide(arg, context) {" + 
                callbackRef + 
                "; }";

            scriptMgr.RegisterClientScriptBlock(this.GetType(), 
                "ExecuteServerSide", callbackScript, true);
        }

        public string GetCallbackResult()
        {
            try
            {
                SPServiceContext serviceContext = 
                    SPServiceContext.GetContext(SPContext.Current.Site);

                UserProfileManager userProfileManager = 
                    new UserProfileManager(serviceContext);

                UserProfile currentUser = 
                    userProfileManager.GetUserProfile(true);

                QuickLinkManager quickLinkManager = currentUser.QuickLinks;

                quickLinkManager.DeleteAll();

                foreach (QuickLink link in this.Links)
                {
                    quickLinkManager.Create(link.Title, link.Url, 
                        QuickLinkGroupType.General, null, Privacy.Public);
                }
            } 
            catch(Exception ex)
            {
                return ex.Message;
            }

            return "Success!";
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            DataContractJsonSerializer serializer = 
                new DataContractJsonSerializer(typeof(List<QuickLink>));

            MemoryStream stream = 
                new MemoryStream(ASCIIEncoding.ASCII.GetBytes(eventArgument));

            this.Links = (List<QuickLink>)serializer.ReadObject(stream);
        }
    }
}


JavaScript Promise vs Deferred

Monday, May 05, 2014

1

jQuery Promises have been around for a while, but I've always slinked away tail between my legs at the mere mention of them. Running might have attracted the beast's attention. Alas, my new project uses Promises religiously. They are actually nifty constructs once you wrap your head around them.  I had to stew and mull for about a week before I could grasp the difference Promises and Deferred (I know, what a scrub)

This post is for anyone specifically wondering about Promises vs Deferred.  I'm not going to talk about Promises in general--there are already a ton of good articles on that topic.

There is really nothing special about Promises and Deferred--they are both plain ol' JavaScript objects.  Every Deferred object has a corresponding Promise object.  The Promise is essentially a copy of the Deferred with limited functionality.

When you are running an async operation, you create a Deferred.  You can then use it to attach handlers, and more importantly, Resolve or Reject when the operation completes.  In the meantime, you get the Deferred's corresponding Promise and return that to your caller.


As the caller, you get back a Promise object with which you can also attach handlers. The difference is that you can NOT trigger those handlers by calling Resolve or Reject.  This makes sense, because the caller wouldn't / shouldn't know about the async operation and when it completes.
 


Blogger Post Summaries & Thumbnails, Part II

Monday, September 05, 2011

6

This is Part II on how to make Blogger display post summaries with thumbnail previews.  Part I goes over exactly what we're trying to accomplish and how the results will look.

The process described here should work on all the out-of-box Blogger templates.  Complications may arise if you're using a heavily customized template... Be sure to save a copy of your template before making any changes!


Edit Template

First, we have to open the blog template for editing.  On your blog's Administration page, go to Template, then click on Edit HTML:


Check Expand Widget Templates.  Before continuing, save a copy of the full template just in case.



Insert Summary Generation Script

Next, we insert a piece of javascript to generate the summaries.  Search for the following tag in the template: <b:includable id="main" var="top">


Copy and paste the code in this file into the space circled in red above:



Update Post Body Template

Finally, we update the template that renders a post to invoke the summary creation script if the current page is the Home page.  If we're on an individual post page or a static page, then display the full post body as normal.

To do so, search for the following tag in the template: <b:includable id="post" var="post">.  Then, search for <data:post.body/> beneath that.  Note that there may be more than one <data:post.body/> in the template, and we specifically want the one under that first tag:


Replace the tag with the contents of this file:


That's it!  Save the template and you should start seeing post summaries on your blog. For reference, here's the entire default Simple template with the added code.


Working with Thumbnails

By default, the first image in post will be used as the thumbnail.  You can override this behavior on specific posts by setting the class attribute on its images (from the post editor's HTML view).  Note that the attributes are case-sensitive.

  • - To use an image other than the first as the thumbnail, set that image's class to preview
  • - To specifically prevent an image from being used as the thumbnail, set its class to noPreview
  • - To use a completely different thumbnail, add the thumbnail image to the post, and set its class to hiddenPreview.  This image will not be visible on the full post, but will be used as the thumbnail for the summary.  I'd recommend putting this at the very end of the post.

For instance, the update below would cause the second image to be used as the thumbnail:


The end!


Blogger Post Summaries & Thumbnails, Part I

Monday, September 05, 2011

0

So I stumbled on some Blogger templates and decided to give my poor, tired blog a makeover.  I fell hard for the pretty ones with the flyout menus, post summaries, thumbnails and all.  Unfortunately, like so many of my flirtations with pretty things, it ended only in despair and disappointment.  My blog ended up looking nothing like what the previews promised, mainly because:

  • - The thumbnail images were stretched to fit, instead of cropped.  They looked absolutely atrocious unless the first picture in all my posts happened to be square.
  • - The preview text was one big blob of text since HTML elements like line breaks, coloring, and bullet points were being stripped.
  • - I couldn't use an image other than the first in a post as the thumbnail preview


That can't fly!  I did some digging and cooked up a short script to generate summaries.  It should work with most Blogger templates, and for sure the out-of-box ones.  Here's how it looks applied to the default "Simple" template.  I can create posts with any formatting and images of any size.



The Home page shows the first few lines of each post, with a "Read More" link to the full post.  Note that formatting like linebreaks and bullets are preserved.  The 200 x 200 thumbnails are then cropped from the top left corner of the first image (unless otherwise specified) in the post.



Read Part II for how to implement this.




Sending data from codebehind to javascript

Monday, September 05, 2011

4

*Feb 2015 Edit: For a solution to the slightly more complex problem of asynchronously calling server-side code from Javascript, and sending back the results, check out my ICallbackEventHandler post.


A few days ago I had to implement a page that lets users apply filters to a dataset (from SharePoint) without reloading the page.  My initial thought was to either:

  1. Use an ajax UpdatePanel.  This would require a postback, but the user wouldn't notice it.
  2. Use jQuery to make a webservice call to the SharePoint search service, and update the page with the results.  This would happen completely on the client side.

    Unfortunately, for this particular project both ajax and the search service were off limits.  Also, the dataset was tiny (< 50 rows) so posting back or re-querying seemed like a waste.  Some research led to a very elegant third option:

    1. Get the entire dataset before the page renders (in codebehind)
    2. Serialize the dataset to JSON format
    3. Render the JSON dataset onto the page as a javascript variable so that it can be manipulated clientside

    Now the JSON data can filtered completely on the client side using jQuery or plain javascript.  This option doesn't require postbacks or hitting a webservice, and the JSON data can be manipulated in object oriented fashion.

    Here's an example with two simple datamodel classes, Company and Employee:


    Say we have a method GetAllCompanies() that returns an array of Companies, which we want to manipulate client side.  First we have to serialize the array into JSON.  Luckily, there there's a JavaScriptSerializer under the System.Web.Script.Serialization namespace that does exactly that.  Next we render the JSON string onto the page as a javascript variable:


    If you look at the page source after the page loads, there should be a script block with the JSON data that looks like something like this:

    Now the object oriented data in the 'companies' variable can be manipulated from javascript!


    Javascript blocks are processed top to bottom, so make sure the JSON script block appears above any script that uses that data.  Otherwise, the variable will be undefined.