in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint, Office 365, Mobile Development, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, Office 365 / SharePoint Online and Visual Studio 2013.

October 2012 - Posts

  • Announcing #ShareHofbrau – Hofbrauhaus Las Vegas after #SPC12

    I’m pleased to announce, that we’re doing #ShareHofbrau again at Hofbrauhaus Las Vegas on Thursday November 15th at 4:00 pm.  We did this event at SPC09 and it was a lot of fun so we’re doing it again.  If you’re not familiar with it, Hofbrauhaus is an authentic German beer hall just off the strip.  Basically, picture a place where Oktoberfest is everyday and they serve Hofbrau beers.  I know a lot of people are flying home on Thursday night, but I also know a lot aren’t leaving until the morning.  So come by and have a beverage before you leave Vegas and use this as the last opportunity to talk to SharePointers from all over the world.  It’s a great way to unwind after a great week at the conference.   I wonder if @JenFloyd08 still has the pictures from last time?  Lol. 

    Hofbrauhaus is located not far off the strip at 4510 Paradise Road near the Hard Rock Hotel.  So come ready to talk about SharePoint and eat and drink some fine German food and beverages.

    If you are interested in coming, indicate your interest by going to the link below.

    http://sharehofbrau.eventbrite.com/

    For more information follow #ShareHofbrau on twitter.

    Thanks and see everyone there!

    @coreyroth

  • How to: Query List Items from the Host Web in a Client Web Part of a SharePoint Hosted app

    That’s a mouthful, but I wanted to make sure that people knew exactly what this post is for.  The problem I am seeing out there already is that while there is a lot of code samples, they aren’t clear for what type of app the sample is for.  If you are doing a provider hosted app for example, the way you query list items is different (using the Cross-Domain Library).  Today’s topic boggled me though because while I found plenty of samples on how to query list items using CSOM from an app, they were all in-fact incorrect for a SharePoint hosted app.  The article I linked is great by the way.  It has many of the things you need to know how to do via CSOM in an app so be sure and check it out.

    Now to get on to the scenario I want to help you with today.  If you are building a Client Web Part, you may have stumbled upon my previous articles on the topic (JavaScript and Getting Started).  These are great articles to get you started, however, it turns out I left out the details on how to query list items from a SharePoint hosted app.  Like many things, it’s not as simple as I thought it was.  I thought it was just a matter of passing another URL into get_web().  I was wrong.  I then saw some examples and thought I just need to pass the URL into a new SPContext object.  Also wrong.  While, you can do that, once you make the call to get your list items, you’ll quickly find yourself with an Access Denied error coming from MicrosoftAjax.js.  I gave up and posted something to the forums and luckily Elisabeth Olson from MSFT came through with the answer.  In my solution, I start with some global variable declarations.

    var context;

    var web;

    var user;

    var spHostUrl;

    var parentContext

    Then the code looks similar to that from my article on SP.js.  In the document ready function, I get the spHostUrl with the following line of code.  You can get that getQueryStringParameter method from my previous article as well.  Remember, the SPHostUrl comes from the {StandardTokens} parameter in your Client Web Part’s elements.xml file.

    spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

    Now, we set up our context and here is where things are a bit different.  First, we get our context object using SP.ClientContext.get_current() as usual.  However, we have to get a new context by using SP.AppContextSite and passing in the current context along with the Host Url.

    context = new SP.ClientContext.get_current();

    parentContext = new SP.AppContextSite(context, spHostUrl);

    After that, we just need to get our SPWeb object using the parentContext.

    web = parentContext.get_web();

    At this point, it’s business as usual to do our queries.  Get the list, set a CAML query, load the getItems call, and then execute the query.

    var list = web.get_lists().getByTitle("My List"));

     

    var camlQuery = new SP.CamlQuery();

    camlQuery.set_viewXml("");

     

    this.listItems = list.getItems(camlQuery);

    context.load(listItems);

     

    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),

        Function.createDelegate(this, this.onQueryFailed));

    My success and failure functions are pretty standard in this case.  I just manually iterate through the results and return the Title and Id.  Otherwise, I display the reason for failure.

    function onQuerySucceeded() {

        $("#results").empty();

        var listInfo = '';

        var listEnumerator = listItems.getEnumerator();

     

        listInfo += "<table><tr><th>Id</th><th>Title</th></tr>";

     

        while (listEnumerator.moveNext()) {

            var listItem = listEnumerator.get_current();

            listInfo += '<tr><td>' + listItem.get_item('ID') + '</td>'

                + '<td>' + listItem.get_item('Title') + '</td>'

                + '</tr>\n';

        }

     

        listInfo += '</table>';

     

        $("#results").html(listInfo);

    }

     

    function onQueryFailed(sender, args) {

        $("#results").empty();

        $("#results").text('Request failed. ' + args.get_message() +

            '\n' + args.get_stackTrace());

    }

    This threw me for a loop for a while, so hopefully this post helps you get started quicker when you build your app.

    Follow me on twitter, @coreyroth, if you have any questions and come see me at SPC if you are going.

  • Note the four hotfixes required for SharePoint 2013 RTM Installation

    Sometimes, it pays to read the manual.  I happened to glance at it while I was doing my installation last night and noticed that there are four required hotfixes you need to install prior to installation of SharePoint 2013 RTM.  You install these after installing the prerequisites via the newly named Microsoft SharePoint Products Preparation Tool.

    Here are the required hotfixes.

    The first two actually require you to enter your E-mail to receive the link.  The latter link directly to the download themselves.  In my particular install, I found that I could install the first three, but the fourth one said it was not applicable to my system.  I proceeded without it and I haven’t seen any major issues (aside from not being able to install Workflow Manager 1.0).  However, I don’t think that is related to the hotfix.

  • Copying Site Collections with PowerShell in SharePoint 2013 Preview

    I’m working on my PowerShell for SharePoint 2013 (SPC195) talk for SPC12 and I find this new cmdlet so useful I thought I would share it immediately.  The cmdlet is Copy-SPSite and it’s easy to use.  Just run it and before you know it, you’ll have a duplicate of a site collection on a fresh new URL.  You can even optionally specify a new content database.  Here is what it looks like:

    Copy-SPSite http://server/sitecollection –DestinationDatabase MyContentDb –TargetUrl http://server/sitecollection2

    A successful execution will return nothing at the command prompt.  This is a great cmdlet for developers and IT pros that often need to quickly clone site collections and tear them down. It will take longer for bigger site collections of course.  Try it out today.

  • How to: Use the SharePoint 2013 Client Object Model (SP.js) from a Client Web Part

    I was talking to Tom Resing (@resing) last week about using the SharePoint Client Object Model inside a Client Web Part and it became apparent that I left you all hanging with my last post.  I got you to the point where you could build your web part, but referencing SP.js is not as simple as you would think it would be.  I had to look at a lot of code samples to put this all together.  This follow-up post will give you the necessary steps to get started working with SharePoint right away.

    The first thing I do is add some script references to the page.  For Client Web Parts, I tend to use a new .js file to host the web part’s JavaScript and I leave app.js to serve the needs of Default.aspx.  Building on my example from the last post, I add a new script called HelloWorldClientWebPart.js.  I add this in the Scripts folder. 

    AppHelloWorldScriptProjectItem

    We’ll add our code to this file in a minute but first I want to add those references.  In this case, we aren’t loading a reference to SP.js yet.  Instead, we’ll load jQuery from a CDN as well as MicrosoftAjax.js.  You may not need all of those, but chances are you do.

    <head>

        <script type="text/javascript" src="../Scripts/jquery-1.6.2.min.js"></script>

        <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>

        <script type="text/javascript" src="../Scripts/HelloWorldClientWebPart.js"></script>

    </head>

    Now we’ll jump over to our new script file.  We’re going to borrow a few lines from App.js starting with variables to hold the context, web, and user.

    var context;

    var web;

    var user;

    Now we use jQuery’s document.ready function to add our code.

    $(document).ready(

        function () {

        }

    );

    You can add this line to your document.ready function to get a reference to the SPSite object of the site hosting the client web part (app part) as opposed to the site actually hosting the app itself.  We’ll also need it to get our reference to SP.js as well.

    //Get the URI decoded SharePoint site url from the SPHostUrl parameter.

    var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

    This method relies on getQueryStringParameter which you’ll find in many App examples.

    function getQueryStringParameter(urlParameterKey) {

        var params = document.URL.split('?')[1].split('&');

        var strParams = '';

        for (var i = 0; i < params.length; i = i + 1) {

            var singleParam = params[i].split('=');

            if (singleParam[0] == urlParameterKey)

                return decodeURIComponent(singleParam[1]);

        }

    }

    To get the host URL, you will have to modify your elements.xml to make this work.  Do this by adding {standardtokens} to the URL of the Content element.

    <Content Type="html" Src="~appWebUrl/Pages/HelloWorldClientWebPart.aspx?{StandardTokens}" />

    When you do this, SharePoint will automatically pass you a number of query string parameters that you can take advantage of including the SPHostUrl.  At that point you can pass the URL into your call to get a SPWeb object.

    Back in the JavaScript file, we add the rest of our code.  First we need to get the URL to the 15 folder inside _layouts and assign it to our layoutsRoot variable.  Now we can use the jQuery getScript() method to retrieve the scripts we need.  Before you get SP.js, you have to get SP.Runtime.js.  That is why you see the nested calls below.  Once SP.js can be retrieved, it makes a call to the execOperation method.  This method can then take advantage of the SharePoint Client Object Model.

    //Build absolute path to the layouts root with the spHostUrl

    var layoutsRoot = spHostUrl + '/_layouts/15/';

     

    $.getScript(layoutsRoot + "SP.Runtime.js", function () {

        $.getScript(layoutsRoot + "SP.js", execOperation);

    }

    );

    To demonstrate it’s use, we’ll use the same script example used in App.js.  We start by defining execOperation and getting a reference to the content and SPSite object.

    function execOperation() {

        // get context and then username

        context = new SP.ClientContext.get_current();

        web = context.get_web();

     

        getUserName();

    }

    We then use the same getUserName() and other functions from App.js.

    function getUserName() {

        user = web.get_currentUser();

        context.load(user);

        context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);

    }

     

    // This function is executed if the above OM call is successful

    // It replaces the content of the 'welcome' element with the user name

    function onGetUserNameSuccess() {

        $('#message').text('Hello ' + user.get_title());

    }

     

    // This function is executed if the above OM call fails

    function onGetUserNameFail(sender, args) {

        alert('Failed to get user name. Error:' + args.get_message());

    }

    Putting the entire script together, here is what it looks like.

    var context;

    var web;

    var user;

     

    //Wait for the page to load

    $(document).ready(

        function () {

            //Get the URI decoded SharePoint site url from the SPHostUrl parameter.

            var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

     

            //Build absolute path to the layouts root with the spHostUrl

            var layoutsRoot = spHostUrl + '/_layouts/15/';

     

            $.getScript(layoutsRoot + "SP.Runtime.js", function () {

                $.getScript(layoutsRoot + "SP.js", execOperation);

            }

            );

     

            // Function to execute basic operations.

            function execOperation() {

                // get context and then username

                context = new SP.ClientContext.get_current();

                web = context.get_web();

     

                getUserName();

            }

        }

    );

     

    function getQueryStringParameter(urlParameterKey) {

        var params = document.URL.split('?')[1].split('&');

        var strParams = '';

        for (var i = 0; i < params.length; i = i + 1) {

            var singleParam = params[i].split('=');

            if (singleParam[0] == urlParameterKey)

                return decodeURIComponent(singleParam[1]);

        }

    }

     

    // This function prepares, loads, and then executes a SharePoint query to get the current users information

    function getUserName() {

        user = web.get_currentUser();

        context.load(user);

        context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);

    }

     

    // This function is executed if the above OM call is successful

    // It replaces the content of the 'welcome' element with the user name

    function onGetUserNameSuccess() {

        $('#message').text('Hello ' + user.get_title());

    }

     

    // This function is executed if the above OM call fails

    function onGetUserNameFail(sender, args) {

        alert('Failed to get user name. Error:' + args.get_message());

    }

    Lastly, I update HelloWorldClientWebPart.aspx with a div to hold the results.  Here is what the entire file looks like.

    <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

    <WebPartPages:AllowFraming ID="AllowFraming1" runat="server" />

    <head>

        <script type="text/javascript" src="../Scripts/jquery-1.6.2.min.js"></script>

        <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>

        <script type="text/javascript" src="../Scripts/HelloWorldClientWebPart.js"></script>

    </head>

    <div>

        <h2>Hello World Client Web Part!</h2>

        <div id="message"></div>

    </div>

    We can then execute the app in the debugger and then add the App Part to the root page of our developer site.  It should look something like this when you’re done.

    AppClientWebPartWithJavaScript

    Sorry to leave you hanging like that on my previous blog post.  I hope this helps you get started with your app.  It’s a bit involved but not too bad.  It would be nice to create a custom SharePoint Project Item that does this for us.

    Come see my sessions at SPC12 and follow me on twitter @coreyroth.

  • How to: Disable Reading View in Word 2013 Preview

    Correct me if I am wrong, but I believe it was Office 2000 (maybe 2003), where we first saw Reading View appear as the default.  I really wasn’t a fan of it then and this was one of the first settings I changed.  Reading View made a return in Office 2013 Preview.  I gave it a chance, but ultimately, I just couldn’t make it work for me.  I even had a few discussion on twitter about it and others really liked it.  Maybe, I’ll give it another try when I get a tablet, but for now, it’s got to go.  Since there is a ton of settings, I thought I would share quickly how to turn this off if you don’t care for it.  Once you are in Word, click on File –> Options.  On the General tab, towards the bottom of the screen look under Start up options for the setting Open e-mail attachments and other uneditable files in reading view.  Uncheck that box and you’re good to go.

    WordReadingViewDisabled

    It took me a second to find this setting even though it’s right there on the first tab.  Now, my documents open in Print Layout as I prefer. :)

    Posted Oct 03 2012, 01:02 PM by CoreyRoth with 28 comment(s)
    Filed under:
  • Back for a third year as Microsoft SharePoint MVP

    I am happy to say that I am back for another year as a SharePoint MVP.  This last 12 months has been exciting.  I’ve spoken at SharePoint Conference and two Tech Eds.   Going to Europe was awesome. :)  I’ve met a lot of new people and had a blast promoting SharePoint.  I want to thank everyone in the SharePoint community.  Hands down we have the best technical community out there. 

    Looking forward to seeing everyone at SPC!  Come see my talks. :)

    Follow me on twitter @coreyroth.

2015 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems