Tag Archives: JavaScript

Хутка і лёгка: Стварыць SharePoint вузла з дапамогай REST

There are a lot of resources around that show how to do this, but I couldn’t find a comprehensive go-to link, so here we are.

You can create a SharePoint site using the REST API.  Here’s a fully baked example:

<!--
    SiteRequestForm.html: Collect information and create a site for the user.
-->

<цэнтр>
<стол>
    <тр>
        <TD>Site Name:</TD>
        <TD><ўваход тып="text" імя="SiteName" ID="SiteName" /></TD>
    </тр>
    <тр>
        <TD colspan="2">
            <ўваход тып="submit" ID="CreateSiteButton" значэнне="Create the Site" />
        </TD>
    </тр>
</стол>
</цэнтр>

<сцэнар SRC="../Plugins/jquery-1.11.0.min.js"></сцэнар>

<сцэнар>
было CreateSiteLogicContainer = {

    createSiteData: {
            "parameters": {
                __metadata: { "type": "SP.WebInfoCreationInformation" },
                Url: "Paultest1",
                Назва: "Paultest1",
                Апісанне: "rest-created web by Paul!",
                Мова: 1033,
                WebTemplate: "sts",
                UseUniquePermissions: ілжывы
            }
    },

    createSite: функцыя () {

        jQuery.support.cors = праўда;

        CreateSiteLogicContainer.createSiteData.parameters.Url = $("#SiteName").Вал();
        
        $.ajax({
            URL-адрас: "https://bigapplesharepoint.sharepoint.com/NBAIADev/_api/web/webinfos/add",
            метад: "POST",

            headers: {
                "Accept": "application/json; odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").Вал()
            },

            дадзеныя: JSON.stringify(CreateSiteLogicContainer.createSiteData),

            success: функцыя () { Апавяшчэнні("success"); },
            памылка: функцыя () { Апавяшчэнні("error"); }

        });
    },

    wireUpForm: функцыя () {
        $("#CreateSiteButton").пстрычка(функцыя () {
            Апавяшчэнні("About to try and create the site.");
            CreateSiteLogicContainer.createSite();
        });
    }


}

CreateSiteLogicContainer.wireUpForm();

</сцэнар>

When successful, you get a JSON packet in response like this:

image

My key thoughts and learnings from this include:

  • This approach uses jQuery.  У маім выпадку, my jQuery library is located in “../plugins.”  You’ll want to change that to point to your favorite JQ location.
  • You can copy and paste that whole snippet into a Content Editor Web Part on a page and it should work just fine.  You’ll want to change the end point of the API call and make sure you reference JQ correctly.
  • The URL is relative to your API’s endpoint.  У маім выпадку, it’s creating sub-sites underneath https://bigapplesharepoint.com
  • You don’t need to provide a content-length. Some blog posts and MSDN document implies that you do, but happened for me automatically, which I assume is being handled by the $.ajax call itself.
  • This line is required in order to avoid a “forbidden” response: "X-RequestDigest": $("#__REQUESTDIGEST").Вал().  There are other ways to do it, but this is pretty nice.  I have lost the link to blog that provided this shortcut.  H/T to you, mysterious blogger!

Good luck and hope this helps someone out.

</канец>

undefinedПадпісацца на мой блог.

Выконвайце за мной на Twitter у http://www.twitter.com/pagalvin

Хутка і проста: SharePoint REST выкліку вяртае толькі 100 Ўлік

I’ve been working on a public facing web site for my SharePoint practice here in New York and it uses a lot of JavaScript and REST calls to show content.

During mainline development, I create a small dataset with just 10 or so rows in a custom list and my REST calls all pulled from there.  Once I bumped up the list to have a few hundred rows of data to test for anticipated growth, I found that I was getting exactly 100 rows returned back on my REST calls.

This is a very simple thing to address.  У маім выпадку (and I believe in most cases), the default REST calls to SharePoint (and possibly as an industry standard?) вяртанне 100 rows.  To return more than the default, use the $top parameter on your call, як у:

GET /Insights Dev/_api/web/lists/GetByTitle(‘MockBlog’)/элементы?$select=ID,Назва,Categories/Title,Blog_x0020_Author/Title,DatePublished,BlogSummary&$expand=Blog_x0020_Author,Катэгорыі&$filter=&$top=9999

I picked 9999 in this case since I know that growth-wise, there won’t be more than 200 or so rows added to this list in a year.  If it becomes ungainly, we can implement some paging down the road.

</канец>

undefinedПадпісацца на мой блог.

Выконвайце за мной на Twitter у http://www.twitter.com/pagalvin

Кэшаванне бедняка у JavaScript

[TL;DR version: use cookies to store the results of async calls; render the results of past async calls immediately and then validate them after page-load.]

I’ve been working on SharePoint intranet site for a client that features, між іншым, a stylized secondary navigation whose menu options are managed via a regular old custom list.  The idea is that the client gets to control “their” site’s menu without affecting or being affected by the global navigation put out by IT.

(there is something incredibly subversive about adding a CEWP that points to an HTML file that loads some CSS and JS to fundamentally alter almost everything about a site’s behavior… but that’s for another post)

The code for this pretty simple:

The sore spot here is that every time anyone hits one of the site’s pages, that user’s web browser is reaching out to get items from the list.  Once dev is complete and testing has proven things to be stable and complete, this call is unnecessary more than 99% of the time since the menu rarely changes.  It also has a weird UI affect which is common in this brave new world of hyper-ajaxy web sites – the page renders and only then does the menu render.  It’s jittery and distracting in my view.  And jittery. Так, caching. 

I modified the logic thusly:

  • Look for a cookie in the browser that contains the menu as I last read it
    • If found, render it immediately.  Don’t wait for the page to finish loading.  (You need to make sure your HTML is strategically placed here, but it’s not hard to do).
  • Wait for the page to finish loading and make an async call to load up menu items from a list using REST or lists.asmx or whatever
  • Compare what I got against the cookie
    • If it matches, STOP
    • У адваротным выпадку, using jQuery, dynamically populate a bunch if <Li>’s in a <Вуліца>
  • Use CSS to do all the formatting
  • Profit!

Some of you are going to say, “hey! there’s no real caching going on here since you’re reading the menu anyway every single time."  And you’re right – I’m not giving the server any kind of break.  But because the call is async and happens after the page’s initial HTML payload fully renders, it “feels” more responsive to the user.  The menu renders pretty much as the page draws.  If the menu happens to the change, the user is subjected to a jittery re-draw of the menu, but only that one time.

There are some ways to make this caching more effective and help out the server at the same time:

  • Put in a rule that the “cookie cache” is valid for a minimum of 24 hours or some other timeframe. As long as there is no expired cookie, use the cookie’s menu snapshot and never hit the server.

Well … that’s all that come to mind right now :). 

If anyone has any clever ideas here I’d love to know them.

And lastly – this technique can be used for other stuff.  This client’s page has a number of data-driven things on various pages, many of them changing relatively rarely (like once a week or once a month).  If you target specific areas of functionality, you can give a more responsive UI by pulling content from the local cookie store and rendering immediately.  It feels faster to the user even if you’re not saving the server any cycles.  Вы можа save the server cycles by deciding on some conditions and triggers to invalidate this local cookie cache.  That’s all situational and artsy stuff and really the most fun :). 

</канец>

undefinedПадпісацца на мой блог.

Выконвайце за мной на Twitter у http://www.twitter.com/pagalvin