Saturday, March 14, 2015

Getting started with Single Page Apps

I hope you’ll indulge me showing my age a bit to start this blog post. I remember the release of Netscape Navigator 4.0 and Microsoft Internet Explorer 4.0. There was quite a bit of hype behind those browsers, as people were predicting you wouldn’t need an operating system any longer, just a browser. Obviously that hasn’t been realized.

However, browsers have become more capable. Implementations have become more standards based. And we, as developers, have access to more power and frameworks than ever before.

While the browser won’t be replacing the OS anytime soon, you can absolutely build apps that behave like they’re locally installed, hosted in the browser. This is the concept of a single page app, or SPA.

An SPA offers several advantages to the web developer. They can often[1] achieve the goal of “write once, run anywhere”, using tools such as jQuery, AngularJS, SignalR, and Bootstrap. All of those client-side frameworks are built using languages web developers are already familiar with – JavaScript, CSS and HTML5. And the server-side can be implemented using whatever technology you’re already using, as you can create HTTP or REST services using ASP.NET Web API and MVC, PHP, and Python Django.

I often have developers ask when they should us an SPA, as opposed to a “traditional” website with MVC. The answer is based on what you’re trying to accomplish. SPAs are perfect when you’re trying to simulate a locally installed application. Ride sharing, location sharing, and games are perfect for SPAs. Traditional websites are perfect for sharing information with the public, for ecommerce or other businesses.

One challenge SPAs present is search engine optimization (SEO). Traditional websites are handled very well by web crawlers, which makes SEO more straight forward. Because web crawlers don’t execute JavaScript, SEO with SPAs becomes a challenge. But there are times when SEO isn’t key. If you already have an established brand, or or scenarios where someone simply finding your app but not the actual data served up by it, then SEO isn’t as important.

But one big thing to keep in mind is that SPA and traditional websites are not mutually exclusive. You could, for example, build an ecommerce site using MVC, and then implement the shopping card UI, both adding items and completing checkout, as an SPA.

If you’re ready to begin the journey into building SPAs, we have several MVAs that can support you.

A great starting point is with Building responsive UI with Bootstrap. Bootstrap is a framework developed by Twitter to be mobile-first, and it simplifies the creation of apps that can scale to different device sizes. It also includes the timeless humor of me and Jon Galloway. And by timeless, I of course mean corny.

The next step is to explore the client side technology. Introduction to AngularJS, Stacey Mulcahy and I will walkthrough one of the most popular frameworks for creating SPAs.

Finally, you need a server to provide the data. In Web API Design Jump Start, Jeremy Likness and I show you how to expose JSON data to clients using an environment you’re already familiar with as a .NET developer.

For extra credit, you can complete the app by allowing two-way client-to-server communication. Jon Galloway and Brady Gaster show you how to how to Light up real-time communications with SignalR.

SPAs can provide that rich user experience across all devices without having to learn a lot of new platforms. With a bit of experience in a couple of new frameworks, you too can meet your users’ needs.

[1] Admittedly, not always

Monday, February 16, 2015

Getting Started with GitHub

If you’ve attended any of the Python and Flask courses that Susan Ibach and I have delivered, or many of the other development MVAs lately, you no doubt noticed we’ve been sharing our code via GitHub.

GitHub, if you’re not familiar with the service, is the de facto choice for most open source developers, as well as those looking to play with code. GitHub offers tools for issue tracking, wikis and documentation. Put simply, it’s a great web site used for storing source code and developer collaboration.

Inside of GitHub you can create what are known as repositories, or repos as the cool kids like to say[1]. Repos are containers for files of almost any variety, and those files can be organized into folders.

The main question becomes, “How do I download the source shared on GitHub?”

The first, and simplest, is to use the Download Zip button on the lower right-hand corner. This button, as you might expect, will zip up the contents of the repository and allow you to download it. From there you can extract the contents to a folder of your choice and away you go from there. The downside is that is a bit of a manual process.

DownloadZip

The second option is to clone the repository. Cloning a repository will give you a copy of the code, and allow you to download (or sync) any changes that are made to that repository later. The nice part about cloning is it integrates nicely with Visual Studio, and you can keep current on any changes. The downside is you’re not able to easily modify the code on your own as any changes you make would be overwritten the next time you chose to sync. That said, generally speaking, after an MVA is recorded few changes are made to the repository.

To clone a repository, simply click the copy button (the one that’s circled) under the HTTPS clone URL heading on the lower right.

Clone

Then, in Visual Studio, open the Team Explorer (View > Team Explorer), and click the Connect button (the one that looks like a plug).

VisualStudioClone

The last step is to paste the copied URL into the URL textbox in Visual Studio and click Clone. This will download all of the files into a folder located at C:\Users\<your username>\Source\Repos\<repo name>. After the files are downloaded you can double click on the clone name and it will list all of the Visual Studio solutions for that repo.

The final option, and probably the best option, is to fork the repo. Forking will give you a completely separate copy of the repo on your own GitHub account. The advantage to forking the repo is you are free to make whatever changes you like to the repo as it’s all yours.

To fork a repo, logon to GitHub. Then navigate to the GitHub repo you wish to fork, and then click Fork in the upper right-hand corner. GitHub will then prompt you asking which account you’d like to use (if you have multiple), and then fire up its copy machine to duplicate the code.

Fork

Once the fork is created you have a new repo that is all yours with all of the code shared from the MVA. You can then clone that new repo into Visual Studio using the exact same steps above (click the copy button, then go into Visual Studio and clone the repo).

Going forward you’ll notice most, if not all, MVAs that focus on developer topics will be using GitHub to share code. If you’re looking to put your newly honed skills to use, join Susan and I as we head back into the studio to close out our Python and Flask trilogy, digging deeper into Flask development and introducing relational databases. See you then!

[1]I’m not actually a cool kid, but this is what I’ve been told.

Friday, December 19, 2014

Why do I need to set the same attribute twice in CSS?

Recently I went into the studio with Helen Zeng to record an MVA on CSS. For those of you not familiar with CSS, CSS stands for Cascading Style Sheets, and it’s a language used to design and layout HTML pages. During our course we dug into a few properties that have been added relatively recently to CSS. And you may have noticed at a couple of points we had to set those properties multiple times.

Helen put it best when she said that CSS is, in a lot of ways, a list of suggestions and standards browser vendors can implement in their products. However, vendors are not required to implement every CSS feature. Vendors are also free to branch off and add their own properties as well. Anyone who’s done web development knows how challenging it can be dealing with different browsers and different implementations.

Vendors often implement properties that aren’t part of the CSS standard. Sometimes this done as a sort of beta test, and sometimes this is done because the vendor doesn’t want to wait until the standard is finalized. Because the feature may be implemented later, or the standard may change when finalized, vendors want to avoid using a name that could mean something later. This is where vendor prefixes come into play.

Vendor prefixes are unique to each browser manufacturer. They are added to the beginning of the property names to create unique names for that vendor. What’s nice about this convention is it means if the property is added to CSS you don’t have to worry about that property meaning different things on different browsers. Each vendor has their own prefix: ms for Microsoft, moz for Mozilla, etc.

The problem, however, is different vendors may all be implementing the same property with their vendor prefix. In order to ensure your page renders properly in every browser you need to set the property for every vendor.

Or, in other words, you need to set the same attribute multiple times.

Now, if you’re anything like me, and I know I am, you probably don’t want to have to remember which properties have vendor prefixes, and you also don’t want to set each one of them by hand. This is where Visual Studio comes to the rescue.

You’re probably already familiar with IntelliSense, which extends into CSS. As you type CSS properties, Visual Studio shows you the available options. When you type a property, like user-select, that has vendor prefixes, Visual Studio is there to help. Note the icon on the left that looks a little like a piece of paper and a pair of scissors. In Visual Studio that indicates a code snippet.

VisualStudioCSSIntelliSense

Whenever you see a code snippet, the shortcut key to have Visual Studio complete it for you is hitting tab twice, or “tab tab” as I always say.

VisualStudioCSSIntelliSenseUserSelect

You’ll notice after that shortcut key combo Visual Studio has done part of the work for you by adding in the vendor prefixes and the property. At this point you might be thinking, “OK, well now I need to set all of those properties by hand.” Once again, code snippets to the rescue. I’m going to disable user selection by setting the option to “none”. When I do this I simply start typing, as the first “inherit” is already highlighted and ready to be overwritten.

VisualStudioCSSIntelliSenseUserSelectOption

Once I type “none”, I simply press Enter. Visual Studio updates all of the other properties for me.

VisualStudioCSSIntelliSenseUserSelectCompleted

And now I can easily ensure my CSS properties are going to apply to all browsers, and ensure backwards compatibility.

There is one small problem, however. As I said earlier, vendors are free to implement properties as they see fit. As a result, the values may mean different things on different browsers. Some additional research may be required as you venture into vendor prefixed properties.

Vendor prefixes can be a bit bewildering. Fortunately, Visual Studio offers great support through IntelliSense and code snippets to make things easier to manage. And if you’re looking to dig more into CSS, Helen and I are here to help with our MVA.

Thursday, October 23, 2014

Programming with Python? Open Source? Microsoft? Did I miss something?

In a word: yes.

I recently recorded Introduction to Programming with Python with Susan Ibach. During the session, toasters became a bit of a running gag, so there was a picture of me on set holding a toaster. When I posed the picture to Facebook a friend of mine asked me the question that inspired the title of this post: “Open Source? Microsoft? Did I miss something?”

You don’t have to look any further than at ASP.NET to see that things have changed. ASP.NET is being developed with both internal developers and in collaboration with a community of open source developers. You can access the source code and contribute at GitHub. And when you glance at the page you’ll notice it even includes instructions on how to use OS X and Linux if you don’t want to use Windows.

Visual Studio now has editors for many open source technologies. If you’re a PHP developer, there are tools for you. Using node.js? There are tools available. Python? We’ve got you covered. And you’ll even notice the last two projects are hosted on CodePlex and are open source.

And the product that’s nearest and dearest to my heart, Microsoft Virtual Academy, is also joining the open source fun. Recently we had a handful of luminaries come through the studio to be interviewed about Microsoft and open source. While I think the entire video is worth watching, I’d suggest watching modules 4 and 5. Module 5 is an interview with Scott Hunter who talks about how ASP.NET found itself being open sourced. And module 4 is an interview with Cliff Allen, a senior attorney at Microsoft who focuses on open source support for many teams within Microsoft.

Then, as mentioned above, there’s the course Susan and I created on Python, which will be available on demand by October 8th.

On October 15th we’ll be live streaming a course titled Building Apps with node.js, hosted by Stacey Mulcahy and Rami Sayar (available on demand about two weeks later).

And in December we have Stacey scheduled to return to the studio with Jamie Kosoy to do a full day on PHP.

Oh, and all of those technologies are fully supported on Azure.

It’s a different world.

So if you’re wondering if you’ve missed something, the answer is a resounding “yes”. I hope you can join us for the ride. It’s going to be a blast!

Tuesday, October 15, 2013

SignalR - Part 3 - Hello, Client

If you’re just joining us, we’re in the process of creating a messaging app with SignalR. Over the next series of posts we want to be able to allow users to message to different groups, create a UI that will highlight new messages, and even store those in a database.

But we’re walking before we run, and right now we’re just implementing a “Send All” functionality. You submit a message and we’re going to send it to everyone connected.

In our previous post, Hello, Server, we examined the server side of our little app. Now it’s time to turn our attention to the client. We’re using MVC, so I’m going to need a controller and a view.

We started with a blank MVC project[1] in VS Web Express[2]. I’m going to add on a simple HomeController and have it return the basic Index view.[4]

public class HomeController : Controller

{

   public ActionResult Index()

   {

         return View();

   }

}

I’m going to create the view. I’m going to empty it out and add in an unordered list, a textbox and a button[4].

<ul id="messages">

 

</ul>

 

Message:

<input type="text" id="new-message" value="" />

<button type="button" id="send-message">Send!</button>

To make life easier, I’m adding in the jQueryUI NuGet package. jQueryUI will include jQuery and make it easier to grab my items and add on the cool effects I’m going to want. Just do a search for jQueryUI and grab the first package. And drag and drop out the CSS and scripts mentioned below.

image_thumb[1]

<link href="~/Content/themes/base/minified/jquery-ui.min.css"

                     rel="stylesheet" />

<script src="~/Scripts/jquery-1.6.4.min.js"></script>

<script src="~/Scripts/jquery-ui-1.10.3.min.js"></script>

For SignalR we need two scripts. The first is the generic SignalR script file. The second is the dynamic SignalR script that will contain all of our methods from our hub. That’s the script file that’s mentioned at the bottom of the readme.txt file. Don’t forget that reference or you’ll wind up getting null and unknown errors. Yes, I speak from experience.

<script src="~/Scripts/jquery.signalR-1.1.3.min.js"></script>

<script src="~/signalr/hubs"></script>

Now on to the code. We need to do two things. First, we need to create the function in JavaScript for the server to call. If you remember from our previous post we called it UpdateMessages and it took a single string parameter. Second, we need to call the method on the server.

First up, creating the method the client can call.

<script>

   $(function() {

      var hub = $.connection.messageHub;

 

      // Create the method on the client

      // that can be called from the server

      hub.client.updateMessages = function (message) {

         var item = "<li>" + message + "</li>";

         $("#messages").append(item);

      };

 

      // more code to come

   });

</script>

The first line of code is the jQuery shortcut for document.ready. That will execute once everything on the page is loaded. The second line is where we get into SignalR. The connection object will give us access to the SignalR connection. Off that object we can access our hub using the exact same name we called it when we created the class, with camel casing.

The next block is where we register the function. You’ll notice we use the client property, which gives us access to the client side of the hub, which is what we use to register the method. You’ll also see we named our method updateMessages using the JavaScript convention of camel casing. This goes back to one of the little things that SignalR does for us – it automatically handles casing. We can code using the casing convention of the environment we’re in.

The signature for the function is exactly what is on the method in our hub – one parameter. The name doesn’t matter, but I like consistency. So we’ll call it message. From there it’s just normal jQuery. Grab the text, put <li> tags around it, and append it to our list of messages.

And that’s the big thing I again want to highlight. We’re free to focus in on what we need to implement on the client, not what needs to be done just to send messages back and forth. We only have two lines of code above that are SignalR focused. The rest is our real implementation.

Now let’s send a message up to the client.

// Wait for the connection to be made

$.connection.hub.start().done(function() {

 

   // Create a click event handler to send the message

   $("#send-message").click(function () {

      var message = $("#new-message").val();

      hub.server.sendNewMessage(message);

      $("#new-message").val("");

   });

});

The above code was placed where I had the “more code to come” comment.

Let’s break this down. The first thing we’re doing is making sure the connection to the server has been made. We don’t want someone clicking on the button and getting an error just because we haven’t connected to the server yet.

The next line is again using jQuery, this time registering the click event and then grabbing the value from the textbox.

Finally, we’re back to SignalR. You’ll notice we’re calling the server property of the hub and accessing the sendMessage function. I know I’m sounding like a broken record[5], but we only have two lines of SignalR code. The rest is jQuery. The rest is just our implementation.

Now we’re ready to test! Ctl-F5 to launch it and we get our basic textbox. We type in a message, hit submit, and we see our new message in the list.

image

And that’s it! We now have our Hello World SignalR application, from client to server.

There’s still more work to be done.

But for right now, let’s just enjoy the fact that with just a bit of client and server code we have a pretty slick little application.

Source code:

---------

[1] I like the templates that are built in. But right now I just want to keep things simple.
[2] I’m using that simply because that’s what installed on my Surface. Plus, it’s a nice way to show I’m not using anything special.
[3] I’m using the HomeController and the Index action simply because it’s the default route. This isn’t an MVC blog post. :-)
[4] Yes, I’m not putting in any html or other tags. Again, I’m trying to keep this as clean as possible.
[5] Or a scratched CD if you don’t remember records. I have no MP3 equivalency.

Monday, October 14, 2013

SignalR - Part 2 - Hello, Server

In my previous blog post, I discussed the concepts of SignalR and why you should be interested as a developer. Hopefully I sold you. But if I didn’t, I think getting in and writing some code will help.

Here’s the basic scenario, and sort of our “SignalR 101” demo. I want a simple chat application for a site. I want to create a form and allow someone to broadcast a message to everyone else connected to the page.

In addition, I’d like to store that information in a database so people can see the most recent 10 messages. And, while we’re at it, I’d like to make sure the UI highlights new messages.

But let’s walk before we run. Let’s start by broadcasting messages to all connected users. And right now I just want to get the server side (or hub) set up and ready to go.

First step – get SignalR. SignalR is available as a NuGet package. So just fire up the NuGet manager and search for SignalR. You’ll just need the first package.

image

The result is one of the main reasons to use NuGet. First, you’ll notice it grabs all the prerequisites for us. Second, it opens a text file with the next steps.

The first step that’s called out is to add a line of code to our global.asax file. This little line will find all of our SignalR hubs and make them available. That one little line will also generate a dynamic bit of JavaScript for us that contains the JavaScript methods for the client to use. The readme.txt file calls out the reference that needs to be made to that dynamic file.

Long story short, we need to do what the readme.txt file says. Since we’re just focused on the server side right now, we’re just going to make our global.asax file look like this:

protected void Application_Start()

{

   // Register the default hubs route: ~/signalr

   RouteTable.Routes.MapHubs();

   // normal code below

}

And that’s it. That’s the server configuration part. That’s everything that needs to be done for the automatic step down that I talked about in the previous blog post. And we can turn our attention to making our actual implementation.

Let’s create our hub first. You can see it listed below.

using Microsoft.AspNet.SignalR;

using System;

 

namespace SignalRBlog.Hubs

{

   public class MessageHub : Hub

   {

      public void SendNewMessage(String message)

      {

         Clients.All.UpdateMessages(message);

      }

   }

}

Take a look at it. Notice if there’s anything special. I’ll give you a hint – there really isn’t. Well, one thing. But on the whole there isn’t.

And that’s the beauty of SignalR. I create the code I need to create, focus on the features I need to implement, and let SignalR take care of the details.

Let’s break things down. First you’ll notice the inheritance. The Hub class is inside the Microsoft.AspNet.SignalR namespace and is the base for all hubs. That is what the register method will focus in on when registering our hubs, and it’s what makes the Clients object (and a few others) available.

Second, you’ll notice the basic SendNewMessage method. Nothing fancy there. Just a public method, taking a String parameter, and returning void. Programming 101.

And finally we get to the real SignalR code – the Clients object. The Clients object gives us access to everyone that’s currently connected. As we’ll see in later blog posts we can use that object to target certain sets of users. But for right now we want to broadcast our message to everyone. The property of Clients that will give us all users is imaginatively named All.

All is a dynamic object. It does represent all users and allows me to call a method on all users. But it’s a dynamic object. Here’s the thing – SignalR doesn’t know what methods we may want to call or what it is we’re going to want to be able to do. As a result it uses a dynamic object which allows us to add on the methods we’re going to need on the fly. At a later point we’ll have to register that method on the client, but that’s the next blog post.

So, here’s what we’ve got. We’ve added SignalR to our project. We’ve added the call to our global.asax file to register the dynamic JavaScript that’s needed. And we created our hub with our first method that can be called from the client. What’s next? Well, to create the client! And that’s the next blog post.

Thursday, October 10, 2013

SignalR - Part 1 - The Introduction

Recently I had the pleasure of presenting the MVC 4 Jump Start with Jon Galloway. It was an awesome experience, we covered a lot of great content, and every demo worked... Until the very end.

Now, as a quick side note, I must say I was impressed that everything worked up until that point. We were doing all of the demos live, and coding without a safety net with over 3,000 people watching was a real rush. And to only have one demo go sideways? I’ll certainly take that. And I was able to get it fixed before we went off the air.

But I’d like to try to take a bit of time and go back through the demo and discuss how SignalR works and what it can do for you. There’s a fair amount of ground that I’d like to cover, and I’m going to break this into smaller, bite-sized chunks so you can skip to the section(s) that interest you most.

Let’s get started with the problem statement and how SignalR, behind the scenes, simplifies the development process.

One thing we as web developers have long wanted to do is be able to send messages down to the client browser. As applications have become more robust and closer to replacing full-blown desktop applications the need for two-way communications has become even greater. But, unfortunately, the options that we’ve had available to us have been a bit of a mixed bag.

The first option that we have is to use polling. Create a block of JavaScript that has a delay timer to ping the server and ask if there are any new messages. This is the programming equivalent of the 4-year old in the back of the car asking, “are we there yet? are we there yet? are we there yet?” Not ideal.

Another possible option is to create an invisible iframe to use a chunked block, sometimes known as a forever frame. This will allow the server to periodically send down JavaScript to the client, which the client will then execute. Again, not ideal.

If we’re looking for true server to client communication we have Server-Sent Events. Originally added to Opera, Server-Sent Events has been made part of the HTML5 specification. It uses HTTP and allows the server to send messages to the client. However, while most other browsers support Server-Sent Events, Internet Explorer does not. So, again, not ideal.

And finally we have WebSockets. While WebSockets uses port 80 and 443, it is a separate protocol from HTTP. It allows for two-way communication in a similar fashion to a network socket that you may have used in the past. The problem with WebSockets is while they’re supported by most modern browsers, older browsers don’t have support. Plus, programming WebSockets is similar to doing socket programming, which isn’t really my favorite style.

So, here’s what we’ve got – four possible solutions for two way communication. We’d like to use WebSockets, but we can’t guarantee the browser will work with them. Failing that, we’d like to use Server-Sent Events, then forever frames, and finally polling. But, I’ve got better things to do with my time than to not only figure out which the browser supports but to create the required code implementations.

While we’re at it, even if I was guaranteed the ability to use WebSockets, I don’t much enjoy programming against them.

With WebSockets I have essentially one method that I can call to send a signal to the server, and one method that I can call to send a signal to the client. It’s up to me on each side to determine the type of message that’s been sent, and to handle the serialization to and from JSON or text. If there’s two different messages I need to be able to send to the client, maybe a “NewComment” and “EditedComment” signal, I need to add the logic to detect the message type, and then act upon the payload that was sent with the rest of the message.

This is where the beauty of SignalR is revealed.

For starters, SignalR will handle the step-back in messaging types automatically for me. It’ll try WebSockets, and then fail back to Server-Sent Events, and then forever frames, and then, if it must, long polling. This way I don’t need to figure out which the browser supports and, more importantly, include the code for each of the methodologies. SignalR does it for me.

Secondly, and I think this is the coolest part, SignalR allows me to create methods on the client that are callable from the server, and, in turn, methods on the server that are callable from the client. Essentially, on each side, I just create normal methods and then call them from the opposite side. So, in my scenario of “NewComment” and “EditedComment” I’d just implement two JavaScript methods named newComment and editedComment, and on the server call those as if they were local to the server. SignalR will handle the communication (and differences in casing) automatically for me.

Or, to put it even more simply, SignalR makes it very easy for me to implement that two way client-server communication we as developers have been craving for years. I don’t need to focus dirty work that needs to be done behind the scenes, I just focus on the implementation and what I’m trying to accomplish.

There’s how SignalR works behind the scenes and what it’s going to do for us. Next up? Let’s get the server side up and running!