<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Dan Wahlin</title><link>https://weblogs.asp.net:443/dwahlin/</link><description>AngularJS, JavaScript, HTML5, jQuery, Node.js, ASP.NET, C#, XAML</description><item><title>Moving Blog to https://blog.codewithdan.com</title><link>https://weblogs.asp.net:443/dwahlin/moving-blog-to-http-blog-codewithdan-com</link><description>&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Moving-Blog-to-httpblog.codewithdan.com_D57E/image_2.png"&gt;&lt;img width="241" height="152" title="image" align="left" style="margin: 0px 25px 25px 0px; border: 0px currentcolor; display: inline; float: right; background-image: none;" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Moving-Blog-to-httpblog.codewithdan.com_D57E/image_thumb.png" border="0" /&gt;&lt;/a&gt;After many years hosting my blog at &lt;a href="https://weblogs.asp.net/dwahlin"&gt;https://weblogs.asp.net/dwahlin&lt;/a&gt; I&amp;rsquo;ve decided to move over to a custom domain - &lt;a href="https://blog.codewithdan.com"&gt;https://blog.codewithdan.com&lt;/a&gt;. I&amp;rsquo;ve really appreciated the hosting that Microsoft has provided and the excellent service behind the scenes by Neudesic. The existing blog and all of the posts will stay up but new posts will be at the URL mentioned below.&lt;/p&gt;
&lt;p&gt;Why am I moving the blog you ask? First off, people have a real challenge spelling my last name (&amp;ldquo;Wahlin&amp;rdquo;) and it&amp;rsquo;s hard to remember &amp;ldquo;dwahlin&amp;rdquo; if you&amp;rsquo;re trying to go to the blog directly. Second, our new company website is going to be at &lt;a href="https://www.codewithdan.com"&gt;https://www.codewithdan.com&lt;/a&gt; so I figured I might as well move the blog there as well. The company site will be released a bit later and we have a lot of great content planned for it. My wife came up with the &amp;ldquo;Code with Dan&amp;rdquo; concept based on feedback we&amp;rsquo;ve had from several clients over the years and felt that it&amp;rsquo;d be a lot easier to remember for people.&lt;/p&gt;
&lt;p&gt;I may still post a portion of each blog post here at the old blog to gradually move people over, but if you have this blog (&lt;a href="https://weblogs.asp.net/dwahlin"&gt;https://weblogs.asp.net/dwahlin&lt;/a&gt;) bookmarked you&amp;rsquo;ll want to change the bookmark to &lt;a href="https://blog.codewithdan.com"&gt;https://blog.codewithdan.com&lt;/a&gt;. Thanks!&lt;/p&gt;</description><pubDate>Mon, 04 Apr 2016 09:00:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/moving-blog-to-http-blog-codewithdan-com</guid><category>blog</category></item><item><title>New Pluralsight Course: Docker for Web Developers</title><link>https://weblogs.asp.net:443/dwahlin/new-pluralsight-course-docker-for-web-developers</link><description>
&lt;h2&gt;How I Got Into Docker (and why you should too)&lt;/h2&gt;
&lt;p&gt;One of the most exciting technologies that I’ve researched and used over the past year is &lt;a href="http://www.docker.com" target="_blank"&gt;Docker&lt;/a&gt;. That’s a pretty bold statement, especially since I enjoy working with a lot of different technologies, so let me share a quick story about how I initially got started with Docker and and my personal journey (if you’d prefer you can &lt;a href="https://www.pluralsight.com/courses/docker-web-development" target="_blank"&gt;jump directly to the Docker for Web Developers Course&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;You may have heard the term “Docker”&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/docker-logo-240_4.png"&gt;&lt;img width="240" height="203" title="docker-logo-240" align="right" style="margin: 12px 0px 0px 12px; border-image: none; float: right; display: inline; background-image: none;" alt="docker-logo-240" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/docker-logo-240_thumb_1.png" border="0"&gt;&lt;/a&gt; tossed around at work or online and wondered what it was…I know I did. I heard a few people mention it on Twitter a few years ago making claims like, “Docker provides a consistent way to deploy applications.” That sounded appealing but wasn’t enough to make me jump into it. I’ve worked in a lot of dev environments over the course of my career and have certainly run into challenges moving software between development, staging and production &lt;/p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/docker-logo-240_4.png"&gt;&lt;br&gt;&lt;/a&gt;&lt;p&gt;environments so the general promise of Docker certainly intrigued me. But, when it came down to it I only had so many hours in the day to research new technologies so I pushed it off. It kept coming up again and again though so I realized I needed to make some time to look into it more.&lt;/p&gt;
&lt;p&gt;Fast-forward a few more weeks and one night I decided to visit the &lt;a href="http://www.docker.com" target="_blank"&gt;Docker website&lt;/a&gt; and do a little reading on the features it offered. The additional features I learned about continued to interest me but at the time I felt like Docker was aimed squarely at SysAdmins which wasn’t that exciting to me - no offense to my SysAdmin friends. :-) It was also 100% Linux-based when it first came out and I wasn’t a “Linux guy” back then. I was super comfortable with Mac and Windows but “Linux” just wasn’t my thing. I put off looking into it more but decided to sign-up for the &lt;a href="https://www.docker.com/newsletter-subscription" target="_blank"&gt;Docker Newsletter&lt;/a&gt; just to keep an eye on it and see if anything interesting showed up. I read a lot of great articles that listed some of the key features:&lt;br&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerFeatures_7.png"&gt;&lt;img width="691" height="248" title="dockerFeatures" style="border: 0px currentcolor; border-image: none; display: inline; background-image: none;" alt="dockerFeatures" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerFeatures_thumb_2.png" border="0"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;As I dug in deeper I learned that Docker allows “Images” published up on &lt;a href="https://hub.docker.com/" target="_blank"&gt;Docker Hub&lt;/a&gt; to be used to create instances of running “Containers”. An image is a super efficient way to get a given framework (Node.js, ASP.NET Core, PHP, etc.), database servers, caching servers and much more up and running on your dev machine or even in production. What’s so cool about the Docker technology is that “Images” aren’t the same thing as the “Virtual Machine Images” you may have used before. In fact, Docker Images are very different from Virtual Machine Images as they’re typically smaller and more efficient to start and stop. A Docker Image isn’t a full OS as with Virtual Machines – it’s a layer that’s added onto a host OS so there are a lot of benefits that Docker Images bring to the table.&amp;nbsp; I’ll save that discussion for another post though. In the meantime, here’s a quick summation of Docker Images and Containers for you:&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerImagesContainers_2.png"&gt;&lt;img width="619" height="333" title="dockerImagesContainers" style="border: 0px currentcolor; border-image: none; display: inline; background-image: none;" alt="dockerImagesContainers" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerImagesContainers_thumb.png" border="0"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;This still sounds/looks rather SysAdmin-ish though right? That’s what I thought initially too. Let’s get to the good stuff that can impact you and your development projects.&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;How Docker Can Help Web Developers (and many others)&lt;/h2&gt;
&lt;p&gt;One day I saw an article in the &lt;a href="https://www.docker.com/newsletter-subscription" target="_blank"&gt;Docker Newsletter&lt;/a&gt; that focused on a few key benefits that Docker offered to web developers. After reading it and thinking it over more I had one of those “light bulb moments” and thought, “Hey, this technology can be used to setup a consistent development environment quickly and easily! How cool is that?” What do I mean by that exactly?&lt;/p&gt;
&lt;p&gt;Let’s say that you need to get Node.js, MongoDB, nginx, Redis and possibly more up and running on your dev machine. In addition to getting these requirements all installed properly, you also have to worry about getting security, configuration and more in place. To top it off, everyone on your team needs to do the same thing on their machines. Do you all have the correct versions of the servers and frameworks installed? What happens in a month or two when a new version comes out for a server/framework that everyone decides to move to? Is it easy to move to the new version? Did everyone configure security the same? How many hours have you (or your team) spent getting a development environment like that up and running correctly (and consistently) for a particular project? When a new developer or contractor comes onboard how quickly can they get to work? Whew – that’s way too many questions to ask and way too much work to do before you even write a single line of code (and yes…I realize there are many ways to automate some of this but rather than digressing I’ll stay focused on Docker here).&lt;/p&gt;
&lt;p&gt;I’ve wasted more time than I care to admit in some cases setting up my dev environment for projects. The good news is that Docker can greatly simplify the process of creating a consistent development environment across multiple team members, remote workers, contractors and more. And – it can do it quickly! There are certainly other benefits as well. When I’m ready to move to staging or production I can move the exact environment (via Docker Images) and feel confident that the application is going to run the same in the other environments.&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerDeveloperFeatures_2.png"&gt;&lt;img width="690" height="336" title="dockerDeveloperFeatures" style="border: 0px currentcolor; border-image: none; display: inline; background-image: none;" alt="dockerDeveloperFeatures" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerDeveloperFeatures_thumb.png" border="0"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;Once I realized that Docker wasn’t just for SysAdmins (which is certainly an important role as well) and could play a huge role for developers I jumped in head first and have never looked back. Sure, there was a learning curve (after all – I did have to learn some Linux fundamentals) but I’ve quite honestly enjoyed the process every step of the way, appreciate the &lt;a href="https://docs.docker.com/" target="_blank"&gt;documentation&lt;/a&gt; that the Docker website offers and enjoy working with the &lt;a href="https://www.docker.com/products/docker-toolbox" target="_blank"&gt;tools&lt;/a&gt; provided by Docker such as &lt;strong&gt;Docker Machine&lt;/strong&gt;, &lt;strong&gt;Docker Client&lt;/strong&gt; and especially &lt;strong&gt;Docker Compose&lt;/strong&gt;. I’ll be writing some posts in the near future about these tools and how they can be used so stay tuned. Follow me on Twitter at &lt;a href="http://twitter.com/danwahlin" target="_blank"&gt;@DanWahlin&lt;/a&gt; if you’re interested in hearing about the latest posts.&lt;/p&gt;
&lt;p&gt;And that brings us to the new course that I just released…&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;The New Pluralsight Course: Docker for Web Developers&lt;/h2&gt;
&lt;p&gt;I’ve been using Docker for quite awhile now and am still super excited about the benefits it offers software developers. In fact, I was so excited about the features that I decided to create a full video course on &lt;a href="https://www.pluralsight.com/courses/docker-web-development" target="_blank"&gt;Pluralsight.com&lt;/a&gt; which was recently released. The course has over 5 hours of in-depth information about why and how you’d use Docker in your Web development environment. Here’s a small sampling of some of the topics covered:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Why use Docker as a Developer?&lt;/li&gt;
&lt;li&gt;The difference between Docker Images and Virtual Machines&lt;/li&gt;
&lt;li&gt;Installing Docker Toolbox on Mac and Windows&lt;/li&gt;
&lt;li&gt;The role of Docker Hub for pulling images&lt;/li&gt;
&lt;li&gt;Getting started quickly and easily with the Kitematic Tool&lt;/li&gt;
&lt;li&gt;Using Docker Machine to work with Linux on Mac and Windows&lt;/li&gt;
&lt;li&gt;Key Docker Machine and Docker Client commands&lt;/li&gt;
&lt;li&gt;How do you hook your source code into Docker?&lt;/li&gt;
&lt;li&gt;How do you build custom Docker images?&lt;/li&gt;
&lt;li&gt;How do multiple containers talk to each other at runtime?&lt;/li&gt;
&lt;li&gt;Bring up a complete development environment with Docker Compose&lt;/li&gt;
&lt;li&gt;Push custom images to Docker Hub&lt;/li&gt;
&lt;li&gt;Using Docker Cloud to deploy your images/containers to a cloud provider&lt;/li&gt;
&lt;li&gt;Much more!&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here’s the official course table of contents…&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;Docker for Web Developers Video Course Outline&lt;/h2&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerCourseBanner_2.png"&gt;&lt;img width="859" height="179" title="dockerCourseBanner" style="border: 0px currentcolor; border-image: none; display: inline; background-image: none;" alt="dockerCourseBanner" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/New-Pluralsight-Course-Docker-for-Web-De_10BEB/dockerCourseBanner_thumb.png" border="0"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Docker's open app-building platform can give any web developer a boost in productivity. You'll learn how to use the Docker toolbox, how to work with images and containers, how to get your project running in the cloud, and more. &lt;a href="https://www.pluralsight.com/courses/docker-web-development" target="_blank"&gt;View the course here.&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Course Overview&lt;/li&gt;
&lt;li&gt;Why Use Docker as a Developer?&lt;/li&gt;
&lt;li&gt;Setting Up Your Dev Environment with Docker Toolbox&lt;/li&gt;
&lt;li&gt;Using Docker Machine and Docker Client&lt;/li&gt;
&lt;li&gt;Hooking Your Source Code into a Container&lt;/li&gt;
&lt;li&gt;Building Custom Images with Dockerfile&lt;/li&gt;
&lt;li&gt;Communicating Between Docker Containers&lt;/li&gt;
&lt;li&gt;Managing Containers with Docker Compose&lt;/li&gt;
&lt;li&gt;Running Your Containers in the Cloud&lt;/li&gt;
&lt;li&gt;Reviewing the Case for Docker&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I put a lot of blood, sweat, tears, late nights, head banging, head scratching, why won’t this s*@? work moments, awesome – it works! moments, joy, excitement and more into the course so I really hope you enjoy it! &lt;a href="https://www.pluralsight.com/courses/docker-web-development" target="_blank"&gt;Get to the full course here!&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;Win Free Pluralsight Access!&lt;/h2&gt;
&lt;p&gt;Wait….you don’t have a &lt;a href="https://www.pluralsight.com/courses/docker-web-development" target="_blank"&gt;Pluralsight&lt;/a&gt; subscription and are totally bummed because you can’t view the course? Well, the good news is that I’ll be giving away a bunch of 30 day subscriptions and even a free year subscription to one lucky winner try to help you out. If you’d like to enter the contest choose one (or both for a better chance of winning) of the following options.&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Option 1:&lt;/strong&gt; Follow me on Twitter at &lt;a href="https://twitter.com/danwahlin" target="_blank"&gt;@DanWahlin&lt;/a&gt; and sign-up for the &lt;strong&gt;Code with Dan Newsletter&lt;/strong&gt; below (there's a lot of great content in the newsletter!).&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Option 2:&lt;/strong&gt; Follow me on Twitter at &lt;a href="https://twitter.com/danwahlin" target="_blank"&gt;@DanWahlin&lt;/a&gt; and Tweet about the contest to your followers (click the button below to send the official Tweet):&lt;/p&gt;
&lt;p&gt;&lt;a class="twitter-share-button" href="https://twitter.com/share" data-dnt="true" data-size="large" data-text="RT for a chance to win free access to @DanWahlin's Docker for Web Developers course on @Pluralsight. #dockerdev" data-url="http://ow.ly/10dgHn"&gt;Tweet&lt;/a&gt;&lt;/p&gt;
&lt;script&gt;// &lt;![CDATA[
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
// ]]&gt;&lt;/script&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;p&gt;If you win I'll direct message you with details on claiming your prize (assuming you followed me as mentioned above). I’ll be randomly selecting Pluralsight subscription winners who subscribe to the newsletter and/or tweet the message above as well so feel free to do both to increase your odds. Good luck!&lt;/p&gt;</description><pubDate>Sun, 03 Apr 2016 21:23:15 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/new-pluralsight-course-docker-for-web-developers</guid><category>cloud</category><category>containers</category><category>docker</category><category>docker-compose</category><category>docker-machine</category><category>images</category><category>pluralsight</category><category>programming</category><category>webdevelopment</category></item><item><title>Video: Modern Web Development Interview with Channel 9</title><link>https://weblogs.asp.net:443/dwahlin/video-modern-web-development-interview-with-channel-9</link><description>&lt;p&gt;I had the privilege to sit down with &lt;a href="http://twitter.com/sethjuarez" target="_blank"&gt;Seth Juarez&lt;/a&gt; from &lt;a href="https://channel9.msdn.com/Events/Seth-on-the-Road" target="_blank"&gt;Channel 9&lt;/a&gt; at the &lt;a href="http://anglebrackets.org" target="_blank"&gt;AngleBrackets&lt;/a&gt; conference in Las Vegas (fall 2015) and talk about modern web development and the main technologies that drive it. We talked about a lot of different topics ranging from TypeScript, Angular and Aurelia on the client-side to Node.js and ASP.NET 5 on the server-side. Seth’s a great interview host (and a super cool guy to hang out with) and I really enjoyed talking with him about modern technology in today’s world. Check out the interview below.&lt;br&gt;&lt;/p&gt; &lt;h1&gt;Modern Web Development with Seth Juarez and Dan Wahlin&lt;/h1&gt;&lt;br&gt;&lt;iframe height="450" src="https://channel9.msdn.com/Events/Seth-on-the-Road/DevIntersection-2015/Modern-Web-Development-with-Dan-Wahlin/player?format=html5" frameborder="0" width="800" allowfullscreen&gt;&lt;/iframe&gt;</description><pubDate>Fri, 15 Jan 2016 04:19:26 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/video-modern-web-development-interview-with-channel-9</guid><category>JavaScript</category><category>TypeScript</category><category>Angular</category><category>Aurelia</category><category>Node.js</category><category>ASP.NET MVC</category></item><item><title>Getting Started with ES6 - Using Classes</title><link>https://weblogs.asp.net:443/dwahlin/getting-started-with-es6-using-classes</link><description>&lt;p&gt;In a &lt;a href="http://weblogs.asp.net/dwahlin/getting-started-with-es6-&amp;ndash;-transpiling-es6-to-es5" target="_blank"&gt;previous post&lt;/a&gt; I introduced how ES6 can be transpiled to ES5 using Traceur or Babel. By using transpilers you can write&amp;ldquo;modern&amp;rdquo; code and leverage features found in ES6 today while still allowing the code to run in older browsers. In this post I&amp;rsquo;m going to dive into classes which is one of the shiny new features found in ES6.&lt;/p&gt;
&lt;h1&gt;Getting Started with ES6/ES2015 Classes&lt;/h1&gt;
&lt;p&gt;Classes are the subject of much debate in the JavaScript world with some people loving them and others hating them. I&amp;rsquo;ve never believed in one world view being right for every situation and think that classes definitely have their place. If nothing else they&amp;rsquo;re worth exploring so that you understand the different options provided by ES6. If you want to continue with the more traditional &amp;ldquo;functional programming&amp;rdquo; techniques available in JavaScript it&amp;rsquo;s important to note that you can still do that. Classes are an option provided by ES6 but certainly not required to write ES6 code.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s an example of an ES6 class that defines an automobile:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Auto {
    constructor(data) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.make = data.make;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.model = data.model;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.year = data.year;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.price = data.price;
    }

    getTotal(taxRate) {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.price + (&lt;span class="kwrd"&gt;this&lt;/span&gt;.price * taxRate);
    }

    getDetails() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; `${&lt;span class="kwrd"&gt;this&lt;/span&gt;.year} ${&lt;span class="kwrd"&gt;this&lt;/span&gt;.make} ${&lt;span class="kwrd"&gt;this&lt;/span&gt;.model}`;
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If you&amp;rsquo;ve worked with languages such as Java, C# or others that support classes the general syntax will probably look familiar. You can see that the &lt;strong&gt;class&lt;/strong&gt; keyword is used to define a container named &lt;strong&gt;Auto&lt;/strong&gt;. The class contains a &lt;strong&gt;constructor&lt;/strong&gt; that is called when the class is created using the &lt;strong&gt;new&lt;/strong&gt; keyword (more on &amp;ldquo;new&amp;rdquo; later). The constructor provides a place where you can initialize properties with values. In the &lt;strong&gt;Auto&lt;/strong&gt; class example above a &lt;strong&gt;data&lt;/strong&gt; object is passed into the constructor and its properties are associated with the &lt;strong&gt;make&lt;/strong&gt;, &lt;strong&gt;model&lt;/strong&gt;, &lt;strong&gt;year&lt;/strong&gt; and &lt;strong&gt;price&lt;/strong&gt; properties.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;Auto&lt;/strong&gt; class also defines two functions named &lt;strong&gt;getTotal()&lt;/strong&gt; and &lt;strong&gt;getDetails()&lt;/strong&gt; as well. You&amp;rsquo;ll quickly notice that the &lt;strong&gt;function&lt;/strong&gt; keyword isn&amp;rsquo;t used to define each function. That&amp;rsquo;s a new feature available in classes (and in others parts of ES6 such as functions in object literals) that provides a nice, compact way to define functions. Within the &lt;strong&gt;getDetails()&lt;/strong&gt; function you&amp;rsquo;ll also notice another new feature in ES6 &amp;ndash; template strings. I&amp;rsquo;ll provide additional details about this feature in a future post.&lt;/p&gt;
&lt;p&gt;The class code shown above is referred to as a &amp;ldquo;class definition&amp;rdquo;. Classes can also be defined using a &amp;ldquo;class expression&amp;rdquo; syntax as well. An example of a class expression is show next:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;let Automobile = &lt;span class="kwrd"&gt;class&lt;/span&gt; {
    constructor(data) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.make = data.make;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.model = data.model;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.year = data.year;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.price = data.price;
    }

    getDetails() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; `${&lt;span class="kwrd"&gt;this&lt;/span&gt;.year} ${&lt;span class="kwrd"&gt;this&lt;/span&gt;.make} ${&lt;span class="kwrd"&gt;this&lt;/span&gt;.model}`;
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;Automobile&lt;/strong&gt; variable in this example is assigned to a class expression that has a constructor and a &lt;strong&gt;getDetails() &lt;/strong&gt;function. The &lt;strong&gt;let&lt;/strong&gt; keyword used in this example creates a local scoped variable. If you put this code inside a block such as an &lt;strong&gt;if&lt;/strong&gt; statement or &lt;strong&gt;for&lt;/strong&gt; loop the variable&amp;rsquo;s scope will be limited to the block. That&amp;rsquo;s another new (and very welcome) feature provided by ES6.&lt;/p&gt;
&lt;p&gt;ES6 classes can also contain property get and set blocks if desired. This is done by using&amp;nbsp; the &lt;strong&gt;get &lt;/strong&gt;and &lt;strong&gt;set&lt;/strong&gt; keywords:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; AutoWithProperties {
    constructor(data) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;._make;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;._model;
    }

    get make() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;._make;
    }
    
    set make(val) {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (val) {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;._make = val;
        } &lt;span class="kwrd"&gt;else&lt;/span&gt; {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;._make = &lt;span class="str"&gt;'No Make'&lt;/span&gt;;
        }
    }
    
    get model() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;._model;
    }
    
    set model(val) {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (val) {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;._model = val;
        } &lt;span class="kwrd"&gt;else&lt;/span&gt; {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;._model = &lt;span class="str"&gt;'No Model'&lt;/span&gt;;
        }
        
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;AutoWithProperties&lt;/strong&gt; class defines two properties named &lt;strong&gt;make&lt;/strong&gt; and &lt;strong&gt;model&lt;/strong&gt; that read (the get block) and write (the set block) to and from backing properties named _&lt;strong&gt;make&lt;/strong&gt; and _&lt;strong&gt;model&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h1&gt;Creating an Instance of a Class&lt;/h1&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Once a class is defined you can create an instance using the &lt;strong&gt;new &lt;/strong&gt;keyword. For example, an instance of &lt;strong&gt;Auto&lt;/strong&gt; can be created using the following code:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;let auto = &lt;span class="kwrd"&gt;new&lt;/span&gt; Auto({
   make: &lt;span class="str"&gt;'Chevy'&lt;/span&gt;,
   model: &lt;span class="str"&gt;'Malibu'&lt;/span&gt;,
   price: 30000, 
   year: 2014
});&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;What happens if you try to call the &lt;strong&gt;Auto&lt;/strong&gt; class as a function without using the &lt;strong&gt;new&lt;/strong&gt; keyword? That&amp;rsquo;s one of the limitations of classes in ES6 and something the anti-class crowd will quickly point out as a flaw. Calling a class as a regular function results in the following error:&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bbaa0c1a4e61_8A2E/classError_2.png"&gt;&lt;img title="classError" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="classError" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bbaa0c1a4e61_8A2E/classError_thumb.png" width="654" height="36" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This limitation is problematic when using a &amp;ldquo;functional programming&amp;rdquo; approach and definitely something to consider before choosing to use classes.&lt;/p&gt;
&lt;p&gt;Classes also aren&amp;rsquo;t hoisted like regular JavaScript functions. If you try to &amp;ldquo;new up&amp;rdquo; a class before the class is defined the class definition won&amp;rsquo;t be hoisted to the top of the code to make that scenario work as with regular JavaScript functions. Instead, you&amp;rsquo;ll get an error saying that the class is not a function. That&amp;rsquo;s another limitation of classes that you should be aware of.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h1&gt;Extending a Class&lt;/h1&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Extending a function in ES5 requires use of the prototype property. ES6 classes still rely on prototype under the covers, but the syntax is much easier to read and understand. To extend a class you can use the &lt;strong&gt;extends&lt;/strong&gt; keyword as shown next:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Car extends Auto {
    constructor(data) {
        super(data);
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.isElectric = data.isElectric;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.isHatchback = data.isHatchback;
    }

    getDetails() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; `${super.getDetails()} Electric: ${&lt;span class="kwrd"&gt;this&lt;/span&gt;.isElectric} Hatchback: ${&lt;span class="kwrd"&gt;this&lt;/span&gt;.isHatchback}`;
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This example defines a new &lt;strong&gt;Car&lt;/strong&gt; class that extends the &lt;strong&gt;Auto&lt;/strong&gt; class. The class&amp;rsquo;s constructor forwards the &lt;strong&gt;data&lt;/strong&gt; parameter to the base class by making a call to &lt;strong&gt;super()&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;It&amp;rsquo;s important to note that a call to &lt;strong&gt;super()&lt;/strong&gt; must be made before properties are initialized using &amp;ldquo;this&amp;rdquo; (if you return Object.create(null) from the constructor then you don&amp;rsquo;t actually have to call super() though).&amp;nbsp; Anytime you extend a class &lt;strong&gt;super()&lt;/strong&gt; must be called even if no data is passed to the base class&amp;rsquo;s constructor. The only exception to this rule is if the base and derived classes do not explicitly define custom constructors. In that case constructors will be implicitly created for both of the classes.&lt;/p&gt;
&lt;p&gt;Here's a fiddle with the Auto and Car code in it that you can play around with:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;iframe width="100%" height="300" src="//jsfiddle.net/dwahlin/o93Lm0rc/embedded/" allowfullscreen="allowfullscreen" frameborder="0"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Classes provide a succinct and clean way to encapsulate code that makes JavaScript feel more &amp;ldquo;object-oriented&amp;rdquo; even though prototypes are still used behind the scenes. They also provide constructors, support properties, allow functions to be defined without using the &lt;strong&gt;function&lt;/strong&gt; keyword and support extension using the &lt;strong&gt;extends&lt;/strong&gt; keyword. Developers coming from languages that support classes will feel right at home using the new class feature in ES6.&lt;/p&gt;
&lt;p&gt;So should you move all of your code to classes as you migrate to ES6? Developers that prefer &amp;ldquo;functional programming&amp;rdquo; will be quick to say NO and avoid them like the plague. Classes don&amp;rsquo;t fit in well with the functional programming approach. If you understand their limitations (having to use new, no hoisting, etc.) then I think they can work well in some applications although it depends on the type of JavaScript code you like to write. I always say, &amp;ldquo;Use the right tool for the right job&amp;rdquo; which means taking the time to learn the ins-and-outs of classes and deciding if their pros outweigh their cons for your target application.&lt;/p&gt;
&lt;p&gt;You can play around with classes by using the fiddle above, by using my ES6 starter project available at &lt;a title="https://github.com/DanWahlin/ES6-Modules-Starter" href="https://github.com/DanWahlin/ES6-Modules-Starter"&gt;https://github.com/DanWahlin/ES6-Modules-Starter&lt;/a&gt; or by visiting the &lt;a href="https://babeljs.io/repl/#?experimental=true&amp;amp;evaluate=true&amp;amp;loose=false&amp;amp;spec=false&amp;amp;code=class%20Auto%20%7B%0A%20%20%0A%7D" target="_blank"&gt;Babel ES6 playground&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Thu, 06 Aug 2015 06:27:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/getting-started-with-es6-using-classes</guid><category>es6</category><category>javascript</category></item><item><title>Video: Building a Single-Page App with Angular, TypeScript, Azure Active Directory and Office 365 APIs</title><link>https://weblogs.asp.net:443/dwahlin/video-building-a-single-page-app-with-angular-typescript-azure-active-directory-and-office-365-apis</link><description>&lt;p&gt;I had the opportunity to speak at the BUILD 2015 conference in San Francisco with my friend &lt;a href="http://www.andrewconnell.com/" target="_blank"&gt;Andrew Connell&lt;/a&gt; and had a great time! We gave a talk on Angular, TypeScript, Azure AD and Office 365 APIs and I also gave two “Express” talks on TypeScript. It was super fun to meet new people and hang out with everyone at the conference. I even had the opportunity to check out the upcoming &lt;a href="http://www.microsoft.com/microsoft-hololens/en-us" target="_blank"&gt;HoloLens&lt;/a&gt; device which was super cool! I was heading up an elevator to a meeting and a member of the HoloLens team approached me and asked if I had some time to do some “HoloLens Testing”. Let’s just say that I was a bit late for my meeting – I wasn’t going to pass up the opportunity to check out HoloLens in person.&lt;/p&gt; &lt;p&gt;Thanks to everyone who came to the talk. We had a great turnout! If you weren’t able to make it (it was tough to get a ticket to BUILD this year) then you can catch the video below.&lt;br&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Building-a-Single-Page-App-Using-Angular_8F86/image_5.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Building-a-Single-Page-App-Using-Angular_8F86/image_thumb_1.png" width="963" height="309"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;We had some microphone challenges for the first minute or so of the talk so it looks like they cut out the introduction but everything else is there if you’re interested in watching the talk. I have no idea why they chose the picture below for the video overlay. I’m apparently saluting Angular and TypeScript (with the wrong hand). &lt;br&gt;&lt;/p&gt; &lt;h2&gt;Building a Single-Page App with Angular, TypeScript, Azure AD and Office 365 APIs&lt;br&gt;&lt;br&gt;&lt;/h2&gt;&lt;iframe height="467" src="//channel9.msdn.com/Events/Build/2015/3-689/player?format=html5" frameborder="0" width="830" allowfullscreen&gt;&lt;/iframe&gt;</description><pubDate>Sun, 03 May 2015 02:18:36 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/video-building-a-single-page-app-with-angular-typescript-azure-active-directory-and-office-365-apis</guid><category>TypeScript</category><category>Angular</category><category>JavaScript</category><category>ES6</category><category>Office365</category></item><item><title>The Role of Interfaces in TypeScript</title><link>https://weblogs.asp.net:443/dwahlin/the-role-of-interfaces-in-typescript</link><description>&lt;p&gt;In my &lt;a href="http://weblogs.asp.net/dwahlin/archive/2013/01/07/extending-classes-and-interfaces-using-typescript.aspx" target="_blank"&gt;last post&lt;/a&gt; I talked about how classes and interfaces could be extended in the TypeScript language. By using TypeScript’s &lt;strong&gt;extends&lt;/strong&gt; keyword you can easily create derived classes that inherit functionality from a base class. You can also use the extends keyword to extend existing interfaces and create new ones. In the previous post I showed an example of an ITruckOptions interface that extends IAutoOptions. An example of the interfaces is shown next:     &lt;br /&gt;&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;interface&lt;/span&gt; IAutoOptions {
    engine: IEngine;
    basePrice: &lt;font color="#0000ff"&gt;number&lt;/font&gt;;
    state: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    make: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    model: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    year: &lt;font color="#0000ff"&gt;number&lt;/font&gt;;
}

&lt;span class="kwrd"&gt;interface&lt;/span&gt; ITruckOptions &lt;span class="kwrd"&gt;extends &lt;/span&gt;IAutoOptions {
    bedLength: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    fourByFour: &lt;span class="kwrd"&gt;bool&lt;/span&gt;;
}&lt;/pre&gt;
&lt;style type="text/css"&gt;


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;
  &lt;br /&gt;I also showed how a class named Engine can implement an interface named IEngine. By having the IEngine interface in an application you can enforce consistency across multiple engine classes.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;interface&lt;/span&gt; IEngine {
    start(callback: (startStatus: &lt;span class="kwrd"&gt;bool&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void&lt;/span&gt;;
    stop(callback: (stopStatus: &lt;span class="kwrd"&gt;bool&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void&lt;/span&gt;;
}

&lt;span class="kwrd"&gt;class&lt;/span&gt; Engine implements IEngine {
    constructor(&lt;span class="kwrd"&gt;public&lt;/span&gt; horsePower: number, &lt;span class="kwrd"&gt;public&lt;/span&gt; engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) { }

    start(callback: (startStatus: &lt;span class="kwrd"&gt;bool&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void &lt;/span&gt;{
        window.setTimeout(() =&amp;gt; {
            callback(&lt;span class="kwrd"&gt;true&lt;/span&gt;, &lt;span class="kwrd"&gt;this&lt;/span&gt;.engineType);
        }, 1000);
    }

    stop(callback: (stopStatus: &lt;span class="kwrd"&gt;bool&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void &lt;/span&gt;{
        window.setTimeout(() =&amp;gt; {
            callback(&lt;span class="kwrd"&gt;true&lt;/span&gt;, &lt;span class="kwrd"&gt;this&lt;/span&gt;.engineType);
        }, 1000);
    }
}&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;Although interfaces work well in object-oriented languages, JavaScript doesn’t provide any built-in support for interfaces so what role do they actually play in a TypeScript application? The first answer to that question was discussed earlier and relates to consistency. Classes that implement an interface must implement all of the required members (note that TypeScript interfaces also support optional members as well). This makes it easy to enforce consistency across multiple TypeScript classes. If a class doesn’t implement an interface properly then the TypeScript compiler will throw an error and no JavaScript will be output. This lets you catch issues upfront rather than after the fact which is definitely beneficial and something that simplifies maintenance down the road. &lt;/p&gt;

&lt;p&gt;If you look at the JavaScript code that’s generated you won’t see interfaces used at all though – JavaScript simply doesn’t support them. Here’s an example of the JavaScript code generated by the TypeScript compiler for Engine: 
  &lt;br /&gt;

  &lt;br /&gt;

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; Engine = (&lt;span class="kwrd"&gt;function&lt;/span&gt; () {
    &lt;span class="kwrd"&gt;function&lt;/span&gt; Engine(horsePower, engineType) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.horsePower = horsePower;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.engineType = engineType;
    }
    Engine.prototype.start = &lt;span class="kwrd"&gt;function&lt;/span&gt; (callback) {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; _this = &lt;span class="kwrd"&gt;this&lt;/span&gt;;
        window.setTimeout(&lt;span class="kwrd"&gt;function&lt;/span&gt; () {
            callback(&lt;span class="kwrd"&gt;true&lt;/span&gt;, _this.engineType);
        }, 1000);
    };
    Engine.prototype.stop = &lt;span class="kwrd"&gt;function&lt;/span&gt; (callback) {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; _this = &lt;span class="kwrd"&gt;this&lt;/span&gt;;
        window.setTimeout(&lt;span class="kwrd"&gt;function&lt;/span&gt; () {
            callback(&lt;span class="kwrd"&gt;true&lt;/span&gt;, _this.engineType);
        }, 1000);
    };
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Engine;
})();&lt;/pre&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Looking through the code you’ll see that there’s no reference to the IEngine interface at all which is an important point to understand with TypeScript – interfaces are only used when you’re writing code (the editor can show you errors) and when you compile. They’re not used at all in the generated JavaScript.&lt;/p&gt;

&lt;p&gt;In addition to driving consistency across TypeScript classes, interfaces can also be used to ensure proper values are being passed into properties, constructors, or functions. Have you ever passed an object literal (for example { firstName:’John’, lastName:’Doe’}) into a JavaScript function or object constructor only to realize later that you accidentally left out a property that should’ve been included? That’s an easy mistake to make in JavaScript since there’s no indication that you forgot something. With TypeScript that type of problem is easy to solve by adding an interface into the mix.&lt;/p&gt;

&lt;p&gt;The Auto class shown next demonstrates how an interface named IAutoOptions can be defined on a constructor parameter. If you pass an object into the constructor that doesn’t satisfy the IAutoOptions interface then you’ll see an error in editors such as Visual Studio and the code won’t compile using the TypeScript compiler.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Auto {
    basePrice: &lt;span class="kwrd"&gt;number&lt;/span&gt;;
    engine: IEngine;
    state: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    make: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    model: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    year: number;

    constructor(options: IAutoOptions) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.engine = options.engine;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.basePrice = options.basePrice;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.state = options.state;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.make = options.make;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.model = options.model;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.year = options.year;
    }
}&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;An example of using the Auto class’s constructor is shown next. In this example the &lt;strong&gt;year&lt;/strong&gt; (a required field in the interface) is missing so the object doesn’t satisfy the IAutoOptions interface.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; auto = &lt;span class="kwrd"&gt;new&lt;/span&gt; Auto({
    engine: &lt;span class="kwrd"&gt;new&lt;/span&gt; Engine(250, &lt;span class="str"&gt;'V8'&lt;/span&gt;),
    basePrice: 45000,
    state: &lt;span class="str"&gt;'Arizona'&lt;/span&gt;,
    make: &lt;span class="str"&gt;'Ford'&lt;/span&gt;,
    model: &lt;span class="str"&gt;'F-150'&lt;/span&gt;
});&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;In this example the object being passed into the Auto’s constructor implements 5 out of 6 fields from the IAutoOptions interface. Because the constructor parameter requires 6 fields an error will be displayed in the editor and the TypeScript compiler will error out as well if you try to compile the code to JavaScript. An example of the error displayed in Visual Studio is shown next:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/image_1AAD90C6.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/image_thumb_47C27D94.png" width="857" height="150" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;This makes it much easier to catch issues such as missing data while you’re writing the initial code as opposed to catching issues after the fact while trying to run the actual JavaScript. If you write unit tests then this functionality should also help ensure that tests are using proper data.&lt;/p&gt;

&lt;p&gt;Interfaces also allow for more loosely coupled applications as well. Looking back at the Auto class code you’ll notice that the engine field is of type IEngine. This allows any object that implements the interface to be passed which provides additional flexibility. The same can be said about the Auto’s constructor parameter since any object that implement IAutoOptions can be passed.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;h1&gt;&amp;#160;&lt;/h1&gt;

&lt;p&gt;In this post you’ve seen that Interfaces provide a great way to enforce consistency across objects which is useful in a variety of scenarios. In addition to consistency, interfaces can also be used to ensure that proper data is passed to properties, constructors and functions. Finally, interfaces also provide additional flexibility in an application and make it more loosely coupled. Although they never appear in the generated JavaScript, they help to identify issues upfront as you’re building an application and certainly help as modifications are made in the future.&lt;/p&gt;

&lt;p&gt;If you’d like to learn more about TypeScript check out the &lt;a href="http://ow.ly/gEhsJ" target="_blank"&gt;TypeScript Fundamentals course on Pluralsight.com&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://pluralsight.com/training/Courses/TableOfContents/typescript" target="_blank"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/image_18FCC4F2.png" width="798" height="97" /&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Mon, 13 Apr 2015 17:57:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/the-role-of-interfaces-in-typescript</guid><category>.NET</category><category>JavaScript</category><category>TypeScript</category></item><item><title>Extending Classes and Interfaces using TypeScript</title><link>https://weblogs.asp.net:443/dwahlin/extending-classes-and-interfaces-using-typescript</link><description>&lt;p&gt;&lt;img style="float: right; display: inline" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/image_thumb_17649611.png" align="right"&gt;In a &lt;a href="http://weblogs.asp.net/dwahlin/archive/2012/10/31/getting-started-with-typescript-classes-static-types-and-interfaces.aspx" target="_blank"&gt;previous post&lt;/a&gt; I discussed the fundamentals of the TypeScript language and how it can be used to build JavaScript applications. TypeScript is all about strongly-typed variables and function parameters, encapsulation of code, and catching issues upfront as opposed to after the fact to provide more maintainable code bases. One of the great features it offers is the ability to take advantage of inheritance without having to be an expert in JavaScript prototypes, constructors, and other language features (although I certainly recommend learning about those features regardless if you use TypeScript or not). &lt;/p&gt; &lt;p&gt;In this post I’ll discuss how classes and interfaces can be extended using TypeScript and the resulting JavaScript that’s generated. Let’s jump in! &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt; &lt;h1&gt;Extending Classes and Interfaces &lt;br&gt;&lt;/h1&gt; &lt;p&gt;Let’s assume that we have a TypeScript class named &lt;strong&gt;Auto&lt;/strong&gt; that has the following code in it: &lt;br&gt;&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode" style="height: 696px; width: 583px"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Auto {
    &lt;span class="kwrd"&gt;private&lt;/span&gt; _basePrice: &lt;span class="kwrd"&gt;number&lt;/span&gt;;
    engine: IEngine;
    state: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    make: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    model: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    year: &lt;span class="kwrd"&gt;number&lt;/span&gt;;
    accessoryList: &lt;span class="kwrd"&gt;string&lt;/span&gt;;

    constructor(options: IAutoOptions) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.engine = options.engine;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.basePrice = options.basePrice;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.state = options.state;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.make = options.make;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.model = options.model;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.year = options.year;
    }

    calculateTotal() : number {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; taxRate = TaxRateInfo.getTaxRate(&lt;span class="kwrd"&gt;this&lt;/span&gt;.state);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.basePrice + (taxRate.rate * &lt;span class="kwrd"&gt;this&lt;/span&gt;.basePrice);
    }

    addAccessories(...accessories: Accessory[]) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.accessoryList = &lt;span class="str"&gt;''&lt;/span&gt;;
        &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;var&lt;/span&gt; i = 0; i &amp;lt; accessories.length; i++) {
            &lt;span class="kwrd"&gt;var&lt;/span&gt; ac = accessories[i];
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.accessoryList += ac.accessoryNumber + &lt;span class="str"&gt;' '&lt;/span&gt; + ac.title + &lt;span class="str"&gt;'&amp;lt;br /&amp;gt;'&lt;/span&gt;;
        }
    }

    getAccessoryList(): &lt;span class="kwrd"&gt;string&lt;/span&gt; {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.accessoryList;
    }

    &lt;span class="kwrd"&gt;get &lt;/span&gt;basePrice(): number {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;._basePrice;
    }

    &lt;span class="kwrd"&gt;set &lt;/span&gt;basePrice(value: number) {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (value &amp;lt;= 0) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="str"&gt;'price must be &amp;gt;= 0'&lt;/span&gt;;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;._basePrice = value;
    }
} &lt;/pre&gt;
&lt;style type="text/css"&gt;


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;Looking through the code you can see that the class has several members including fields, a constructor, functions (including a function that accepts a special type of … parameter referred to as a rest parameter), and the get and set blocks for a property named basePrice. Although unrelated to inheritance, it’s important to note that properties in TypeScript only work when setting the TypeScript compilation target to ECMAScript 5 using the --target switch (for example:&amp;nbsp; tsc.exe --target ES5 YourFile.ts). &lt;/p&gt;
&lt;p&gt;The engine field in the Auto class accepts any type that implements a TypeScript interface named IEngine and the constructor accepts any object that implements an IAutoOptions interface. Both of these interfaces are shown next: &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;interface&lt;/span&gt; IEngine {
    start(callback: (startStatus: &lt;span class="kwrd"&gt;boolean&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void&lt;/span&gt;;
    stop(callback: (stopStatus: &lt;span class="kwrd"&gt;boolean&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void&lt;/span&gt;;
}

&lt;span class="kwrd"&gt;interface&lt;/span&gt; IAutoOptions {
    engine: IEngine;
    basePrice: &lt;span class="kwrd"&gt;number&lt;/span&gt;;
    state: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    make: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    model: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    year: &lt;span class="kwrd"&gt;number&lt;/span&gt;;
}&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;The start() and stop() functions in the IEngine interface both accept a callback function. The callback function must accept two parameters of type boolean and string. An example of implementing the IEngine interface using TypeScript is shown next. A class that implements an interface must define all members of the interface unless the members are marked as optional using the ? operator. &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Engine &lt;span class="kwrd"&gt;implements &lt;/span&gt;IEngine {
    constructor(&lt;span class="kwrd"&gt;public&lt;/span&gt; horsePower: &lt;span class="kwrd"&gt;number&lt;/span&gt;, &lt;span class="kwrd"&gt;public&lt;/span&gt; engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) { }

    start(callback: (startStatus: &lt;span class="kwrd"&gt;boolean&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void&lt;/span&gt;{
        window.setTimeout(() =&amp;gt; {
            callback(&lt;span class="kwrd"&gt;true&lt;/span&gt;, &lt;span class="kwrd"&gt;this&lt;/span&gt;.engineType);
        }, 1000);
    }

    stop(callback: (stopStatus: &lt;span class="kwrd"&gt;boolean&lt;/span&gt;, engineType: &lt;span class="kwrd"&gt;string&lt;/span&gt;) =&amp;gt; &lt;span class="kwrd"&gt;void&lt;/span&gt;) : &lt;span class="kwrd"&gt;void&lt;/span&gt;{
        window.setTimeout(() =&amp;gt; {
            callback(&lt;span class="kwrd"&gt;true&lt;/span&gt;, &lt;span class="kwrd"&gt;this&lt;/span&gt;.engineType);
        }, 1000);
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;It goes without saying that if we wanted to create a Truck class that extends the Auto class we wouldn’t want to cut-and-paste the code from Auto into Truck since that would lead to a maintenance headache down the road. Fortunately, TypeScript allows us to take advantage of inheritance to re-use the code in Auto. An example of a Truck class that extends the Auto class using the TypeScript &lt;strong&gt;extends&lt;/strong&gt; keyword is shown next: &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Truck &lt;span class="kwrd"&gt;extends &lt;/span&gt;Auto {
    &lt;span class="kwrd"&gt;private&lt;/span&gt; _bedLength: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    fourByFour: &lt;span class="kwrd"&gt;boolean&lt;/span&gt;;

    constructor(options: ITruckOptions) {
        &lt;span class="kwrd"&gt;super&lt;/span&gt;(options);
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.bedLength = options.bedLength;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.fourByFour = options.fourByFour;
    }

    &lt;span class="kwrd"&gt;get &lt;/span&gt;bedLength(): &lt;span class="kwrd"&gt;string&lt;/span&gt; {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;._bedLength;
    }

    &lt;span class="kwrd"&gt;set &lt;/span&gt;bedLength(value: &lt;span class="kwrd"&gt;string&lt;/span&gt;) {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (value == &lt;span class="kwrd"&gt;null&lt;/span&gt; || value == undefined || value == &lt;span class="str"&gt;''&lt;/span&gt;) {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;._bedLength = &lt;span class="str"&gt;'Short'&lt;/span&gt;;
        }
        &lt;span class="kwrd"&gt;else&lt;/span&gt; {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;._bedLength = value;
        }
    }
}&lt;/pre&gt;&lt;br&gt;
&lt;p&gt;The Truck class extends Auto by adding bedLength and fourByFour capabilities. The constructor also accepts an object that implements the ITruckOptions interface which in turn extends the IAutoOptions interface shown earlier. Notice that interfaces can also be extended in TypeScript by using the &lt;strong&gt;extends&lt;/strong&gt; keyword: &lt;br&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;interface&lt;/span&gt; ITruckOptions &lt;span class="kwrd"&gt;extends &lt;/span&gt;IAutoOptions {
    bedLength: &lt;span class="kwrd"&gt;string&lt;/span&gt;;
    fourByFour: &lt;span class="kwrd"&gt;boolean&lt;/span&gt;;
}&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;Here’s an example of creating a new instance of the Truck class and passing an object that implements the ITruckOptions interface into its constructor: &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; truck = &lt;span class="kwrd"&gt;new&lt;/span&gt; Truck({
    engine: &lt;span class="kwrd"&gt;new&lt;/span&gt; Engine(250, &lt;span class="str"&gt;'V8'&lt;/span&gt;),
    basePrice: 45000,
    state: &lt;span class="str"&gt;'Arizona'&lt;/span&gt;,
    make: &lt;span class="str"&gt;'Ford'&lt;/span&gt;,
    model: &lt;span class="str"&gt;'F-150'&lt;/span&gt;,
    year: 2013,
    bedLength: &lt;span class="str"&gt;'Short Bed'&lt;/span&gt;,
    fourByFour: &lt;span class="kwrd"&gt;true&lt;/span&gt;
});&lt;/pre&gt;
&lt;h1&gt;&lt;br&gt;&lt;br&gt;Inheritance in JavaScript &lt;br&gt;&lt;/h1&gt;
&lt;p&gt;&lt;br&gt;You can see that the TypeScript &lt;strong&gt;extends&lt;/strong&gt; keyword provides a simple and convenient way to inherit functionality from a base class (or extend an interface) but what happens behind the scenes once the code is compiled into JavaScript? After all, JavaScript doesn’t have an &lt;strong&gt;extends&lt;/strong&gt; or &lt;strong&gt;inherits&lt;/strong&gt; keyword in the language - at least not in ECMAScript 5 or earlier. If you look at the JavaScript code that’s output by the TypeScript compiler you’ll see that a little magic is added to simulate inheritance in JavaScript using prototyping. &lt;/p&gt;
&lt;p&gt;First, a variable named __extends is added into the generated JavaScript and it is assigned to a function that accepts two parameters as shown next: &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; __extends = &lt;span class="kwrd"&gt;this&lt;/span&gt;.__extends || &lt;span class="kwrd"&gt;function&lt;/span&gt; (d, b) {
    &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;var&lt;/span&gt; p &lt;span class="kwrd"&gt;in&lt;/span&gt; b) &lt;span class="kwrd"&gt;if&lt;/span&gt; (b.hasOwnProperty(p)) d[p] = b[p];
    &lt;span class="kwrd"&gt;function&lt;/span&gt; __() { &lt;span class="kwrd"&gt;this&lt;/span&gt;.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = &lt;span class="kwrd"&gt;new&lt;/span&gt; __();
};&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;&lt;br&gt;The function accepts the derived/child type (the d parameter) and the base type (the b parameter).&amp;nbsp; Inside of the function an object named __ is created (definitely a strange name) and the derived type is assigned to it’s constructor. From there, the base type’s prototype is assigned to the __ object’s prototype. To finish things up a new instance of the __ object is created and assigned to the derived type’s prototype so it picks up prototype members from the base type. In the end, this little function provides a re-useable way to handle inheritance between two objects in JavaScript. If you’re new to prototypes then you’re probably appreciating the simplicity provided by the TypeScript &lt;strong&gt;extends&lt;/strong&gt; keyword!&lt;/p&gt;
&lt;p&gt;The __extends function is used later in the generated JavaScript code to handle inheritance between Truck and Auto. An example of the code that’s generated to represent the Truck class is shown next: &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; Truck = (&lt;span class="kwrd"&gt;function&lt;/span&gt; (_super) {
    __extends(Truck, _super);
    &lt;span class="kwrd"&gt;function&lt;/span&gt; Truck(options) {
        _super.call(&lt;span class="kwrd"&gt;this&lt;/span&gt;, options);
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.bedLength = options.bedLength;
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.fourByFour = options.fourByFour;
    }
    Object.defineProperty(Truck.prototype, &lt;span class="str"&gt;"bedLength"&lt;/span&gt;, {
        get: &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;._bedLength;
        },
        set: &lt;span class="kwrd"&gt;function&lt;/span&gt; (value) {
            &lt;span class="kwrd"&gt;if&lt;/span&gt;(value == &lt;span class="kwrd"&gt;null&lt;/span&gt; || value == undefined || value == &lt;span class="str"&gt;''&lt;/span&gt;) {
                &lt;span class="kwrd"&gt;this&lt;/span&gt;._bedLength = &lt;span class="str"&gt;'Short'&lt;/span&gt;;
            } &lt;span class="kwrd"&gt;else&lt;/span&gt; {
                &lt;span class="kwrd"&gt;this&lt;/span&gt;._bedLength = value;
            }
        },
        enumerable: &lt;span class="kwrd"&gt;true&lt;/span&gt;,
        configurable: &lt;span class="kwrd"&gt;true&lt;/span&gt;
    });
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Truck;
})(Auto);&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;Notice that the Truck variable is assigned to a function that accepts a parameter named _super. This parameter represents the base class to inherit functionality from. The function assigned to Truck is self-invoked at the bottom of the code and the base class to derive from (Auto in this example) is passed in for the value of the _super parameter. The __extends function discussed earlier is then called inside of the Truck function and the derived type (Truck) and base type (Auto) are passed in as parameters. The magic of inheritance then happens using prototypes as discussed earlier. &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt;
&lt;h1&gt;Conclusion &lt;br&gt;&lt;/h1&gt;
&lt;p&gt;In this post you’ve seen how TypeScript can be used to create an inheritance hierarchy and the resulting JavaScript that’s generated. You’ve also seen how interfaces can be created, implemented, and even extended using TypeScript.&lt;/p&gt;
&lt;p&gt;Check out the &lt;a href="http://pluralsight.com/training/Courses/TableOfContents/typescript"&gt;TypeScript Fundamentals course&lt;/a&gt; on &lt;a href="http://www.pluralsight.com" target="_blank"&gt;Pluralsight.com&lt;/a&gt;&amp;nbsp; and see what TypeScript offers for both large-scale and small-scale JavaScript applications. &lt;/p&gt;</description><pubDate>Fri, 10 Apr 2015 17:49:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/extending-classes-and-interfaces-using-typescript</guid><category>.NET</category><category>JavaScript</category><category>TypeScript</category></item><item><title>Introducing the AngularU Conference</title><link>https://weblogs.asp.net:443/dwahlin/introducing-the-angularu-conference</link><description>&lt;p&gt;&lt;img style="float: right; display: inline;" src="http://peterkellner.net/misc/angularsticker_300x300.png" align="right" /&gt;In late 2014 my good friend &lt;a href="https://twitter.com/pkellner" target="_blank"&gt;Peter Kellner&lt;/a&gt; approach me with a big idea &amp;ndash; an idea that immediately caught my attention. He wanted to explore collaborating on a new conference idea that would highlight &lt;a href="http://angular.io" target="_blank"&gt;Angular&lt;/a&gt; and other &amp;ldquo;hot&amp;rdquo; Web development topics and wondered if I&amp;rsquo;d be interested in working with him and another friend of his named &lt;a href="https://twitter.com/javaclimber" target="_blank"&gt;Kevin Nilson&lt;/a&gt; (who is also a good friend now) on a full-scale conference. I&amp;rsquo;ve been involved with chairing a lot of conference tracks over the years but never been the driving force behind organizing an entire conference. While the idea was definitely exciting it was also a little scary &amp;ndash; at least initially. &lt;br /&gt;&lt;br /&gt;After talking more with Peter and Kevin I decided to jump in and we&amp;rsquo;ve been working hard to put on a top-notch conference called &lt;a href="http://angularu.com" target="_blank"&gt;AngularU&lt;/a&gt; (short for &amp;ldquo;Angular University&amp;rdquo;) that will be held in &lt;strong&gt;San Francisco &lt;/strong&gt;from &lt;strong&gt;June 22 &amp;ndash; 25, 2015&lt;/strong&gt;. I&amp;rsquo;m really excited about the conference and thought I&amp;rsquo;d discuss some of the key reasons in this post.&lt;/p&gt;
&lt;h2&gt;The Web is Changing Rapidly&lt;/h2&gt;
&lt;p&gt;It&amp;rsquo;s no secret that the web is changing at a rapid pace. In fact &amp;ldquo;rapid&amp;rdquo; may be an understatement since in the time I&amp;rsquo;ve been writing this post I suspect several new JavaScript or CSS libraries have been released on Github. Keeping up with the pace of Web technologies can be a challenging proposition to say the least although for me personally I think it&amp;rsquo;s all part of the fun of working in this space. In my training classes I always tell people that, &amp;ldquo;If you&amp;rsquo;re getting bored you&amp;rsquo;re just not trying hard enough&amp;rdquo; since there&amp;rsquo;s so much to learn.&lt;/p&gt;
&lt;p&gt;When Peter and I first discussed the concept of doing an Angular conference I thought about it more and realized that while focusing on Angular would be good, several other conferences were already doing that exact thing really well such as &lt;a href="http://www.ng-conf.org/" target="_blank"&gt;ng-conf&lt;/a&gt; (friends from the ng-conf event such as &lt;a href="https://twitter.com/js_dev" target="_blank"&gt;Aaron Frost&lt;/a&gt; and &lt;a href="https://twitter.com/josepheames" target="_blank"&gt;Joe Eames&lt;/a&gt; have even taken the time to provide us with a lot of excellent feedback).&amp;nbsp; I took a step back and thought about what web technologies I&amp;rsquo;d like to see included if I could create my own conference given the rapid pace of the web in general. After thinking about it more I decided that I&amp;rsquo;d want a conference that had Angular sessions (including Angular 2!) as well as sessions on TypeScript, ES6, and Web Components. I suggested that general concept to Peter and we agreed that providing more broad coverage of web technologies would be the overall goal of AngularU. As a result, the &lt;a href="http:/angularu.com" target="_blank"&gt;AngularU conference&lt;/a&gt; now has many talks lined up to discuss TypeScript, ES6, Web Components, CSS and more which should help attendees get a good understanding about the latest and greatest technologies out there.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Top-Notch Experts and Speakers&lt;/h2&gt;
&lt;p&gt;There are a lot of conferences out there and many claim to have the &amp;ldquo;best speakers in the industry&amp;rdquo;. If I was going to be involved with a conference then I definitely wanted some of the top names and key players in the industry to be involved. Peter, Kevin and I decided that we wanted the Google team to give the keynote on &lt;a href="http://angular.io" target="_blank"&gt;Angular 2&lt;/a&gt;. Fortunately, we had a meeting with &lt;a href="https://twitter.com/bradlygreen" target="_blank"&gt;Brad Green&lt;/a&gt; and &lt;a href="https://twitter.com/igorminar" target="_blank"&gt;Igor Minar&lt;/a&gt; from the Angular team and they agreed to give the keynote. We&amp;rsquo;re really excited that Brad, Igor, and &lt;a href="https://twitter.com/mhevery" target="_blank"&gt;Misko Hevery&lt;/a&gt; have agreed to come speak! It&amp;rsquo;ll be great to hear about the latest updates on Angular 2 in June.&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_2.png"&gt;&lt;img title="image" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_thumb.png" width="547" height="196" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_4.png"&gt;&lt;img title="image" style="background-image: none; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_thumb_1.png" width="130" align="right" height="140" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_6.png"&gt;&lt;img title="image" style="background-image: none; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 10px 0px 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_thumb_2.png" width="107" align="left" height="123" /&gt;&lt;/a&gt;We didn&amp;rsquo;t stop there. With the big announcement about &lt;a href="http://typescriptlang.org" target="_blank"&gt;TypeScript&lt;/a&gt; and &lt;a href="http://angular.io" target="_blank"&gt;Angular&lt;/a&gt; we also wanted a top-notch person involved with TypeScript to come speak. As a result, the day 2 keynote at AngularU will be by &lt;a href="https://twitter.com/jntrnr" target="_blank"&gt;Jonathan Turner&lt;/a&gt;, the program manager on the TypeScript team. We&amp;rsquo;re super excited to have Jonathan involved with the conference as well. We also wanted someone very well known in the JavaScript community to be involved who&amp;rsquo;s had a tremendous influence over the years on the JavaScript code most of us write today. We&amp;rsquo;re very excited to have &lt;a href="http://javascript.crockford.com/" target="_blank"&gt;Douglas Crockford&lt;/a&gt; coming as well to give a day 1 afternoon keynote to discuss his latest findings in the world of JavaScript!&lt;/p&gt;
&lt;p&gt;In addition to the keynote speakers we also have many additional great speakers and experts in the industry such as &lt;a href="https://twitter.com/john_papa" target="_blank"&gt;John Papa&lt;/a&gt; (he and I will be giving a talk after the day 1 keynote), &lt;a href="https://twitter.com/johnlindquist" target="_blank"&gt;John Lindquist&lt;/a&gt;, &lt;a href="https://twitter.com/simpulton" target="_blank"&gt;Lukas Ruebbelke&lt;/a&gt; and many more. Check out the &lt;a href="http://angularu.com"&gt;http://angularu.com&lt;/a&gt; site for a list of speakers (more are being added as we finalize talk selections).&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_8.png"&gt;&lt;img title="image" style="background-image: none; float: right; padding-top: 0px; padding-left: 0px; margin: 10px 0px 10px 10px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_thumb_3.png" width="434" align="right" height="569" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;AngularU Sessions&lt;/h2&gt;
&lt;p&gt;So what are some of the topics speakers will be covering at AngularU? Here are a few of the talks:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Angular 2 Keynote&lt;/li&gt;
&lt;li&gt;TypeScript Keynote&lt;/li&gt;
&lt;li&gt;JavaScript/ES6 Keynote&lt;/li&gt;
&lt;li&gt;Migrating to Angular 2&lt;/li&gt;
&lt;li&gt;Crazy Fast Prototyping with Angular&lt;/li&gt;
&lt;li&gt;Modular Angular: Building Reusable Components Today&lt;/li&gt;
&lt;li&gt;ES6 with Angular Today&lt;/li&gt;
&lt;li&gt;Web Components and the Shadow DOM&lt;/li&gt;
&lt;li&gt;Creating D3 components with Angular 2 and TypeScript&lt;/li&gt;
&lt;li&gt;Angular 2 Server Rendering&lt;/li&gt;
&lt;li&gt;Angular 2 Core Concepts&lt;/li&gt;
&lt;li&gt;Foundation for Apps: Integrating Angular with Responsive Web Apps&lt;/li&gt;
&lt;li&gt;Many more!&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;br /&gt;Check out the &lt;a href="http://angularu.com" target="_blank"&gt;AngularU website&lt;/a&gt; to see a complete list of speakers and talks. We&amp;rsquo;ll be updating it with new talks and speakers in early April so check back often for the latest.&lt;/p&gt;
&lt;h2&gt;&lt;br /&gt;Have Fun While Learning and Networking&lt;/h2&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_10.png"&gt;&lt;img title="image" style="background-image: none; float: left; padding-top: 0px; padding-left: 0px; margin: 3px 10px 0px 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_thumb_4.png" width="196" align="left" height="115" /&gt;&lt;/a&gt;People learn best while they&amp;rsquo;re having fun and we plan to make AngularU a fun yet educational event. From the AngularU game room to the lunch and attendee party events, we have a lot of great stuff planned that will help people meet and get a chance to discuss all of the things happening with web development. In addition to the events planned for attendees, we also have a community night planned that anyone from the San Francisco area can attend and have other events to give everyone a chance to talk with the speakers and other experts who will be attending.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;&lt;br /&gt;Come Join Us at AngularU in San Francisco!&lt;/h2&gt;
&lt;p&gt;We&amp;rsquo;ve come a long way from the initial call that Peter and I had about potentially doing a conference and are super excited about all of the great speakers and content that will be at the event! We hope that you&amp;rsquo;ll come join in the fun and learning at AngularU!&lt;/p&gt;
&lt;p&gt;&lt;a href="http://angularu.com" target="_blank"&gt;AngularU&lt;/a&gt; will run from June 22nd &amp;ndash; 23rd at the Hyatt Regency San Francisco Airport hotel and conference center. Post-conference workshops will run on June 24th &amp;ndash; 25th at the same location.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_14.png"&gt;&lt;img title="image" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Introducing-the-Angular-U-Conference_A554/image_thumb_6.png" width="652" height="266" /&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Sun, 29 Mar 2015 21:49:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/introducing-the-angularu-conference</guid><category>angularjs</category><category>javascript</category><category>ES6</category><category>TypeScript</category><category>conference</category></item><item><title>Creating a TypeScript Workflow with Gulp</title><link>https://weblogs.asp.net:443/dwahlin/creating-a-typescript-workflow-with-gulp</link><description>&lt;img style="float: right; margin: 0px 0px 10px 10px; display: inline" src="https://pbs.twimg.com/profile_images/2660272602/87a5a0fdc86455c3f94b0b0eebfdb1b9.png" align="right"&gt; &lt;p&gt;TypeScript provides a lot of great functionality that lets you leverage many of the features available in ES6 today but how do you get started using it in your favorite editor? If you’re using Visual Studio or WebStorm then TypeScript support can be used directly and everything happens magically without much work on your part. But, if you’re using Sublime Text, Brackets, Atom, or another editor you’ll have to find a plugin to compile .ts files to JavaScript or create your own custom workflow.  &lt;p&gt;While several plugins exist to compile TypeScript and even provide code help as you’re writing TypeScript code in different editors, I generally prefer to use my own custom workflow. There are multiple benefits associated with going with this approach including the ability to standardize and share tasks across team members as well as being able to tie the workflow into a custom build process used in continuous integration scenarios. In this post I’ll walk through the process of creating a custom TypeScript workflow using &lt;a href="http://gulpjs.com/"&gt;Gulp&lt;/a&gt; (a JavaScript task manager). It’s a workflow setup that my friend &lt;a href="https://twitter.com/andrewconnell" target="_blank"&gt;Andrew Connell&lt;/a&gt; and I created when we recently converted an &lt;a href="https://github.com/DanWahlin/AngularTypeScript" target="_blank"&gt;application&lt;/a&gt; to TypeScript. Throughout the post you’ll learn how to setup a file named gulpfile.js to compile TypeScript to JavaScript and also see how you can “lint” your TypeScript code to make sure it’s as clean and tidy as possible.&lt;br&gt; &lt;h2&gt;Getting Started Creating a Custom TypeScript Workflow&lt;/h2&gt; &lt;p&gt;I talked about using Gulp to automate the process of transpiling ES6 to ES5 in a &lt;a href="http://weblogs.asp.net/dwahlin/getting-started-with-es6-%E2%80%93-transpiling-es6-to-es5"&gt;previous post&lt;/a&gt;. The general process shown there is going to be used here as well although I’ll be providing additional details related to TypeScript. If you’re new to Gulp, it’s a JavaScript task manager that can be used to compile .ts files to .js files, lint your TypeScript, minify and concatenate scripts, and much more. You can find additional details at &lt;a href="http://gulpjs.com/"&gt;http://gulpjs.com&lt;/a&gt;. &lt;p&gt;Here’s a step-by-step walk-through that shows how to get started creating a TypeScript workflow with Gulp. Although there are several steps to perform, it’s a one-time setup that can be re-used across projects. If you’d prefer to use a starter project rather than walking through the steps that are provided in this post then see the project at &lt;a href="https://github.com/DanWahlin/AngularIn20TypeScript"&gt;https://github.com/DanWahlin/AngularIn20TypeScript&lt;/a&gt; or download the project associated with the exact steps shown in this post &lt;a href="https://dl.dropboxusercontent.com/u/6037348/TypeScript/typescriptGulpWorkflow.zip" target="_blank"&gt;here&lt;/a&gt;. &lt;br&gt; &lt;h3&gt;Creating the Application Folders and Files&lt;br&gt;&lt;/h3&gt; &lt;ol&gt; &lt;li&gt;Create a new folder where your project code will live. You can name it anything you’d like but I’ll call it &lt;b&gt;typescriptDemo&lt;/b&gt; in this post.&lt;br&gt;&lt;/li&gt; &lt;li&gt;Create the following folders inside of &lt;strong&gt;typescriptDemo&lt;/strong&gt;:&lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;src&lt;/strong&gt;&lt;/li&gt; &lt;li&gt;&lt;strong&gt;src/app&lt;/strong&gt;&lt;/li&gt; &lt;li&gt;&lt;strong&gt;src/js&lt;/strong&gt;&lt;br&gt;&lt;!--EndFragment--&gt;&lt;br&gt;&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Open a command-prompt in the root of the &lt;b&gt;typescriptDemo&lt;/b&gt; folder and run the following &lt;b&gt;npm&lt;/b&gt; command (you’ll need to have &lt;a href="http://nodejs.org/"&gt;Node.js&lt;/a&gt; installed) to create a file named &lt;b&gt;package.json&lt;/b&gt;. &lt;br&gt;&lt;br&gt;&lt;/li&gt;&lt;b&gt;npm init&lt;br&gt;&lt;br&gt;&lt;/b&gt; &lt;li&gt;Answer the questions that are asked. For this example you can go with all of the defaults it provides. After completing the wizard a new file named &lt;b&gt;package.json&lt;/b&gt; will be added to the root of the folder.&lt;br&gt;&lt;/li&gt; &lt;li&gt;Create the following files in the &lt;b&gt;typescriptDemo&lt;/b&gt; folder:&lt;/li&gt;&lt;/ol&gt; &lt;ul&gt; &lt;ul&gt; &lt;li&gt;&lt;b&gt;gulpfile.js&lt;/b&gt;&lt;/li&gt; &lt;li&gt;&lt;b&gt;gulpfile.config.js&lt;/b&gt;&lt;/li&gt; &lt;li&gt;t&lt;strong&gt;slint.json&lt;br&gt;&lt;/strong&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;&lt;b&gt;&lt;/b&gt; &lt;h3&gt;&lt;br&gt;Installing Gulp, Gulp Modules and TSD&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/1aaa3d08d14c_14AAE/image_2.png"&gt;&lt;img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 0px 0px 10px 10px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/1aaa3d08d14c_14AAE/image_thumb.png" width="400" align="right" height="100"&gt;&lt;/a&gt;&lt;br&gt;&lt;/h3&gt; &lt;p&gt;&lt;b&gt;&lt;/b&gt; &lt;ol&gt; &lt;li&gt;Now let’s get &lt;strong&gt;Gulp&lt;/strong&gt; installed globally on your machine. Open a command-prompt and run the following command:&lt;br&gt;&lt;br&gt;&lt;/li&gt;&lt;b&gt;npm install gulp –g&lt;br&gt;&lt;br&gt;&lt;/b&gt; &lt;li&gt;Open &lt;b&gt;package.json&lt;/b&gt; and add the following &lt;b&gt;devDependencies&lt;/b&gt; property into it. The location of the property in the file doesn’t really matter but I normally put it at the bottom. A sample &lt;b&gt;package.json&lt;/b&gt; file with the dependencies already in it can be found at &lt;a href="https://github.com/DanWahlin/AngularIn20TypeScript"&gt;https://github.com/DanWahlin/AngularIn20TypeScript&lt;/a&gt;. &lt;br&gt;&lt;br&gt;&lt;b&gt;Note:&lt;/b&gt; The module versions shown here will certainly change over time. You can visit &lt;a href="http://npmjs.org"&gt;http://npmjs.org&lt;/a&gt; to find the latest version of a given module. &lt;br&gt;&lt;/li&gt;&lt;pre class="csharpcode"&gt;&lt;span class="str"&gt;"devDependencies"&lt;/span&gt;: { 
    &lt;span class="str"&gt;"gulp"&lt;/span&gt;: &lt;span class="str"&gt;"^3.8.11"&lt;/span&gt;, 
    &lt;span class="str"&gt;"gulp-debug"&lt;/span&gt;: &lt;span class="str"&gt;"^2.0.1"&lt;/span&gt;, 
    &lt;span class="str"&gt;"gulp-inject"&lt;/span&gt;: &lt;span class="str"&gt;"^1.2.0"&lt;/span&gt;, 
    &lt;span class="str"&gt;"gulp-sourcemaps"&lt;/span&gt;: &lt;span class="str"&gt;"^1.5.1"&lt;/span&gt;, 
    &lt;span class="str"&gt;"gulp-tslint"&lt;/span&gt;: &lt;span class="str"&gt;"^1.4.4"&lt;/span&gt;, 
    &lt;span class="str"&gt;"gulp-typescript"&lt;/span&gt;: &lt;span class="str"&gt;"^2.5.0"&lt;/span&gt;, 
    &lt;span class="str"&gt;"gulp-rimraf"&lt;/span&gt;: &lt;span class="str"&gt;"^0.1.1"&lt;/span&gt; 
}&lt;br&gt;&lt;br&gt;&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;li&gt;Ensure that your command window path is at the root of the &lt;b&gt;typescriptDemo&lt;/b&gt; folder and run the following command to install the dependencies:&lt;br&gt;&lt;br&gt;&lt;b&gt;npm install&lt;br&gt;&lt;/b&gt;&lt;br&gt;&lt;/li&gt;
&lt;li&gt;The &lt;a href="http://definitelytyped.org"&gt;http://definitelytyped.org&lt;/a&gt; site provides a Node.js module named &lt;b&gt;tsd&lt;/b&gt; that can be used to install TypeScript type definition files that are used to provide enhanced code help in various editors. Install the &lt;b&gt;tsd&lt;/b&gt; module globally by running the following command:&lt;br&gt;&lt;br&gt;&lt;b&gt;npm install tsd@next -g&lt;br&gt;&lt;/b&gt;&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Run the following command:&lt;br&gt;&lt;br&gt;&lt;b&gt;tsd init&lt;br&gt;&lt;/b&gt;&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Open the tsd.json file that is generated in the root of &lt;strong&gt;typescriptDemo &lt;/strong&gt;and change the following properties to include “tools” in the path as shown next:&lt;br&gt;&lt;br&gt;&lt;b&gt;"path": "tools/typings",&lt;br&gt;&lt;/b&gt;&lt;b&gt;"bundle": "tools/typings/tsd.d.ts"&lt;br&gt;&lt;br&gt;&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Let’s use &lt;b&gt;tsd&lt;/b&gt; to install a TypeScript definition file for Angular (an angular.d.ts file) and update the &lt;b&gt;tsd.json&lt;/b&gt; file with the Angular file details as well. Run the following command:&lt;br&gt;&lt;br&gt;&lt;/li&gt;
&lt;p&gt;&lt;b&gt;tsd install angular --save&lt;/b&gt; &lt;br&gt;
&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; You can install additional type definition files for other JavaScript libraries/frameworks by running the same command but changing the name from “angular” to the appropriate library/framework. See &lt;a href="http://definitelytyped.org/tsd"&gt;http://definitelytyped.org/tsd&lt;/a&gt; for a list of the type definition files that are available.&lt;br&gt;&lt;/p&gt;
&lt;li&gt;Let’s now install the jQuery type definition as well since the Angular type definition file has a dependency on it:&lt;br&gt;&lt;br&gt;&lt;b&gt;tsd install jquery --save&lt;br&gt;&lt;/b&gt;&lt;br&gt;&lt;/li&gt;
&lt;li&gt;If you look in the &lt;b&gt;typescriptDemo&lt;/b&gt; folder you’ll see a new folder is created named &lt;b&gt;tools&lt;/b&gt;. Inside of this folder you’ll find a file named &lt;b&gt;typings&lt;/b&gt; that has an &lt;b&gt;angular/angular.d.ts&lt;/b&gt; type definition file and a &lt;b&gt;jquery/jquery.d.ts&lt;/b&gt; file in it. You’ll also see a file named &lt;b&gt;tsd.json&lt;/b&gt;.&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Create a file named &lt;b&gt;typescriptApp.d.ts&lt;/b&gt; in the &lt;b&gt;typescriptDemo/tools/typings&lt;/b&gt; folder. This file will track all of the TypeScript files within the application to simplify the process of resolving dependencies and compiling TypeScript to JavaScript.&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Add the following into the &lt;strong&gt;typescriptApp.d.ts &lt;/strong&gt;file and save it (the comments are required for one of the Gulp tasks to work properly):&lt;/li&gt;&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;b&gt;//{&lt;/b&gt;
&lt;p&gt;&lt;b&gt;&lt;/b&gt;
&lt;p&gt;&lt;b&gt;//}&lt;/b&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;h3&gt;&lt;br&gt;Creating Gulp Tasks&lt;br&gt;&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Open &lt;a href="https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/gulpfile.config.js"&gt;https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/gulpfile.config.js&lt;/a&gt; in your browser and copy the contents of the file into your empty &lt;b&gt;gulpfile.config.js&lt;/b&gt; file. This file sets up paths that will be used when performing various tasks such as compiling TypeScript to JavaScript.&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Open &lt;a href="https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/gulpfile.js"&gt;https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/gulpfile.js&lt;/a&gt; in your browser and copy the contents of the file into your empty &lt;b&gt;gulpfile.js&lt;/b&gt; file. This creates the following Gulp tasks:&lt;br&gt;&lt;br&gt;&lt;b&gt;gen-ts-refs&lt;/b&gt;: Adds all of your TypeScript file paths into a file named &lt;b&gt;typescriptApp.d.ts&lt;/b&gt;. This file will be used to support code help in some editors as well as aid with compilation of TypeScript files. &lt;/li&gt;
&lt;p&gt;&lt;b&gt;ts-lint&lt;/b&gt;: Runs a “linting” task to ensure that your code follows specific guidelines defined in the tsline.js file. 
&lt;p&gt;&lt;b&gt;compile-ts: &lt;/b&gt;Compiles TypeScript to JavaScript and generates source map files used for debugging TypeScript code in browsers such as Chrome. 
&lt;p&gt;&lt;b&gt;clean-ts:&lt;/b&gt; Used to remove all generated JavaScript files and source map files. 
&lt;p&gt;&lt;b&gt;watch:&lt;/b&gt; Watches the folder where your TypeScript code lives and triggers the ts-lint, compile-ts, and gen-ts-refs tasks as files changes are detected. 
&lt;p&gt;&lt;b&gt;default:&lt;/b&gt; The default Grunt task that will trigger the other tasks to run. This task can be run by typing &lt;b&gt;gulp&lt;/b&gt; at the command-line when you’re within the &lt;b&gt;typescriptDemo&lt;/b&gt; folder.&lt;br&gt;&lt;br&gt;&lt;/p&gt;
&lt;li&gt;Open &lt;a href="https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/tslint.json"&gt;https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/tslint.json&lt;/a&gt; in your browser and copy the contents of the file into your empty &lt;b&gt;tslint.js&lt;/b&gt; file. This has the “linting” guidelines that will be applied to your code. You’ll more than likely want to tweak some of the settings in the file depending on your coding style.&lt;br&gt;&lt;br&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;h3&gt;Compiling TypeScript to JavaScript&lt;br&gt;&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Now that the necessary files are in place (whew!), let’s add a test TypeScript file into the application folder and try to compile it to JavaScript. Create a file named &lt;b&gt;customer.ts&lt;/b&gt; in the &lt;b&gt;typescriptDemo/src/app&lt;/b&gt; folder.&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Add the following code into the &lt;b&gt;customer.ts&lt;/b&gt; file:&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Customer {
    name: &lt;span class="kwrd"&gt;string&lt;/span&gt;;

    constructor(name: &lt;span class="kwrd"&gt;string&lt;/span&gt;) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.name = name;
    }

    getName() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.name;
    }
}
&lt;/pre&gt;&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Run the following command in your command window (run it from the root of the &lt;b&gt;typescriptDemo&lt;/b&gt; folder):&lt;br&gt;&lt;br&gt;&lt;b&gt;gulp&lt;br&gt;&lt;/b&gt;&lt;br&gt;&lt;/li&gt;
&lt;li&gt;You should see output that shows that the tasks have successfully completed. &lt;br&gt;&lt;/li&gt;
&lt;li&gt;Open the &lt;b&gt;src/js&lt;/b&gt; folder and you should that two new files named &lt;b&gt;customer.js &lt;/b&gt;and &lt;b&gt;customer.js.map&lt;/b&gt; are now there.&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Go back to &lt;b&gt;customer.ts&lt;/b&gt; and change the case of the &lt;b&gt;Customer&lt;/b&gt; class to &lt;b&gt;customer&lt;/b&gt;. Save the file and notice that the gulp tasks have run in the command window. You should see a &lt;strong&gt;tslint&lt;/strong&gt; error saying that the case of the class is wrong.&lt;br&gt;&lt;/li&gt;
&lt;li&gt;Your Gulp/TypeScript workflow is now ready to go. &lt;br&gt;&lt;br&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In this post you’ve seen the steps required to create a custom TypeScript workflow using the Gulp JavaScript task runner. Although you may certainly want to tweak some of the settings and tasks, the steps shown here should help get you started using TypeScript in your applications. 
&lt;p&gt;In case you missed it earlier in the post, a project that has all of the steps already completed can be found at &lt;a href="https://github.com/DanWahlin/AngularIn20TypeScript"&gt;https://github.com/DanWahlin/AngularIn20TypeScript&lt;/a&gt;. You can also find the exact setup discussed in this post &lt;a href="https://dl.dropboxusercontent.com/u/6037348/TypeScript/typescriptGulpWorkflow.zip"&gt;here&lt;/a&gt; (just run &lt;strong&gt;npm install&lt;/strong&gt; to get the required modules for the project).
</description><pubDate>Mon, 23 Mar 2015 07:14:15 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/creating-a-typescript-workflow-with-gulp</guid><category>TypeScript</category><category>Gulp</category><category>JavaScript</category><category>angularjs</category><category>jQuery</category><category>.NET</category></item><item><title>Getting Started with TypeScript – Classes, Types and Interfaces</title><link>https://weblogs.asp.net:443/dwahlin/getting-started-with-typescript-classes-static-types-and-interfaces</link><description>&lt;p&gt;One of the big announcements at &lt;a href="http://ng-conf.org" title="ng-conf" target="_blank"&gt;ng-conf&lt;/a&gt; this week was the collaborative work that the Angular and TypeScript teams have been doing. Angular 2 will leverage TypeScript heavily and you can as well in any type of JavaScript application (client-side or even server-side with Node.js). You can also use ES6 or ES5 with Angular 2 if you decide that TypeScript isn't for you. &lt;a href="http://twitter.com/andrewconnell" title="Andrew Connell" target="_blank"&gt;Andrew Connell&lt;/a&gt; and &lt;a href="http://twitter.com/danwahlin" title="Dan Wahlin" target="_blank"&gt;I&lt;/a&gt; gave a talk on TypeScript at ng-conf that you can view here if interested:&lt;/p&gt;
&lt;p&gt;&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/U7NYTKgkZgo?list=PLOETEcp3DkCoNnlhE-7fovYvqwVPrRiY7" frameborder="0" allowfullscreen=""&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;I've been a big fan of TypeScript for many years and decided to update a few previous posts I've done to help people get started with it. In this first post I'll talk about the basics of TypeScript and provide additional details about the language in future posts.&lt;/p&gt;
&lt;h4&gt;TypeScript Overview&lt;/h4&gt;
&lt;p&gt;Here&amp;rsquo;s what the TypeScript site (&lt;a href="http://typescriptlang.org"&gt;http://typescriptlang.org&lt;/a&gt;) says about TypeScript:&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;
&lt;h1 style="box-sizing: content-box; font-size: 18pt; margin: 0px auto; font-family: SegoeUILight, 'Segoe UI Light', SegoeUI, 'Segoe UI', arial, sans-serif; font-weight: normal; line-height: normal; color: #31859c; padding: 0px 25px; border: 0px; outline: 0px; vertical-align: baseline; font-stretch: normal; width: 765px; max-width: 765px;"&gt;TypeScript lets you write JavaScript the way you really want to.&lt;br style="box-sizing: border-box;" /&gt;TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.&amp;nbsp;Any browser. Any host. Any OS. Open Source.&lt;/h1&gt;
&lt;p&gt;&lt;br /&gt;TypeScript was created by Anders Hejlsberg (the creator of the C# language) and his team at Microsoft. To sum it up, TypeScript is a language based on ES6 standards that can be compiled to JavaScript. It isn&amp;rsquo;t a stand-alone language that&amp;rsquo;s completely separate from JavaScript&amp;rsquo;s roots though. It&amp;rsquo;s a superset of JavaScript which means that standard JavaScript code can be placed in a TypeScript file (a file with a .ts extension) and used directly. That&amp;rsquo;s a very important point/feature of the language since it means you can use existing JavaScript code and frameworks with TypeScript without having to do major code conversions to make it all work. Once a TypeScript file is saved it can be compiled to JavaScript using TypeScript&amp;rsquo;s tsc.exe compiler tool, by using a variety of editors/tools, or by using JavaScript task runners such as Grunt or Gulp.&lt;/p&gt;
&lt;p&gt;TypeScript offers several key features. First, it provides built-in static type support meaning that you define variables and function parameters as being &amp;ldquo;string&amp;rdquo;, &amp;ldquo;number&amp;rdquo;, &amp;ldquo;boolean&amp;rdquo;, and more to avoid incorrect types being assigned to variables or passed to functions. Second, TypeScript provides a way to write modular code by directly supporting ES6 class and module definitions and it even provides support for custom interfaces that can be used to drive consistency. Finally, TypeScript integrates with several different tools such as Brackets, Sublime Text, Emacs, Visual Studio, and Vi to provide syntax highlighting, code help, build support, and more depending on the editor. Find out more about editor support at &lt;a href="http://www.typescriptlang.org/#Download"&gt;http://www.typescriptlang.org/#Download&lt;/a&gt;. In addition to all of this, TypeScript supports much of ES6 (with more and more ES6 features being added in each release) and also includes support for concepts such as generics (code templates), interfaces, and more.&lt;/p&gt;
&lt;p&gt;TypeScript can also be used with existing JavaScript frameworks/libraries such as Angular, Node.js, jQuery, and others and even catch type issues and provide enhanced code help as you build your apps. Special &amp;ldquo;declaration&amp;rdquo; files that have a &lt;i&gt;d.ts&lt;/i&gt; extension are available for over 300 frameworks/libaries and with the latest announcement at ng-conf by the Angular and TypeScript teams I fully expect that number to go even higher. Visit &lt;a href="http://definitelytyped.org" target="_blank"&gt;http://definitelytyped.org&lt;/a&gt;&amp;nbsp;to access the different declaration files that can be used with tools to provide additional code help and ensure that a string isn&amp;rsquo;t passed to a parameter that expects a number. Although declaration files aren&amp;rsquo;t required, TypeScript&amp;rsquo;s support for declaration files makes it easier to catch issues upfront while working with existing libraries such as Angular and jQuery.&lt;/p&gt;
&lt;h4&gt;&lt;br /&gt;Getting Started with TypeScript&lt;/h4&gt;
&lt;p&gt;To get started learning TypeScript visit the TypeScript Playground available at &lt;a href="http://www.typescriptlang.org"&gt;http://www.typescriptlang.org&lt;/a&gt;. Using the playground editor you can experiment with TypeScript code, get code help as you type, and see the JavaScript that TypeScript generates once it&amp;rsquo;s compiled. Here&amp;rsquo;s an example of the TypeScript playground in action:&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/Figure1_42D258B4.png"&gt;&lt;img title="Figure1" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;" border="0" alt="Figure1" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/Figure1_thumb_3A6E835D.png" width="806" height="558" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;One of the first things that may stand out to you about the code shown above is that classes can be defined in TypeScript. This makes it easy to group related variables and functions into a container which helps tremendously with re-use and maintainability especially in enterprise-scale JavaScript applications. While you can certainly simulate classes using JavaScript patterns (note that ECMAScript 6 will support classes directly), TypeScript makes it quite easy especially if you come from an object-oriented programming background. An example of the Greeter class shown in the TypeScript Playground is shown next:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Greeter {
    greeting: &lt;span class="kwrd"&gt;string&lt;/span&gt;;

    constructor (message: &lt;span class="kwrd"&gt;string&lt;/span&gt;) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.greeting = message;
    }

    greet() {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;"Hello, "&lt;/span&gt; + &lt;span class="kwrd"&gt;this&lt;/span&gt;.greeting;
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Looking through the code you&amp;rsquo;ll notice that types can be defined on variables and parameters such as &lt;i&gt;greeting: string&lt;/i&gt;, that constructors can be defined, and that functions can be defined such as &lt;i&gt;greet()&lt;/i&gt;. The ability to define types is a key feature of TypeScript (and where its name comes from) that can help identify bugs upfront before even running the code. Many types are supported including primitive types like string, number, boolean, array, and null as well as object literals and more complex types such as HTMLInputElement (for an &amp;lt;input&amp;gt; tag). Custom types can be defined as well.&lt;/p&gt;
&lt;p&gt;The JavaScript output by compiling the TypeScript Greeter class is shown next:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; Greeter = (&lt;span class="kwrd"&gt;function&lt;/span&gt; () {
    &lt;span class="kwrd"&gt;function&lt;/span&gt; Greeter(message) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.greeting = message;
    }
    Greeter.prototype.greet = &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;"Hello, "&lt;/span&gt; + &lt;span class="kwrd"&gt;this&lt;/span&gt;.greeting;
    };
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Greeter;
})();&lt;/pre&gt;
&lt;p&gt;&lt;br /&gt;Notice that the code is using JavaScript prototyping and closures to simulate a Greeter class in JavaScript. The body of the code is wrapped with a self-invoking function to take the variables and functions out of the global JavaScript scope. This is important feature that helps avoid naming collisions between variables and functions.&lt;/p&gt;
&lt;p&gt;In cases where you&amp;rsquo;d like to wrap a class in a naming container (similar to a namespace or package in other languages) you can use TypeScript&amp;rsquo;s &lt;i&gt;module&lt;/i&gt; keyword. The following code shows an example of wrapping an AcmeCorp module around the Greeter class. In order to create a new instance of Greeter the module name must now be used. This can help avoid naming collisions that may occur with the Greeter class.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;module AcmeCorp {
    export &lt;span class="kwrd"&gt;class&lt;/span&gt; Greeter {
        greeting: &lt;span class="kwrd"&gt;string&lt;/span&gt;;

        constructor (message: &lt;span class="kwrd"&gt;string&lt;/span&gt;) {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.greeting = message;
        }

        greet() {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;"Hello, "&lt;/span&gt; + &lt;span class="kwrd"&gt;this&lt;/span&gt;.greeting;
        }
    }
}

&lt;span class="kwrd"&gt;var&lt;/span&gt; greeter = &lt;span class="kwrd"&gt;new&lt;/span&gt; AcmeCorp.Greeter(&lt;span class="str"&gt;"world"&lt;/span&gt;);&lt;/pre&gt;
&lt;p&gt;&lt;br /&gt;In addition to being able to define custom classes and modules in TypeScript, you can also take advantage of inheritance by using TypeScript&amp;rsquo;s &lt;i&gt;extends&lt;/i&gt; keyword. The following code shows an example of using inheritance to define two report objects:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Report {
    name: &lt;span class="kwrd"&gt;string&lt;/span&gt;;

    constructor (name: &lt;span class="kwrd"&gt;string&lt;/span&gt;) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.name = name;
    }

    print() {
        alert(&lt;span class="str"&gt;"Report: "&lt;/span&gt; + &lt;span class="kwrd"&gt;this&lt;/span&gt;.name);
    }
}

&lt;span class="kwrd"&gt;class&lt;/span&gt; FinanceReport extends Report {
    constructor (name: &lt;span class="kwrd"&gt;string&lt;/span&gt;) {
        super(name);
    }

    print() {
        alert(&lt;span class="str"&gt;"Finance Report: "&lt;/span&gt; + &lt;span class="kwrd"&gt;this&lt;/span&gt;.name);
    }

    getLineItems() {
        alert(&lt;span class="str"&gt;"5 line items"&lt;/span&gt;);
    }
}

&lt;span class="kwrd"&gt;var&lt;/span&gt; report = &lt;span class="kwrd"&gt;new&lt;/span&gt; FinanceReport(&lt;span class="str"&gt;"Month's Sales"&lt;/span&gt;);
report.print();
report.getLineItems();&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In this example a base Report class is defined that has a variable (name), a constructor that accepts a name parameter of type string, and a function named print(). The FinanceReport class inherits from Report by using TypeScript&amp;rsquo;s &lt;i&gt;extends&lt;/i&gt; keyword. As a result, it automatically has access to the print() function in the base class. In this example the FinanceReport overrides the base class&amp;rsquo;s print() method and adds its own. The FinanceReport class also forwards the name value it receives in the constructor to the base class using the &lt;i&gt;super()&lt;/i&gt; call.&lt;/p&gt;
&lt;p&gt;TypeScript also supports the creation of custom interfaces when you need to provide consistency across a set of objects and ensure that proper types are used. The following code shows an example of an interface named &lt;i&gt;Thing&lt;/i&gt; (from the TypeScript samples) and a class named &lt;i&gt;Plane&lt;/i&gt; that implements the interface to drive consistency across the app. Notice that the Plane class includes intersect and normal as a result of implementing the interface.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;interface&lt;/span&gt; Thing {
    intersect: (ray: Ray) =&amp;gt; Intersection;
    normal: (pos: Vector) =&amp;gt; Vector;
    surface: Surface;
}

&lt;span class="kwrd"&gt;class&lt;/span&gt; Plane implements Thing {
    normal: (pos: Vector) =&amp;gt;Vector;

    intersect: (ray: Ray) =&amp;gt;Intersection;

    constructor (norm: Vector, offset: number, &lt;span class="kwrd"&gt;public&lt;/span&gt; surface: Surface) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.normal = &lt;span class="kwrd"&gt;function&lt;/span&gt; (pos: Vector) { &lt;span class="kwrd"&gt;return&lt;/span&gt; norm; }
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.intersect = &lt;span class="kwrd"&gt;function&lt;/span&gt; (ray: Ray): Intersection {
            &lt;span class="kwrd"&gt;var&lt;/span&gt; denom = Vector.dot(norm, ray.dir);
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (denom &amp;gt; 0) {
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;
            } &lt;span class="kwrd"&gt;else&lt;/span&gt; {
                &lt;span class="kwrd"&gt;var&lt;/span&gt; dist = (Vector.dot(norm, ray.start) + offset) / (-denom);
                &lt;span class="kwrd"&gt;return&lt;/span&gt; { thing: &lt;span class="kwrd"&gt;this&lt;/span&gt;, ray: ray, dist: dist };
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;At first glance it doesn&amp;rsquo;t appear that the surface member is implemented in Plane but it&amp;rsquo;s actually included automatically due to the &lt;i&gt;public surface: Surface&lt;/i&gt; parameter in the constructor. Adding &lt;i&gt;public varName: Type&lt;/i&gt; to a constructor automatically adds a typed variable into the class without having to explicitly write the code as with &lt;i&gt;normal&lt;/i&gt; and &lt;i&gt;intersect&lt;/i&gt;.&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;TypeScript has many additional language features but defining types and creating classes, modules, and interfaces are some of the key features it offers. I'll be covering additional features in future posts so stay tuned. Subscribe to my Web Weekly newsletter (at the top of the blog or below) to stay up-to-date on all of the latest technology that I find and write about.&lt;/p&gt;</description><pubDate>Sun, 08 Mar 2015 16:38:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/getting-started-with-typescript-classes-static-types-and-interfaces</guid><category>HTML5</category><category>JavaScript</category><category>TypeScript</category><category>Angular</category></item><item><title>The AngularJS Custom Directives Video Training Course Has Been Released!</title><link>https://weblogs.asp.net:443/dwahlin/the-angularjs-custom-directives-video-training-course-has-been-released</link><description>&lt;p&gt;&lt;a href="https://www.udemy.com/angularjs-custom-directives/" target="_blank"&gt;&lt;img title="CourseLogoSuperHero" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border: 0px;" border="0" alt="CourseLogoSuperHero" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/AngularJS-Custom-Directives-Video-Course_B732/CourseLogoSuperHero_3.jpg" width="500" height="281" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;m excited to announce that my new &lt;a href="https://www.udemy.com/angularjs-custom-directives/" target="_blank"&gt;AngularJS Custom Directives&lt;/a&gt; video training course has been released on Udemy.com! If you&amp;rsquo;ve been wanting to dive deeper into AngularJS directives and understand how they work while also clarifying terms such as isolate scope, transclusion, linking, and much more then this is the course for you. If you enjoyed my &lt;a href="http://tinyurl.com/AngularJSJumpStart" target="_blank"&gt;AngularJS JumpStart&lt;/a&gt; course or my &lt;a href="http://weblogs.asp.net/dwahlin/video-tutorial-angularjs-fundamentals-in-60-ish-minutes" target="_blank"&gt;AngularJS in 60ish Minutes&lt;/a&gt; video on YouTube then I guarantee you&amp;rsquo;ll love this course.&lt;/p&gt;
&lt;p&gt;The first 2 modules of the course are available to &lt;a href="https://www.udemy.com/angularjs-custom-directives/?couponCode=ajsd-29bucks#/" target="_blank"&gt;view absolutely free&lt;/a&gt; so that you can check it out. Here&amp;rsquo;s an additional free video from the Isolate Scope section in Module 3 of the course.&lt;/p&gt;
&lt;h2&gt;Understanding Shared and Isolate Scope&lt;/h2&gt;
&lt;p&gt;&lt;br /&gt;&lt;iframe width="640" height="480" src="https://www.youtube.com/embed/P4JnEqlnLnE" frameborder="0" allowfullscreen="allowfullscreen"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;!--&lt;h2&gt;&lt;br /&gt;Win a FREE Copy!&lt;/h2&gt;
&lt;p&gt;&lt;br /&gt;The course includes over 4+ hours of videos and tons of source code that you can follow along with during the videos. If you&amp;rsquo;re interested in a chance to win a free copy of the course select one of the following options or do both to be entered twice!&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Sign-up for the Web Weekly newsletter (sign-up at the top of my blog). I&amp;rsquo;ll randomly pick winners from the subscribers.&lt;/li&gt;
&lt;li&gt;Follow &lt;a href="https://twitter.com/danwahlin" target="_blank"&gt;@DanWahlin&lt;/a&gt; on Twitter and click the tweet button below to tweet a message about the AngularJS Custom Directives course using hash tag #angularjsdirectives. I&amp;rsquo;ll randomly pick winners from the list of tweets that use the hash tag and send the message.&lt;/li&gt;
&lt;/ol&gt;
&lt;div id="custom-tweet-button"&gt;&lt;a href="https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Fweblogs.asp.net/dwahlin&amp;amp;text=RT%20for%20a%20chance%20to%20win%20a%20free%20copy%20of%20the%20new%20AngularJS%20Custom%20Directives%20course%20by%20%40DanWahlin!%20%20%23angularjsdirectives&amp;amp;tw_p=tweetbutton&amp;amp;url=https://www.udemy.com/angularjs-custom-directives" target="_blank"&gt;Tweet&lt;/a&gt;&lt;/div&gt;
--&gt;
&lt;div&gt;&amp;nbsp;&lt;/div&gt;
&lt;h2&gt;AngularJS Custom Directives Course Overview&lt;/h2&gt;
&lt;p&gt;&lt;br /&gt;Are you interested in learning how to take your AngularJS skills to the next level? Have you been confused by terms like tranclusion, isolate scope, interpolation, local scope properties, and more? Have you wanted to build custom directives but didn't know where to start? Look no further than the &lt;a href="https://www.udemy.com/angularjs-custom-directives/" target="_blank"&gt;AngularJS Custom Directives&lt;/a&gt; course!&lt;/p&gt;
&lt;p&gt;Throughout this course you'll be provided with a step-by-step look at the process of creating custom directives and cover key concepts that you need to know to take your AngularJS skills to the next level. Topics such as the $compile service, the directive definition object (DDO), the link() function, isolate scope, controller integration, transclusion, working with the $interpolate service, $asyncValidators, and much more are covered as well as techniques for structuring AngularJS directive code.&lt;/p&gt;
&lt;p&gt;In addition to expert instruction by AngularJS &lt;a href="https://developers.google.com/experts/people/dan-wahlin" target="_blank"&gt;Google Developer Expert&lt;/a&gt; (GDE) Dan Wahlin you'll also be provided with hands-on code samples that you can follow along with at your own pace. Just pause or rewind the video if you need to see the code again or jump right to the end solution that's provided if you'd like. Begin and end code is provided so that you can maximize your learning and become an expert in building directives!&lt;/p&gt;
&lt;p&gt;The modules covered in the course include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Getting Started with Directives&lt;/li&gt;
&lt;li&gt;Shared and Isolate Scope&lt;/li&gt;
&lt;li&gt;The Link Function&lt;/li&gt;
&lt;li&gt;Using Controllers in Directives&lt;/li&gt;
&lt;li&gt;Bonus Content (several robust directive examples)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Many additional details are provided throughout the modules including coverage of the $parse and $interpolate services, how controllers and the link function can be used in concert, why and how to use transclusion to merge custom content, pros and cons of available coding approaches for custom directives, techniques for passing parameter data to functions when using local scope properties, and much, much more.&lt;/p&gt;
&lt;p&gt;View a complete list of &lt;a href="https://www.udemy.com/angularjs-custom-directives/" target="_blank"&gt;topics covered here&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&amp;nbsp;&lt;/div&gt;</description><pubDate>Sun, 22 Feb 2015 15:00:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/the-angularjs-custom-directives-video-training-course-has-been-released</guid><category>angularjs</category><category>directives</category><category>javascript</category><category>SPA</category><category>patterns</category><category>Udemy</category></item><item><title>Adding Azure Active Directory and OWIN Code into an AngularJS/ASP.NET MVC Application to Handle User Authentication</title><link>https://weblogs.asp.net:443/dwahlin/adding-azure-active-directory-and-owin-code-into-an-angularjs-asp-net-mvc-application-to-handle-user-authentication</link><description>&lt;p&gt;In a &lt;a href="http://www.itunity.com/article/integrating-aad-services-angularjs-office-365-part-3-770" target="_blank"&gt;previous post&lt;/a&gt; I discussed how to setup the necessary configuration code and assemblies in an AngularJS/ASP.NET MVC application in order to authenticate users against &lt;a href="http://azure.microsoft.com/en-us/services/active-directory/" target="_blank"&gt;Azure Active Directory&lt;/a&gt; (AAD). Once the initial configuration is complete you can write code to redirect users to the AAD login screen to retrieve an ID token. &lt;/p&gt; &lt;p&gt;In Part 4 of an article series I’m writing for &lt;a href="http://itunity.com"&gt;http://itunity.com&lt;/a&gt; I discuss the necessary code that’s required to authenticate a user and retrieve the ID token. Additional topics covered include hooking AAD into the ASP.NET MVC pipeline, creating an Entity Framework token cache, triggering authentication against AAD in MVC controllers, and more. Here’s an excerpt from the article. The complete code for the application discussed in the article series can be found on the &lt;a href="https://github.com/OfficeDev/SP-AngularJS-ExpenseManager-Code-Sample" target="_blank"&gt;OfficeDev Github site&lt;/a&gt;.&lt;br&gt;&lt;/p&gt; &lt;h2&gt;Adding AAD Configuration and Assemblies into an Application&lt;/h2&gt; &lt;p&gt;&lt;a href="http://www.itunity.com/article/integrating-aad-services-angularjs-office-365-part-3-770"&gt;Part 3&lt;/a&gt; of this series covered how to access the Client ID, Key, and Tenant ID values from Azure Active Directory (AAD) and add them into web.config. It also showed how to get the necessary AAD and OWIN NuGet packages in place and create a &lt;em&gt;SettingsHelper&lt;/em&gt; class to simplify the process of accessing web.config values.  &lt;p&gt;In this article, you’ll see how the values defined in web.config can be used to associate a custom application with AAD. Topics covered include setting up a token storage cache, hooking AAD code into the OWIN startup process, and creating an ASP.NET MVC controller to display a login page to end users and handle directing them to the application upon successful authentication. All of the code that follows is from the &lt;a href="https://github.com/OfficeDev/SP-AngularJS-ExpenseManager-Code-Sample"&gt;Expense Manager application&lt;/a&gt; that’s available on the OfficeDev GitHub site.  &lt;p&gt;Let’s kick things off by looking at AAD token storage and the role it plays in applications.&lt;br&gt; &lt;h3&gt;AAD Token Storage&lt;/h3&gt; &lt;p&gt;The NuGet packages added into the application (see &lt;a href="http://www.itunity.com/article/integrating-aad-services-angularjs-office-365-part-3-770"&gt;Part 3&lt;/a&gt; of this series) provide the necessary functionality to authenticate a user with AAD. Once authenticated, AAD will return an ID token that can be stored by the application and used as secured resources such as Web API, Office 365 APIs, or other resources are accessed. The AAD documentation provides a diagram that sums up the overall authentication workflow well:&lt;br&gt; &lt;p&gt;&lt;a href="http://www.itunity.com/content/content/771/wahlin_fig1.png"&gt;&lt;img style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; padding-right: 0px; border-top-width: 0px" border="0" alt="The flow as a user logs into AAD, gets an ID token, and then accesses an application and additional resources" src="http://www.itunity.com/content/content/771/wahlin_fig1.png?w=550"&gt;&lt;/a&gt;  &lt;p&gt;&lt;br&gt;Figure 1. The flow as a user logs into AAD, gets an ID token, and then accesses an application and additional resources. This image is from &lt;a href="http://msdn.microsoft.com/en-us/library/azure/dn499820.aspx"&gt;http://msdn.microsoft.com/en-us/library/azure/dn499820.aspx&lt;/a&gt;.  &lt;p&gt;&amp;nbsp; &lt;p&gt;While the token received by the application can be stored in memory during development, it’s recommended that a more robust token store be put in place to handle that task for production. You can find several sample applications that integrate with AAD and handle tokens on the &lt;a href="https://github.com/AzureADSamples"&gt;Azure Active Directory Github samples site&lt;/a&gt;. Some of the samples use an in-memory store while others rely on a database, which is recommended when an app is ready to move to production.  &lt;p&gt;In this part of the article, you’ll see the steps required to get an Entity Framework and SQL Server token store in place. If you don’t already have the Entity Framework NuGet package installed in your project you’ll need to install it.  &lt;p&gt;From a high level, the following tasks will be discussed:  &lt;ol&gt; &lt;li&gt;Create a model class named &lt;em&gt;PerWebUserCache&lt;/em&gt; that’s used to define properties that are needed to store and retrieve AAD tokens.  &lt;li&gt;Create an Entity Framework DbContext class named &lt;em&gt;EFADALContext&lt;/em&gt; that interacts with a SQL Server database.  &lt;li&gt;Create a token cache class named &lt;em&gt;EFADALTokenCache&lt;/em&gt; that uses the context class to store and retrieve tokens from a SQL Server database.  &lt;li&gt;Add startup code that uses the previous classes and is responsible for handling authentication as a user requests a secure resource.&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;To get started, add a new class named &lt;em&gt;PerWebUserCache.cs&lt;/em&gt; into the &lt;em&gt;Models&lt;/em&gt; folder of an ASP.NET MVC application. This code defines properties that will be used by the token store. Add the following code into the class:&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.ComponentModel.DataAnnotations;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; ExpenseManager.Models
{
   &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PerWebUserCache
   {
       [Key]
       &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; EntryId { get; set; }
       &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; webUserUniqueId { get; set; }
       &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt;[] cacheBits { get; set; }
       &lt;span class="kwrd"&gt;public&lt;/span&gt; DateTime LastWrite { get; set; }
   }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;p&gt;&lt;br&gt;Listing 1. The PerWebUserCache model class defines properties that will be used by the token store.&lt;br&gt;
&lt;p&gt;Now add a class named &lt;em&gt;EFADALContext.cs&lt;/em&gt; into the &lt;em&gt;Utils&lt;/em&gt; folder. This class will derive from Entity Framework’s &lt;em&gt;DbContext&lt;/em&gt; class and handle mapping the &lt;em&gt;PerWebUserCache&lt;/em&gt; object to the proper table in SQL Server. Add the following code into the &lt;em&gt;EFADALContext&lt;/em&gt; class: &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; ExpenseManager.Models;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Data.Entity;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Data.Entity.ModelConfiguration.Conventions;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; ExpenseManager.Utils
{
   &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; EFADALContext : DbContext
   {
       &lt;span class="kwrd"&gt;public&lt;/span&gt; EFADALContext() : &lt;span class="kwrd"&gt;base&lt;/span&gt;(&lt;span class="str"&gt;"EFADALContext"&lt;/span&gt;)
       {
       }
       &lt;span class="kwrd"&gt;public&lt;/span&gt; DbSet&amp;lt;PerWebUserCache&amp;gt; PerUserCacheList { get; set; }
       &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnModelCreating(DbModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove&amp;lt;PluralizingTableNameConvention&amp;gt;();
       }
   }
}&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;Listing 2. The EFADALContext class handles table creation and queries with SQL Server.&lt;br&gt;
&lt;p&gt;Now that the model and database context classes have been created, a token cache class named &lt;em&gt;EFADALTokenCache&lt;/em&gt; can be created that uses the context to store and retrieve AAD tokens. This is one of many &lt;a href="https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet/blob/master/TodoListWebApp%2FDAL%2FEFADALTokenCache.cs"&gt;classes&lt;/a&gt; provided by the AAD samples site on GitHub that was mentioned earlier. 
&lt;p&gt;Add a class named &lt;em&gt;EFADALTokenCache.c&lt;/em&gt;s into the &lt;em&gt;Utils&lt;/em&gt; folder that has the following code in it: &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; Microsoft.IdentityModel.Clients.ActiveDirectory;
&lt;span class="kwrd"&gt;using&lt;/span&gt; ExpenseManager.Models;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Data.Entity;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; ExpenseManager.Utils
{
   &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; EFADALTokenCache : TokenCache
   {
       &lt;span class="kwrd"&gt;private&lt;/span&gt; EFADALContext _Context = &lt;span class="kwrd"&gt;new&lt;/span&gt; EFADALContext();
       &lt;span class="kwrd"&gt;string&lt;/span&gt; User;
       PerWebUserCache Cache;

       &lt;span class="rem"&gt;// constructor&lt;/span&gt;
       &lt;span class="kwrd"&gt;public&lt;/span&gt; EFADALTokenCache(&lt;span class="kwrd"&gt;string&lt;/span&gt; user)
       {
           &lt;span class="rem"&gt;// associate the cache to the current user of the web app&lt;/span&gt;
           User = user;
           &lt;span class="kwrd"&gt;this&lt;/span&gt;.AfterAccess = AfterAccessNotification;
           &lt;span class="kwrd"&gt;this&lt;/span&gt;.BeforeAccess = BeforeAccessNotification;
           &lt;span class="kwrd"&gt;this&lt;/span&gt;.BeforeWrite = BeforeWriteNotification;

           &lt;span class="rem"&gt;// look up the entry in the DB&lt;/span&gt;
           Cache = _Context.PerUserCacheList.FirstOrDefault(c =&amp;gt; 
                    c.webUserUniqueId == User);
           &lt;span class="rem"&gt;// place the entry in memory&lt;/span&gt;
           &lt;span class="kwrd"&gt;this&lt;/span&gt;.Deserialize((Cache == &lt;span class="kwrd"&gt;null&lt;/span&gt;) ? &lt;span class="kwrd"&gt;null&lt;/span&gt; : Cache.cacheBits);
       }

       &lt;span class="rem"&gt;// clean up the DB&lt;/span&gt;
       &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Clear()
       {
           &lt;span class="kwrd"&gt;base&lt;/span&gt;.Clear();
           &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var cacheEntry &lt;span class="kwrd"&gt;in&lt;/span&gt; _Context.PerUserCacheList)
               _Context.PerUserCacheList.Remove(cacheEntry);
           _Context.SaveChanges();
       }

       &lt;span class="rem"&gt;// Notification raised before ADAL accesses the cache.&lt;/span&gt;
       &lt;span class="rem"&gt;// This is your chance to update the in-memory copy from the DB&lt;/span&gt;
       &lt;span class="rem"&gt;// if the in-memory version is stale.&lt;/span&gt;
       &lt;span class="kwrd"&gt;void&lt;/span&gt; BeforeAccessNotification(TokenCacheNotificationArgs args)
       {
           &lt;span class="kwrd"&gt;if&lt;/span&gt; (Cache == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
           {
               &lt;span class="rem"&gt;// first time access&lt;/span&gt;
               Cache = _Context.PerUserCacheList.FirstOrDefault(c =&amp;gt; 
                        c.webUserUniqueId == User);
           }
           &lt;span class="kwrd"&gt;else&lt;/span&gt;
           {   &lt;span class="rem"&gt;// retrieve last write from the DB&lt;/span&gt;
               var status = from e &lt;span class="kwrd"&gt;in&lt;/span&gt; _Context.PerUserCacheList
                            &lt;span class="kwrd"&gt;where&lt;/span&gt; (e.webUserUniqueId == User)
                            select &lt;span class="kwrd"&gt;new&lt;/span&gt;
                            {
                                LastWrite = e.LastWrite
                            };
               &lt;span class="rem"&gt;// if the in-memory copy is older than the persistent copy&lt;/span&gt;
               &lt;span class="kwrd"&gt;if&lt;/span&gt; (status.First().LastWrite &amp;gt; Cache.LastWrite)

               &lt;span class="rem"&gt;// read from from storage, update in-memory copy&lt;/span&gt;
               {
                   Cache = _Context.PerUserCacheList.FirstOrDefault(
                            c =&amp;gt; c.webUserUniqueId == User);
               }
           }
           &lt;span class="kwrd"&gt;this&lt;/span&gt;.Deserialize((Cache == &lt;span class="kwrd"&gt;null&lt;/span&gt;) ? &lt;span class="kwrd"&gt;null&lt;/span&gt; : Cache.cacheBits);
       }

       &lt;span class="rem"&gt;// Notification raised after ADAL accessed the cache.&lt;/span&gt;
       &lt;span class="rem"&gt;// If the HasStateChanged flag is set, ADAL changed the content of the cache&lt;/span&gt;
       &lt;span class="kwrd"&gt;void&lt;/span&gt; AfterAccessNotification(TokenCacheNotificationArgs args)
       {
           &lt;span class="rem"&gt;// if state changed&lt;/span&gt;
           &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;this&lt;/span&gt;.HasStateChanged)
           {
               Cache = &lt;span class="kwrd"&gt;new&lt;/span&gt; PerWebUserCache
               {
                   webUserUniqueId = User,
                   cacheBits = &lt;span class="kwrd"&gt;this&lt;/span&gt;.Serialize(),
                   LastWrite = DateTime.Now
               };

               &lt;span class="rem"&gt;// update the DB and the lastwrite                &lt;/span&gt;
               _Context.Entry(Cache).State = Cache.EntryId == 0 ? 
                  EntityState.Added : EntityState.Modified;
               _Context.SaveChanges();
               &lt;span class="kwrd"&gt;this&lt;/span&gt;.HasStateChanged = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
           }
       }
       &lt;span class="kwrd"&gt;void&lt;/span&gt; BeforeWriteNotification(TokenCacheNotificationArgs args)
       {
           &lt;span class="rem"&gt;// if you want to ensure that no concurrent write takes place, &lt;/span&gt;
           &lt;span class="rem"&gt;// use this notification to place a lock on the entry&lt;/span&gt;
       }
   }
}&lt;/pre&gt;&lt;font face="Courier New"&gt;&lt;br&gt;&lt;/font&gt;
&lt;p&gt;Listing 3. The EFADALTokenCache class is responsible for storing and retrieving AAD tokens used by the application.&lt;br&gt;
&lt;p&gt;This code handles managing an in-memory store that is backed by a database. As changes are made or the local cache becomes stale, calls are made to update the proper fields in the database. With the EFADALTokenCache class in place along with the model and database context classes, it’s now time to add AAD code in the application to allow users to be authenticated. This code will tie AAD into OWIN so that any secured application resources trigger the authentication process. 
&lt;p&gt;Read the full article at &lt;a title="http://www.itunity.com/article/integrating-angularjs-azure-active-directory-services-office-365sharepoint-part-4-771" href="http://www.itunity.com/article/integrating-angularjs-azure-active-directory-services-office-365sharepoint-part-4-771"&gt;http://www.itunity.com/article/integrating-angularjs-azure-active-directory-services-office-365sharepoint-part-4-771&lt;/a&gt;. 
</description><pubDate>Mon, 26 Jan 2015 00:40:07 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/adding-azure-active-directory-and-owin-code-into-an-angularjs-asp-net-mvc-application-to-handle-user-authentication</guid><category>.NET</category><category>ActiveDirectory</category><category>Azure</category><category>AngularJS</category><category>Office365</category><category>JavaScript</category><category>Cloud</category><category>SPA</category></item><item><title>Adding Azure Active Directory Configuration Code and Assemblies into an AngularJS/ASP.NET MVC Application</title><link>https://weblogs.asp.net:443/dwahlin/adding-azure-active-directory-configuration-code-and-assemblies-into-an-asp-net-web-application</link><description>&lt;p&gt;In a &lt;a href="http://weblogs.asp.net/dwahlin/registering-a-custom-angularjs-application-with-azure-active-directory" target="_blank"&gt;previous post&lt;/a&gt; I discussed the process for registering an application with &lt;a href="http://azure.microsoft.com/en-us/services/active-directory/" target="_blank"&gt;Azure Active Directory&lt;/a&gt; (AAD) so that users can be authenticated. AAD supports a wide range of features that can be used to perform authentication, authorization, and claims-based security tasks. &lt;/p&gt; &lt;p&gt;Once an application has been registered with AAD you’ll need to add configuration code into the application’s web.config file, add related NuGet packages, and add custom C# code into the application in order to take advantage of AAD authentication functionality. In Part 3 of an article series I’m writing for &lt;a href="http://itunity.com"&gt;http://itunity.com&lt;/a&gt; I discuss these tasks and walk-through the complete process. Here’s an excerpt from the article.&lt;br&gt;&lt;/p&gt; &lt;h2&gt;Integrating AngularJS with Azure Active Directory and Office 365/SharePoint, Part 3 – Adding AAD Configuration and Assemblies into an Application&lt;/h2&gt; &lt;p&gt;You can choose from many different techniques to authenticate users in an application. You can build a custom solution using a file or database, you can use Active Directory, you can deploy a third-party solution, or you can use a cloud-based service, to name just a few. Every situation is unique so the authentication choice made really depends upon the requirements of the application. In cases where an application can be used from a variety of locations and devices, a cloud-based authentication solution can work quite well.&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.itunity.com/article/integrating-angularjs-o365-aad-registering-custom-app-720" target="_blank"&gt;Part 2&lt;/a&gt; of this article series showed the process for registering an application with the &lt;a href="http://azure.microsoft.com/en-us/services/active-directory/" target="_blank"&gt;Azure Active Directory&lt;/a&gt; (AAD) cloud service. Once you’ve registered an application, you can configure the Client ID and key created in AAD in your custom application. You can then add AAD assemblies to provide authentication functionality.&lt;/p&gt; &lt;p&gt;In this article, I’ll discuss how to get the necessary configuration and assemblies in place to tie the AngularJS Expense Manager application discussed in &lt;a href="http://www.itunity.com/article/integrating-angularjs-aad-office-365sharepoint-part-1-622" target="_blank"&gt;Part 1&lt;/a&gt; to AAD so that users can authenticate into Office 365 services. In Part 4 I will provide a walk-through of the code that needs to be added into the application to enable user authentication with AAD.&lt;/p&gt; &lt;p&gt;Let’s start by discussing the assemblies that need to be installed into the application and how you can simplify that process by using NuGet.&lt;br&gt;&lt;/p&gt; &lt;h3&gt;Installing the required assemblies using NuGet&lt;/h3&gt; &lt;p&gt;Once an application has been registered with AAD (refer to the Part 2 article for step-by-step details on doing that) you can begin the process of integrating AAD authentication into the application. To get started, you’ll need to add several assemblies into your project including some AAD-specific assemblies as well as OWIN assemblies. The AAD assemblies will be used to communicate with AAD while the OWIN assemblies will be used to hook AAD authentication into the custom application. Here’s a step-by-step walkthrough of getting the assemblies into a project.&lt;/p&gt; &lt;p&gt;Create a new ASP.NET MVC application in Visual Studio (the sample application is named “ExpenseManager”). Now select Tools → NuGet Package Manager → Package Manager Console from the Visual Studio menu.&lt;/p&gt; &lt;p&gt;Once the Package Manager Console is open, run the following commands in it to get the necessary assemblies into place as shown in Figure 1.&lt;br&gt;&lt;/p&gt; &lt;p&gt;&lt;img alt="Use NuGet to install the AAD assemblies to communicate with AAD and the OWIN assemblies to hook AAD authentication into the custom application" src="http://www.itunity.com/content/content/770/wahlin_fig1.png?w=550"&gt;&lt;/p&gt; &lt;p&gt;Figure 1. Installing NuGet packages using the Package Manager Console.&lt;br&gt;&lt;/p&gt; &lt;p&gt;Type each of the following commands into the command-prompt area and press Enter to install the specific Nuget package:&lt;/p&gt; &lt;p&gt;Install-Package -Id Microsoft.Owin.Host.SystemWeb&lt;br&gt;Install-Package -Id Microsoft.Owin.Security.Cookies&lt;br&gt;Install-Package -Id Microsoft.Owin.Security.OpenIdConnect&lt;br&gt;Install-Package -Id Microsoft.IdentityModel.Clients.ActiveDirectory&lt;/p&gt; &lt;p&gt;&lt;br&gt;After installing the Nuget packages, open the References node in the Solution Explorer and note that several new assemblies have been added that are related to AAD and authentication. Figures 2 and 3 show a few of the assemblies that are added:&lt;br&gt;&lt;/p&gt; &lt;p&gt;&lt;img alt="AAD-specific assemblies used to communicate with AAD" src="http://www.itunity.com/content/content/770/wahlin_fig2.png"&gt;&lt;/p&gt; &lt;p&gt;Figure 2. Assemblies related to AAD.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;img alt="OWIN assemblies used to hook AAD authentication into the custom application" src="http://www.itunity.com/content/content/770/wahlin_fig3.png"&gt;&lt;/p&gt; &lt;p&gt;Figure 3. OWIN assemblies.&lt;/p&gt; &lt;p&gt;Now that the essential assemblies are installed, it’s time to add the application’s AAD Client ID and Key into the application. These values are needed to “hook” the application to AAD.&lt;/p&gt; &lt;p&gt;Note that all of the code that follows is from the Expense Manager application that’s available on the &lt;a href="https://github.com/OfficeDev/SP-AngularJS-ExpenseManager-Code-Sample" target="_blank"&gt;OfficeDev GitHub site&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Read the full article at &lt;a title="http://www.itunity.com/article/integrating-aad-services-angularjs-office-365-part-3-770" href="http://www.itunity.com/article/integrating-aad-services-angularjs-office-365-part-3-770"&gt;http://www.itunity.com/article/integrating-aad-services-angularjs-office-365-part-3-770&lt;/a&gt;. &lt;/p&gt;</description><pubDate>Mon, 26 Jan 2015 00:20:28 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/adding-azure-active-directory-configuration-code-and-assemblies-into-an-asp-net-web-application</guid><category>.NET</category><category>ActiveDirectory</category><category>Azure</category><category>AngularJS</category><category>Office365</category><category>JavaScript</category><category>Cloud</category><category>SPA</category></item><item><title>Creating Custom AngularJS Directives Part 6 - Using Controllers</title><link>https://weblogs.asp.net:443/dwahlin/creating-custom-angularjs-directives-part-6-using-controllers</link><description>&lt;img src="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/AngularJS_thumb_1008B166.jpg"&gt; &lt;script type="text/javascript"&gt;// &lt;![CDATA[
document.write(getHtmlFragment('angularjsGetStarted'));
// ]]&gt;&lt;/script&gt; &lt;h2&gt;&lt;br&gt;Creating Custom AngularJS Directives Series&lt;/h2&gt;&lt;script type="text/javascript"&gt;// &lt;![CDATA[
document.write(getHtmlFragment('customDirectivesLinks'));
// ]]&gt;&lt;/script&gt; &lt;p&gt;Up to this point in the AngularJS directives series you’ve learned about many key aspects of directives but haven’t seen anything about how controllers fit into the picture. Although controllers are typically associated with routes and views, they can also be embedded in AngularJS directives. In fact, there are many scenarios where custom directives can take advantage of controllers to minimize code and simplify maintenance. While using controllers in directives is certainly optional, if you’d prefer to build directives using similar techniques that you use now to build views then you’ll find controllers are essential in many cases. By using controllers, directives start to feel like “child views”.&lt;/p&gt; &lt;p&gt;In this post I’ll walk through the process of integrating controllers into directives and show the role that they can play. Let’s start off by looking at a directive that doesn’t use a&amp;nbsp; controller and talk through the pros and cons of the approach.&lt;br&gt;&lt;br&gt;&lt;/p&gt; &lt;h2&gt;A Directive without a Controller&lt;/h2&gt; &lt;p&gt;&lt;br&gt;Directives provide several different ways to render HTML, collect data, and perform additional tasks. In situations where a directive is performing a lot of DOM manipulation, using the &lt;strong&gt;link&lt;/strong&gt; function makes sense.&amp;nbsp; Here’s a simple example of the &lt;strong&gt;link&lt;/strong&gt; function in action:&lt;br&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {

  &lt;span class="kwrd"&gt;var&lt;/span&gt; app = angular.module(&lt;span class="str"&gt;'directivesModule'&lt;/span&gt;);

  app.directive(&lt;span class="str"&gt;'domDirective'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
      &lt;span class="kwrd"&gt;return&lt;/span&gt; {
          restrict: &lt;span class="str"&gt;'A'&lt;/span&gt;,
          link: &lt;span class="kwrd"&gt;function&lt;/span&gt; ($scope, element, attrs) {
              element.on(&lt;span class="str"&gt;'click'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
                  element.html(&lt;span class="str"&gt;'You clicked me!'&lt;/span&gt;);
              });
              element.on(&lt;span class="str"&gt;'mouseenter'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
                  element.css(&lt;span class="str"&gt;'background-color'&lt;/span&gt;, &lt;span class="str"&gt;'yellow'&lt;/span&gt;);
              });
              element.on(&lt;span class="str"&gt;'mouseleave'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
                  element.css(&lt;span class="str"&gt;'background-color'&lt;/span&gt;, &lt;span class="str"&gt;'white'&lt;/span&gt;);
              });
          }
      };
  });

}());&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Adding a controller into this directive doesn’t make much sense given that the goal is to handle events and manipulate the DOM. Although it would be possible to accomplish the same task using a view in the directive (along with built-in AngularJS directives such as ng-click) and controller there’s really no reason to add a controller into this directive if DOM manipulation is the overall end goal.&lt;/p&gt;
&lt;p&gt;In cases where you’re manipulating the DOM, integrating data into the generated HTML, handling events, and more, adding a controller can minimize the amount of code you write and simplify the overall process in some cases. To make this more clear, let’s look at an example of a directive then renders a list of items and provides a button that can be used to add items to the list. Here’s the simple output that the directive renders:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Creating-Custom-AngularJS-Directives-Par_D3AB/image_thumb%5B2%5D_2.png"&gt;&lt;img title="image_thumb[2]" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image_thumb[2]" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/Creating-Custom-AngularJS-Directives-Par_D3AB/image_thumb%5B2%5D_thumb.png" width="163" height="127"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;There are several different ways to handle rendering this type of UI. A typical DOM-centric approach would use the &lt;strong&gt;link&lt;/strong&gt; function to handle everything as shown in the following directive. Keep in mind there are many ways to do this and the overall goal is to demonstrate DOM-centric code (as simply as possible):&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="csharpcode"&gt;(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {

  &lt;span class="kwrd"&gt;var&lt;/span&gt; app = angular.module(&lt;span class="str"&gt;'directivesModule'&lt;/span&gt;);

  app.directive(&lt;span class="str"&gt;'isolateScopeWithoutController'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
      
      &lt;span class="kwrd"&gt;var&lt;/span&gt; link = &lt;span class="kwrd"&gt;function&lt;/span&gt; (scope, element, attrs) {
              
              &lt;span class="rem"&gt;//Create a copy of the original data that’s passed in              &lt;/span&gt;
              &lt;span class="kwrd"&gt;var&lt;/span&gt; items = angular.copy(scope.datasource);
              
              &lt;span class="kwrd"&gt;function&lt;/span&gt; init() {
                  &lt;span class="kwrd"&gt;var&lt;/span&gt; html = &lt;span class="str"&gt;'&amp;lt;button id="addItem"&amp;gt;Add Item&amp;lt;/button&amp;gt;&amp;lt;div&amp;gt;&amp;lt;/div&amp;gt;'&lt;/span&gt;;
                  element.html(html);
                  
                  element.on(&lt;span class="str"&gt;'click'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt;(&lt;span class="kwrd"&gt;event&lt;/span&gt;) {
                      &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;event&lt;/span&gt;.srcElement.id === &lt;span class="str"&gt;'addItem'&lt;/span&gt;) {
                          addItem();
                          &lt;span class="kwrd"&gt;event&lt;/span&gt;.preventDefault();
                      }
                  });
              }
              
              &lt;span class="kwrd"&gt;function&lt;/span&gt; addItem() {
                  &lt;span class="rem"&gt;//Call external function passed in with &amp;amp;&lt;/span&gt;
                  scope.add();

                  &lt;span class="rem"&gt;//Add new customer to the local collection&lt;/span&gt;
                  items.push({
                      name: &lt;span class="str"&gt;'New Directive Customer'&lt;/span&gt;
                  });
                  
                  render();
              }
              
              &lt;span class="kwrd"&gt;function&lt;/span&gt; render() {
                  &lt;span class="kwrd"&gt;var&lt;/span&gt; html = &lt;span class="str"&gt;'&amp;lt;ul&amp;gt;'&lt;/span&gt;;
                  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;var&lt;/span&gt; i=0,len=items.length;i&amp;lt;len;i++) {
                      html += &lt;span class="str"&gt;'&amp;lt;li&amp;gt;'&lt;/span&gt; + items[i].name + &lt;span class="str"&gt;'&amp;lt;/li&amp;gt;'&lt;/span&gt;
                  }
                  html += &lt;span class="str"&gt;'&amp;lt;/ul&amp;gt;'&lt;/span&gt;;                  
                  
                  element.find(&lt;span class="str"&gt;'div'&lt;/span&gt;).html(html);
              }
              
              init();
              render();        
      };
      
      
      &lt;span class="kwrd"&gt;return&lt;/span&gt; {
          restrict: &lt;span class="str"&gt;'EA'&lt;/span&gt;,
          scope: {
              datasource: &lt;span class="str"&gt;'='&lt;/span&gt;,
              add: &lt;span class="str"&gt;'&amp;amp;'&lt;/span&gt;,
          },
          link: link
      };
  });

}());&lt;/pre&gt;&lt;font size="2" face="Consolas"&gt;&lt;br&gt;&lt;/font&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Although this code gets the job done, it’s more along the lines of a jQuery plugin and takes what I refer to as a “&lt;a href="http://weblogs.asp.net/dwahlin/The-JavaScript-Cheese-is-Moving_3A00_-Data_2D00_Oriented-vs.-Control_2D00_Oriented-Programming" target="_blank"&gt;control-oriented&lt;/a&gt;” approach where tag names and/or IDs are prevalent in the code. All of the DOM manipulation is handled manually which is fine and maybe even preferred in some cases (for performance reasons for example), but it’s definitely not the normal way we build Angular apps. The DOM manipulation code is mixed in with the scope which starts to get messy especially as the directive grows in size.&lt;/p&gt;
&lt;p&gt;As the button is clicked the &lt;strong&gt;addItem()&lt;/strong&gt; function is called which handles calling an isolate scope property (&lt;strong&gt;add&lt;/strong&gt;) and invoking the &lt;strong&gt;render()&lt;/strong&gt; function which renders a &amp;lt;ul&amp;gt; tag and multiple &amp;lt;li&amp;gt; tags. There’s nothing wrong with this approach per se, but I’m not a fan of having a lot of separate strings embedded in the JavaScript since they can cause a maintenance nightmare over time. While a small directive like this is fairly easy to maintain, the code can get more challenging as the directive has additional features added. &lt;/p&gt;
&lt;p&gt;There’s also a more subtle issue at play in this code. When &lt;strong&gt;scope.add()&lt;/strong&gt; is called the invoked parent scope function will need to use &lt;strong&gt;$scope.$apply()&lt;/strong&gt; to update any properties in the parent scope since the call to &lt;strong&gt;add&lt;/strong&gt; is being made from vanilla JavaScript rather than from within the context of AngularJS (something that’s outside the scope of this post, but definitely important to consider). Finally, the directive doesn’t resemble the “child view” concept that was mentioned at the beginning of the post – it’s just a bunch of code. How can a controller help out in this example? Let’s take a look.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Adding a Controller and View into a Directive&lt;/h2&gt;
&lt;p&gt;&lt;br&gt;The directive shown in the previous section gets the job done but what if you could write it much like you’d write a standard AngularJS view and use a more &lt;a href="http://weblogs.asp.net/dwahlin/The-JavaScript-Cheese-is-Moving_3A00_-Data_2D00_Oriented-vs.-Control_2D00_Oriented-Programming" target="_blank"&gt;data-oriented&lt;/a&gt; approach as opposed to the &lt;a href="http://weblogs.asp.net/dwahlin/The-JavaScript-Cheese-is-Moving_3A00_-Data_2D00_Oriented-vs.-Control_2D00_Oriented-Programming" target="_blank"&gt;control-oriented&lt;/a&gt; approach that the DOM takes? By using a controller and view in a directive the development process feel more along the lines of what you do everyday in AngularJS applications.&lt;/p&gt;
&lt;p&gt;Here’s an example of converting the directive shown earlier into a cleaner version (in my opinion anyway) that relies on a controller and a simple view:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;pre class="csharpcode"&gt;(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {

  &lt;span class="kwrd"&gt;var&lt;/span&gt; app = angular.module(&lt;span class="str"&gt;'directivesModule'&lt;/span&gt;);

  app.directive(&lt;span class="str"&gt;'isolateScopeWithController'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
      
    &lt;span class="kwrd"&gt;var&lt;/span&gt; controller = [&lt;span class="str"&gt;'$scope'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; ($scope) {

          &lt;span class="kwrd"&gt;function&lt;/span&gt; init() {
              $scope.items = angular.copy($scope.datasource);
          }

          init();

          $scope.addItem = &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
              $scope.add();

              &lt;span class="rem"&gt;//Add new customer to directive scope&lt;/span&gt;
              $scope.items.push({
                  name: &lt;span class="str"&gt;'New Directive Controller Item'&lt;/span&gt;
              });
          };
      }],
        
      template = &lt;span class="str"&gt;'&amp;lt;button ng-click="addItem()"&amp;gt;Add Item&amp;lt;/button&amp;gt;&amp;lt;ul&amp;gt;'&lt;/span&gt; +
                 &lt;span class="str"&gt;'&amp;lt;li ng-repeat="item in items"&amp;gt;{{ ::item.name }}&amp;lt;/li&amp;gt;&amp;lt;/ul&amp;gt;'&lt;/span&gt;;
      
      &lt;span class="kwrd"&gt;return&lt;/span&gt; {
          restrict: &lt;span class="str"&gt;'EA'&lt;/span&gt;, &lt;span class="rem"&gt;//Default in 1.3+&lt;/span&gt;
          scope: {
              datasource: &lt;span class="str"&gt;'='&lt;/span&gt;,
              add: &lt;span class="str"&gt;'&amp;amp;'&lt;/span&gt;,
          },
          controller: controller,
          template: template
      };
  });

}());&lt;/pre&gt;&lt;br&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The directive could be used in one of the following ways:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="csharpcode"&gt;Attribute: &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;isolate-scope-with-controller&lt;/span&gt; &lt;span class="attr"&gt;datasource&lt;/span&gt;&lt;span class="kwrd"&gt;="customers"&lt;/span&gt; &lt;span class="attr"&gt;add&lt;/span&gt;&lt;span class="kwrd"&gt;="addCustomer()"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

Element: &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;isolate-scope-with-controller&lt;/span&gt; &lt;span class="attr"&gt;datasource&lt;/span&gt;&lt;span class="kwrd"&gt;="customers"&lt;/span&gt; &lt;span class="attr"&gt;add&lt;/span&gt;&lt;span class="kwrd"&gt;="addCustomer()"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;br&gt;         &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;isolate-scope-with-controller&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Looking through the directive code you can see that it’s very similar to the approach you’d take for writing a normal view with a controller. I’d argue that it looks like you’re writing a “child view” as mentioned at the beginning of this post since the code is focused more on the data and less on the “controls” in the view. The view takes advantage of AngularJS directives to handle various control rendering tasks which eliminates all of the DOM code that had to be written before.&lt;/p&gt;
&lt;p&gt;The view is defined using the &lt;strong&gt;template&lt;/strong&gt; property and the controller is defined using the &lt;strong&gt;controller&lt;/strong&gt; property. Keep in mind that the view can be loaded from a file using the &lt;strong&gt;&lt;a href="https://docs.angularjs.org/api/ng/service/$compile" target="_blank"&gt;templateUrl&lt;/a&gt;&lt;/strong&gt; property or from the &lt;strong&gt;&lt;a href="https://docs.angularjs.org/api/ng/service/$templateCache" target="_blank"&gt;$templateCache&lt;/a&gt;&lt;/strong&gt; as well – it doesn’t have to be embedded directly in the directive. The &lt;strong&gt;templateUrl&lt;/strong&gt; or &lt;strong&gt;$templateCache&lt;/strong&gt; options are really useful when a view has a lot of HTML in it that you don’t want embedded in the directive. &lt;/p&gt;
&lt;p&gt;As mentioned, the code in the view leverages existing AngularJS directives such as &lt;strong&gt;ng-click&lt;/strong&gt; and &lt;strong&gt;ng-repeat&lt;/strong&gt; and also uses &lt;strong&gt;{{ … }}&lt;/strong&gt; data binding expressions. This eliminates the DOM code shown earlier in the DOM-centric/control-oriented directive. The controller has the &lt;strong&gt;$scope&lt;/strong&gt; injected as you’d expect and uses it to define an &lt;strong&gt;items&lt;/strong&gt; property which is consumed by &lt;strong&gt;ng-repeat&lt;/strong&gt; in the view to generate &amp;lt;li&amp;gt; tags. As the button in the view is clicked the &lt;strong&gt;addItem()&lt;/strong&gt; function on the &lt;strong&gt;$scope&lt;/strong&gt; is invoked which calls the &lt;strong&gt;add&lt;/strong&gt; isolate scope property and adds a new item object into the local collection (since angular.copy() is used items added into the local collection won’t show up in the parent scope). Because &lt;strong&gt;addItem()&lt;/strong&gt; is called using &lt;strong&gt;ng-click&lt;/strong&gt;, the parent scope call that is made ($scope.add()) won’t need to worry about using &lt;strong&gt;$scope.$apply()&lt;/strong&gt; as mentioned in the earlier section.&lt;/p&gt;
&lt;p&gt;In situations where a directive is being written with raw performance in mind then the DOM-centric approach shown earlier may be preferred I realize since you’d be purposely taking over control of the HTML that’s generated and avoiding the use of Angular directives. If you ever attend one of my conference sessions or training classes you’ll often hear me say, “Use the right tool for the right job”. I’ve never believed that “one size fits all” and know that each situation and application is unique. &lt;/p&gt;
&lt;p&gt;This thought process definitely applies to directives since there are many different ways to write them.&amp;nbsp; In many situations I’m happy with how AngularJS performs and know about the pitfalls to avoid so I prefer the controller/view type of directive whenever possible. It makes maintenance much easier down the road since you can leverage existing Angular directives in the directive’s view and modify the view using a controller and scope. If, however, I was trying to maximize performance and eliminate the use of directives such as ng-repeat then going the DOM-centric route with the &lt;strong&gt;link&lt;/strong&gt; function might be a better choice. Again, choose the right tool for the right job.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Using controllerAs in a Directive&lt;/h2&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If you’re a fan of the controllerAs syntax you may be wondering if the same style can be used inside of directives. The answer is “yes”! When you define a Directive Definition Object (DDO) in a directive you can add a &lt;strong&gt;controllerAs&lt;/strong&gt; property. Starting with Angular 1.3 you’ll also need to add a &lt;strong&gt;&lt;a href="https://docs.angularjs.org/api/ng/service/$compile" target="_blank"&gt;bindToController&lt;/a&gt;&lt;/strong&gt; property as well to ensure that properties are bound to the controller rather than to the scope. Here’s an example of the previous directive that has been converted to use the controllerAs syntax:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="csharpcode"&gt;(function() {

  var app = angular.module(&lt;span class="str"&gt;'directivesModule'&lt;/span&gt;);

  app.directive(&lt;span class="str"&gt;'isolateScopeWithControllerAs'&lt;/span&gt;, function () {
      
      var controller = function () {
          
              var vm = &lt;span class="kwrd"&gt;this&lt;/span&gt;;
          
              function init() {
                  vm.items = angular.copy(vm.datasource);
              }
              
              init();
              
              vm.addItem = function () {
                  vm.add();

                  &lt;span class="rem"&gt;//Add new customer to directive scope&lt;/span&gt;
                  vm.items.push({
                      name: &lt;span class="str"&gt;'New Directive Controller Item'&lt;/span&gt;
                  });
              };
      };    
      
      var template = &lt;span class="str"&gt;'&amp;lt;button ng-click="vm.addItem()"&amp;gt;Add Item&amp;lt;/button&amp;gt;'&lt;/span&gt; +
                     &lt;span class="str"&gt;'&amp;lt;ul&amp;gt;&amp;lt;li ng-repeat="item in vm.items"&amp;gt;{{ ::item.name }}&amp;lt;/li&amp;gt;&amp;lt;/ul&amp;gt;'&lt;/span&gt;;
      
      &lt;span class="kwrd"&gt;return&lt;/span&gt; {
          restrict: &lt;span class="str"&gt;'EA'&lt;/span&gt;, &lt;span class="rem"&gt;//Default for 1.3+&lt;/span&gt;
          scope: {
              datasource: &lt;span class="str"&gt;'='&lt;/span&gt;,
              add: &lt;span class="str"&gt;'&amp;amp;'&lt;/span&gt;,
          },
          controller: controller,
          controllerAs: &lt;span class="str"&gt;'vm'&lt;/span&gt;,
          bindToController: &lt;span class="kwrd"&gt;true&lt;/span&gt;, &lt;span class="rem"&gt;//required in 1.3+ with controllerAs&lt;/span&gt;
          template: template
      };
  });

}());&lt;/pre&gt;&lt;font size="2" face="Consolas"&gt;&lt;br&gt;&lt;/font&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Notice that a controller alias of &lt;strong&gt;vm&lt;/strong&gt; (short for “ViewModel”) has been assigned to the &lt;strong&gt;controllerAs&lt;/strong&gt; property and that the alias is used in the controller code and in the view. The &lt;strong&gt;bindToController&lt;/strong&gt; property is set to &lt;strong&gt;true&lt;/strong&gt; to ensure that properties are bound to the controller instead of the scope. While this code is very similar to the initial controller example shown earlier, it allows you to use “dot” syntax in the view (vm.customers for example) which is a recommended approach.&lt;br&gt;&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;&lt;br&gt;Controllers can be used to cleanup directives in many scenarios. Although using a controller isn’t always necessary, you’ll find that by levering the “child view” concept in directives your code can be kept more maintainable and easier to work with. The next post in the series moves on to discuss additional features that can be used in directives such as $asyncValidators.&lt;/p&gt;</description><pubDate>Mon, 29 Dec 2014 22:06:33 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/creating-custom-angularjs-directives-part-6-using-controllers</guid><category>AngularJS</category><category>directives</category><category>JavaScript</category><category>SPA</category></item><item><title>Getting Started with ES6 – Transpiling ES6 to ES5 with Traceur and Babel</title><link>https://weblogs.asp.net:443/dwahlin/getting-started-with-es6-%E2%80%93-transpiling-es6-to-es5</link><description>&lt;p&gt;In the &lt;a href="https://weblogs.asp.net/dwahlin/getting-started-with-es6-%E2%80%93-the-next-version-of-javascript" target="_blank"&gt;first post&lt;/a&gt; in this series I introduced key features in ECMAScript 6 (ES6), discussed tools that can be used today to transpile code to ES5 so that it can work in today’s browsers, and listed several resources that will help get you started. Before jumping into the first official ES6 feature (that’s coming&lt;img align="right" style="border-width: 0px; margin: 10px; padding-top: 0px; padding-right: 0px; padding-left: 0px; float: right; display: inline; background-image: none;" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_thumb_1.png" border="0"&gt; in the next post) I wanted to write a step-by-step walkthrough that covers how to get the &lt;a href="https://github.com/google/traceur-compiler" target="_blank"&gt;Traceur&lt;/a&gt; and &lt;a href="https://babeljs.io/" target="_blank"&gt;Babel&lt;/a&gt; transpilers working with &lt;a href="http://gulpjs.com/" target="_blank"&gt;Gulp&lt;/a&gt; (a JavaScript task runner). I’m also going to sneak in a little TypeScript as well since it’s another option. By getting these tools in place you can start writing ES6 code, convert/transpile it to ES5, and then use the generated code in older browsers. Going that route lets you take advantage of the future of JavaScript right now without having to wait around until all of the browsers fully support ES6.&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/2272876fb5e4_BAB3/image_8.png"&gt;&lt;img width="240" height="93" title="image" align="right" style="border-width: 0px; margin: 10px; padding-top: 0px; padding-right: 0px; padding-left: 0px; float: right; display: inline; background-image: none;" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/2272876fb5e4_BAB3/image_thumb_3.png" border="0"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Two options are available in this post. If you want a step-by-step look at getting Gulp setup to work with ES6 transpilers then I’d recommend reading the entire post. If you want to start working with ES6 but aren’t interested in getting the ES6 transpilers setup then skip to the &lt;strong&gt;Configuring ES6 Samples&lt;/strong&gt; section below where you can download a project that has everything in place and discusses how to get started using it.&lt;/p&gt; &lt;p&gt;Let’s jump into a step-by-step walk-through of setting up Gulp, Traceur and Babel.&lt;/p&gt; &lt;h2&gt;Installing Node.js and Gulp&lt;/h2&gt; &lt;p&gt;&lt;br&gt;Transpilers such as &lt;a href="https://github.com/google/traceur-compiler" target="_blank"&gt;Traceur&lt;/a&gt; and &lt;a href="https://babeljs.io/" target="_blank"&gt;Babel&lt;/a&gt; can be run directly from the command line which makes it fairly trivial to convert ES6 code to ES5. However, after performing a command-line task a few times you’ll begin to wonder if there’s a way to automate the process. The good news is that JavaScript task runner tools such as &lt;a href="http://gruntjs.com/" target="_blank"&gt;Grunt&lt;/a&gt; or &lt;a href="http://gulpjs.com/" target="_blank"&gt;Gulp&lt;/a&gt; can automate just about any JavaScript task you can think of. You can use them to perform a variety of tasks such as restarting a Node.js server if it dies, “live” reloading a webpage as HTML or CSS code changes, concatenating and minifying JavaScript files, finding unused CSS classes in a file, plus much more. You can also use these tools to automatically convert ES6 code to ES5 as you save a code file.&lt;/p&gt; &lt;p&gt;While both tools get the job done well, I personally prefer Gulp so the steps that follow will show how to use it. I’m going to assume that you haven’t done much with Node.js or Gulp so if you’re already a Node.js or Gulp expert you can gloss over some of the steps that follow. Let’s get started by getting Node.js and Gulp installed.&lt;/p&gt; &lt;h3&gt;Step 1: Install Node.js&lt;/h3&gt; &lt;p&gt;&lt;br&gt;Gulp requires &lt;a href="http://nodejs.org" target="_blank"&gt;Node.js&lt;/a&gt; so the first thing you’ll need to do (if you haven’t done it already) is install Node.js on your machine. Navigate to &lt;a href="http://nodejs.org"&gt;http://nodejs.org&lt;/a&gt; in the browser and click the &lt;strong&gt;Install&lt;/strong&gt; button to download the Node.js installation file.&lt;br&gt;&lt;br&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/2272876fb5e4_BAB3/image_2.png"&gt;&lt;img width="240" height="90" title="image" style="border-width: 0px; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/2272876fb5e4_BAB3/image_thumb.png" border="0"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt;&lt;/p&gt; &lt;p&gt;Once the file downloads, double-click it and follow the instructions to install Node.js on your machine.&lt;/p&gt; &lt;p&gt;&lt;br&gt;&amp;nbsp;&lt;/p&gt; &lt;h3&gt;Step 2: Use npm to Install Gulp&lt;/h3&gt; &lt;p&gt;&lt;br&gt;When you install Node.js you also get access to another tool called &lt;a href="https://www.npmjs.com/" target="_blank"&gt;npm&lt;/a&gt; that can be used to install Node.js modules. Gulp is one of many modules that are available (see &lt;a href="https://www.npmjs.com"&gt;https://www.npmjs.com&lt;/a&gt; for a complete list).&amp;nbsp; Follow these steps to use npm to install Gulp.&lt;/p&gt; &lt;p&gt;&lt;br&gt;&lt;strong&gt;Note for Mac Users&lt;/strong&gt;: You may need to add “sudo” in front of the install commands below if they fail. If you don’t want to use sudo (for security reasons) check out &lt;a href="http://howtonode.org/introduction-to-npm" target="_blank"&gt;this post&lt;/a&gt;.&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Create the following folder structure on your desktop (or anywhere else you’d like to create it):&lt;br&gt;&lt;br&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/2272876fb5e4_BAB3/image_10.png"&gt;&lt;img width="183" height="150" title="image" style="border-width: 0px; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/2272876fb5e4_BAB3/image_thumb_4.png" border="0"&gt;&lt;/a&gt;&lt;br&gt;&lt;br&gt; &lt;li&gt;Open a command-prompt and navigate to the &lt;strong&gt;es6Demos&lt;/strong&gt; folder.&lt;br&gt;&lt;br&gt; &lt;li&gt;Type the following at the command-prompt: &lt;br&gt;&lt;br&gt;&lt;strong&gt;npm init&lt;br&gt;&lt;br&gt;&lt;/strong&gt; &lt;li&gt;Running this command will start a command-line wizard that’s used to generate a file named &lt;strong&gt;package.json&lt;/strong&gt;. &lt;br&gt;&lt;br&gt; &lt;li&gt;Accept all of the defaults for now (or you can supply values for the author name, description, etc. if you’d like) by pressing Return/Enter for each question asked. &lt;br&gt;&lt;br&gt; &lt;li&gt;At the end of the wizard you’ll be asked to type “yes” to complete the process. The &lt;strong&gt;package.json&lt;/strong&gt; file that’s generated is used to store all of the modules that your app may use (such as Gulp and others).&lt;br&gt;&lt;br&gt; &lt;li&gt;Type the following at the command-prompt to install the Gulp module globally on your machine:&lt;br&gt;&lt;br&gt;&lt;strong&gt;npm install gulp -g&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/strong&gt; &lt;li&gt;Next type the following at the command-prompt to add Gulp to your &lt;strong&gt;package.json&lt;/strong&gt; file’s dev dependencies. This will cause the &lt;strong&gt;package.json&lt;/strong&gt; file to be updated and add a &lt;strong&gt;node_modules&lt;/strong&gt; folder into the &lt;strong&gt;es6Demos&lt;/strong&gt; folder that contains Gulp-related code/files.&lt;br&gt;&lt;br&gt;&lt;strong&gt;npm install gulp --save-dev&lt;br&gt;&lt;/strong&gt;&lt;strong&gt;&lt;br&gt;&lt;/strong&gt; &lt;li&gt;&lt;/li&gt;&lt;li&gt;To try out Gulp, type the following at the command-prompt and press Enter/Return. You should see an error saying that no gulpfile was found.&lt;br&gt;&lt;br&gt;&lt;strong&gt;gulp&lt;br&gt;&lt;/strong&gt;&lt;br&gt;&lt;br&gt;&lt;/li&gt;&lt;/ol&gt; &lt;h3&gt;Step 3: Install Traceur, Babel, and Additional Gulp Modules&lt;/h3&gt; &lt;p&gt;&lt;br&gt;Now that Node.js and Gulp are available it’s time to load the &lt;strong&gt;Traceur&lt;/strong&gt; and &lt;strong&gt;Babel &lt;/strong&gt;Gulp modules so that we can use them to transpile ES6 code to ES5. In a “real” app you’d choose one of these rather than using both at the same time, but you’ll configure both here so that you can see the type of ES5 code that they generate.&lt;/p&gt; &lt;p&gt;I’m going to show the entire process for getting Gulp modules in place. At the end of the steps I’ll show how simple it is to get everything going using npm and the package.json file though so that in the future this process is super quick.&lt;/p&gt; &lt;p&gt;&lt;br&gt;&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Run the following commands at the command-prompt (it should still be at the &lt;strong&gt;es6Demos&lt;/strong&gt; folder) to install Gulp modules (and some others) that can be used to transpile ES6 to ES5. As mentioned above, I’m showing how to install each individual Gulp module so that you understand the process. It’s a one-time setup process and can be re-used once in place as you’ll see at the end of this section. &lt;br&gt;&lt;br&gt;&lt;strong&gt;npm install gulp-babel --save-dev&lt;br&gt;npm install babel-preset-es2015 –save-dev&lt;br&gt;npm install gulp-traceur --save-dev&lt;br&gt;npm install gulp-typescript --save-dev&lt;br&gt;npm install gulp-plumber --save-dev&lt;br&gt;npm install gulp-concat --save-dev&lt;br&gt;npm install gulp-uglify --save-dev&lt;br&gt;&lt;/strong&gt;&lt;br&gt;Although the gulp-plumber, gulp-concat, gulp-typescript, and gulp-uglify modules are optional, they’re quite useful in a real-life workflow. The gulp-plumber module can help fix errors that occur in the Gulp pipeline while gulp-concat and gulp-uglify can be used to concatenate and minify JavaScript files to get them ready for production. I won’t focus on them in this post but they’re good to have in place and use once you’re ready to move files into production.&lt;br&gt;&lt;br&gt; &lt;li&gt;Open the &lt;strong&gt;package.json&lt;/strong&gt; file that’s in the &lt;strong&gt;es6Demos&lt;/strong&gt; folder in a text editor and notice that a &lt;strong&gt;devDependencies&lt;/strong&gt; property has been added along with details about each module that you installed earlier including their version number. The file should look something like the following (note that I removed a few properties to keep it short and removed the versions since they change frequently):&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;{
  &lt;span class="str"&gt;"name"&lt;/span&gt;: &lt;span class="str"&gt;"ES6Demos"&lt;/span&gt;,
  &lt;span class="str"&gt;"version"&lt;/span&gt;: &lt;span class="str"&gt;"1.0.0"&lt;/span&gt;,
  &lt;span class="str"&gt;"description"&lt;/span&gt;: &lt;span class="str"&gt;""&lt;/span&gt;,
  &lt;span class="str"&gt;"author"&lt;/span&gt;: &lt;span class="str"&gt;""&lt;/span&gt;,
  &lt;span class="str"&gt;"license"&lt;/span&gt;: &lt;span class="str"&gt;"ISC"&lt;/span&gt;,
  &lt;span class="str"&gt;"devDependencies"&lt;/span&gt;: {
    &lt;span class="str"&gt;"gulp"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,
    &lt;span class="str"&gt;"gulp-babel"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,&lt;br&gt;    &lt;span class="str"&gt;"babel-preset-es2015"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,
    &lt;span class="str"&gt;"gulp-concat"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,
    &lt;span class="str"&gt;"gulp-plumber"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,
    &lt;span class="str"&gt;"gulp-traceur"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,
    &lt;span class="str"&gt;"gulp-typescript"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,
    &lt;span class="str"&gt;"gulp-uglify"&lt;/span&gt;: &lt;span class="str"&gt;"^x.x.x"&lt;/span&gt;,&lt;span class="str"&gt;"&lt;/span&gt;
  }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;!--
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
--&gt;&lt;/style&gt;

&lt;li&gt;Open the &lt;strong&gt;node_modules&lt;/strong&gt; folder and notice the subfolders that are there now. &lt;/li&gt;&lt;li&gt;In the root folder add a file named &lt;strong&gt;.babelrc&lt;/strong&gt; that has the following content: { “presets”: [“es2015”] }&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&lt;br&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Step 4: Creating a gulpfile&lt;/h3&gt;
&lt;p&gt;&lt;br&gt;Now that all of the necessary modules are in place it’s time to create a Gulp task runner file name &lt;strong&gt;gulpfile.js&lt;/strong&gt;. This file is responsible for defining tasks that use the Gulp modules installed earlier such as Traceur and Babel.&lt;br&gt;&lt;br&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create a new file in the &lt;strong&gt;es6Demos&lt;/strong&gt; folder named &lt;strong&gt;gulpfile.js&lt;/strong&gt;.&lt;br&gt;&lt;br&gt;
&lt;li&gt;Add the following code into &lt;strong&gt;gulpfile.js&lt;/strong&gt; to load the Gulp modules installed earlier and define a few paths:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; gulp = require(&lt;span class="str"&gt;'gulp'&lt;/span&gt;),
    traceur = require(&lt;span class="str"&gt;'gulp-traceur'&lt;/span&gt;),
    babel = require(&lt;span class="str"&gt;'gulp-babel'&lt;/span&gt;),
    plumber = require(&lt;span class="str"&gt;'gulp-plumber'&lt;/span&gt;),
    es6Path = &lt;span class="str"&gt;'es6/*.js'&lt;/span&gt;,
    compilePath = &lt;span class="str"&gt;'es6/compiled'&lt;/span&gt;;&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;!--
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
--&gt;&lt;/style&gt;

&lt;li&gt;Now add the following code under the code in the previous step to create a new &lt;strong&gt;Traceur&lt;/strong&gt; task. This adds the plumber module into the streaming process to handle any errors that occur in the the piping process more gracefully and then invokes the &lt;strong&gt;Traceur&lt;/strong&gt; transpiler. The blockBinding property allows block level definitions to be used in the ES6 code via a new &lt;em&gt;let&lt;/em&gt; keyword (more about that feature in a future post).&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;gulp.task(&lt;span class="str"&gt;'traceur'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
    gulp.src([es6Path])
        .pipe(plumber())
        .pipe(traceur({ blockBinding: &lt;span class="kwrd"&gt;true&lt;/span&gt; }))
        .pipe(gulp.dest(compilePath + &lt;span class="str"&gt;'/traceur'&lt;/span&gt;));
});&lt;/pre&gt;
&lt;li&gt;Now add code to create a &lt;strong&gt;Babel&lt;/strong&gt; task:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;gulp.task(&lt;span class="str"&gt;'babel'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; () {
    gulp.src([es6Path])
        .pipe(plumber())
        .pipe(babel())
        .pipe(gulp.dest(compilePath + &lt;span class="str"&gt;'/babel'&lt;/span&gt;));
});&lt;/pre&gt;
&lt;li&gt;The previous tasks will cause ES6 to be transpiled to ES5 (using two different techniques) but they won’t run any time an ES6 file is saved. To automate the process add the following watch task:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;gulp.task(&lt;span class="str"&gt;'watch'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt;() {

    gulp.watch([es6Path], [&lt;span class="str"&gt;'traceur'&lt;/span&gt;, &lt;span class="str"&gt;'babel'&lt;/span&gt;]);

});
&lt;/pre&gt;
&lt;li&gt;Finally, create a default task that runs the &lt;strong&gt;traceur&lt;/strong&gt;, &lt;strong&gt;babel&lt;/strong&gt;, and &lt;strong&gt;watch&lt;/strong&gt; tasks when you first start Gulp:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;gulp.task(&lt;span class="str"&gt;'default'&lt;/span&gt;, [&lt;span class="str"&gt;'traceur'&lt;/span&gt;, &lt;span class="str"&gt;'babel'&lt;/span&gt;, &lt;span class="str"&gt;'watch'&lt;/span&gt;]);&lt;br&gt;&lt;br&gt;&lt;/pre&gt;
&lt;li&gt;Save &lt;strong&gt;gulpfile.j&lt;/strong&gt;s and run the following command again at the command-prompt:&lt;br&gt;&lt;br&gt;&lt;strong&gt;gulp&lt;br&gt;&lt;br&gt;&lt;/strong&gt;
&lt;li&gt;The Gulp tasks should now run and the console should display output about the tasks.&lt;br&gt;
&lt;li&gt;Leave the console up and running and continue to the next section. &lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&lt;br&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Transpiling ES6 to ES5&lt;/h2&gt;
&lt;p&gt;&lt;br&gt;Now that you have Gulp up and running and the Traceur and ES6 tasks in place it’s time to transpile ES6 to ES5.&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Add a new file named &lt;strong&gt;car.js&lt;/strong&gt; into the &lt;strong&gt;es6&lt;/strong&gt; folder.&lt;br&gt;&lt;br&gt;
&lt;li&gt;Add the following code into &lt;strong&gt;car.js&lt;/strong&gt;. I’ll be discussing this code in a future post but in a nutshell, ES6 now supports encapsulating code by using classes.&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Car {
    
    constructor(engine) {
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.engine = engine;
    }

}&lt;/pre&gt;
&lt;li&gt;Open the &lt;strong&gt;es6/compiled/traceur&lt;/strong&gt; folder and open the &lt;strong&gt;car.js&lt;/strong&gt; file. It will have the following ES5 code in it:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;&lt;span class="str"&gt;"use strict"&lt;/span&gt;;
&lt;span class="kwrd"&gt;var&lt;/span&gt; Car = &lt;span class="kwrd"&gt;function&lt;/span&gt; Car(engine) {
  &lt;span class="kwrd"&gt;this&lt;/span&gt;.engine = engine;
};
($traceurRuntime.createClass)(Car, {}, {});&lt;/pre&gt;&lt;br&gt;&lt;br&gt;
&lt;li&gt;The &lt;strong&gt;car.js&lt;/strong&gt; file in &lt;strong&gt;es6/compiled/babel&lt;/strong&gt; has the following ES5 code:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;pre class="csharpcode"&gt;&lt;span class="str"&gt;"use strict"&lt;/span&gt;;

&lt;span class="kwrd"&gt;var&lt;/span&gt; Car = &lt;span class="kwrd"&gt;function&lt;/span&gt; Car(engine) {
  &lt;span class="kwrd"&gt;this&lt;/span&gt;.engine = engine;
};&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/pre&gt;
&lt;li&gt;You’ve now successfully transpiled ES6 code to ES5 using both Traceur and Babel. &lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&lt;br&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Configuring the ES6 Samples&lt;/h2&gt;
&lt;p&gt;&lt;br&gt;If you decided to skip all of the steps above you can visit &lt;a href="http://github.com/danwahlin/es6samples" target="_blank"&gt;http://github.com/danwahlin/es6samples&lt;/a&gt; and click the&amp;nbsp; &lt;strong&gt;Download ZIP&lt;/strong&gt; button to get all of the code (or clone the repository if you’re familiar with Git). Once you have the code extracted follow the steps below to get Gulp and the transpilers setup.&lt;/p&gt;
&lt;p&gt;Note that if you’re on a Mac you may need to use “sudo” (prefix each of the npm commands with it) if any of the install commands trigger an error.&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Install &lt;strong&gt;Node.js&lt;/strong&gt; if it’s not already on your system. &lt;br&gt;&lt;br&gt;
&lt;li&gt;Open a command-prompt and navigate to the project’s root folder that has the &lt;strong&gt;package.json&lt;/strong&gt; file in it.&lt;br&gt;&lt;br&gt;
&lt;li&gt;If you haven’t already installed &lt;strong&gt;Gulp&lt;/strong&gt; run the following command:&lt;br&gt;&lt;br&gt;&lt;strong&gt;npm install gulp -g&lt;br&gt;&lt;br&gt;&lt;/strong&gt;
&lt;li&gt;Run &lt;strong&gt;npm install&lt;/strong&gt; to get the necessary Node.js/Gulp modules installed.&lt;br&gt;&lt;br&gt;
&lt;li&gt;Run the following command to transpile the JavaScript files from ES6 to ES5 and start the file watcher:&lt;br&gt;&lt;br&gt;&lt;strong&gt;gulp&lt;br&gt;&lt;br&gt;&lt;/strong&gt;
&lt;li&gt;Open the &lt;strong&gt;es6/compiled&lt;/strong&gt; folder and look at the files that are generated in the two subfolders (traceur and babel). &lt;/li&gt;&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;br&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;&lt;br&gt;Transpilers such as Traceur and Babel provide a way to convert ES6 code to ES5 quickly and easily. In this post you’ve seen a step-by-step walk-through of setting up the Gulp task runner to automate the transpilation process and how it can simplify the overall process of converting ES6 code and ES5. Now that the setup work for transpiling files is in place it’s time to jump into some of the different ES6 features that are available. Stay tuned for future posts.&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;br&gt;&lt;strong&gt;Onsite Developer Training:&lt;/strong&gt; If your company is interested in onsite training on JavaScript, ES6, AngularJS, Node.js, C# or other technologies please email &lt;a href="mailto:training@wahlinconsulting.com"&gt;training@wahlinconsulting.com&lt;/a&gt; for details about the classes that we offer.&lt;/p&gt;</description><pubDate>Tue, 16 Dec 2014 07:59:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/getting-started-with-es6-%E2%80%93-transpiling-es6-to-es5</guid><category>JavaScript</category><category>ES6</category><category>ECMASCript6</category><category>Transpile</category><category>Traceur</category><category>Babel</category><category>Gulp</category><category>Node.js</category></item><item><title>Registering a Custom AngularJS Application with Azure Active Directory</title><link>https://weblogs.asp.net:443/dwahlin/registering-a-custom-angularjs-application-with-azure-active-directory</link><description>&lt;p&gt;&lt;img style="float: left; margin: 0px 15px 15px 0px; display: inline" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bc4f2922cfcb_9E75/azure_thumb.png" align="left"&gt;If you’re working with Azure and need to add authentication and identity management into an application look no further than &lt;a href="http://azure.microsoft.com/en-us/services/active-directory/" target="_blank"&gt;Azure Active Directory&lt;/a&gt; (AAD). AAD provides a robust set of services for single sign-on, authentication, multi-factor authentication, and more. Rather than setting up a custom authentication provider for an app, you can leverage existing functionality provided by AAD. &lt;/p&gt; &lt;p&gt;To associate a custom application with AAD you first need to register it. If you’ve ever registered a custom app with Facebook, Twitter, or another service you’ll find the AAD app registration process to be quite similar. When you register your application, AAD will generate a client ID and password that can be configured in your app and act as&amp;nbsp; a “hook” between the two. Once that’s done the application can direct all authentication actions to AAD and upon successful authentication, AAD can redirect the user back to a page in your custom app. This causes identity and access tokens to be provided to your application by AAD. An identity token has information about a given authenticated user (in addition to other details) while an access token provides temporary access to a secured resource (such as Office 365 services) that is also registered with AAD.&lt;/p&gt; &lt;p&gt;In a &lt;a href="https://weblogs.asp.net/dwahlin/building-applications-with-angularjs-azure-active-directory-and-office-365-sharepoint" target="_blank"&gt;previous post&lt;/a&gt; I discussed a series of articles that I’m writing about AngularJS, Azure Active Directory, and Office 365/SharePoint for &lt;a href="http://www.itunity.com/" target="_blank"&gt;itunity.com&lt;/a&gt;. The first article introduced the application and provided an overview of the technologies used while the second article walks through how to register the custom application with AAD. Although I can’t post the entire article, here’s a snippet from it with a link to the complete article below.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;Integrating AngularJS with Azure Active Directory and Office 365/SharePoint, Part 2 &lt;br&gt;&lt;/h2&gt; &lt;p&gt;&lt;a href="http://www.itunity.com/article/integrating-angularjs-azure-active-directory-office-365sharepoint-part-1-622" target="_blank"&gt;Part 1&lt;/a&gt; of this article series introduced a stand-alone Expense Manager application built using AngularJS, Azure Active Directory, and the Office 365/SharePoint APIs. The overall scenario discussed throughout the series revolves around integrating data from the cloud into an application that can stand on its own and run gracefully in desktop browsers and mobile/tablet browsers. If you haven't read through &lt;a href="http://www.itunity.com/article/integrating-angularjs-azure-active-directory-office-365sharepoint-part-1-622" target="_blank"&gt;Part 1&lt;/a&gt;, I encourage you to read it first before going through this article since it provides additional context about the application and the technologies used to build it. If you're new to Microsoft Azure or Office 365 cloud services, I also recommend that you learn more about them at &lt;a href="http://azure.microsoft.com/" target="_blank"&gt;http://azure.microsoft.com&lt;/a&gt; and &lt;a href="http://products.office.com/business/enterprise-productivity-tools" target="_blank"&gt;http://products.office.com/business/enterprise-productivity-tools&lt;/a&gt;. &lt;p&gt;One of the essential requirements that enterprise applications (and many non-enterprise applications) have is authentication and identity management. Although you can certainly use on-premise deployments of Active Directory (AD) or another custom security provider, Azure Active Directory (AAD) integrates directly with Office 365/SharePoint APIs (in addition to several others) and lets you harness the power of the cloud. In this article, you'll see how a custom application such as the Expense Manager application discussed in Part 1 can be registered with Azure Active Directory so that users can be authenticated. In the next article in the series, we'll explore the AAD code that's required and see how it plugs into an ASP.NET MVC application. &lt;p&gt;So what is Azure Active Directory and how do you get started using it? In a nutshell, it provides "Identity and Access Management for the Cloud" (see &lt;a href="http://azure.microsoft.com/services/active-directory/" target="_blank"&gt;http://azure.microsoft.com/services/active-directory&lt;/a&gt; for additional details). By using the Azure management website, you can setup and integrate AAD authentication and identity management into custom applications and also use it to secure Office 365/SharePoint deployments. AAD has many additional features, but the Expense Manager application discussed in this series uses it strictly for authentication purposes so that Office 365/SharePoint lists can be accessed and modified. &lt;p&gt;You can manage your Azure account and AAD functionality by going to &lt;a href="https://manage.windowsazure.com/" target="_blank"&gt;https://manage.windowsazure.com&lt;/a&gt;. A new Azure management portal (&lt;a href="https://portal.azure.com/" target="_blank"&gt;https://portal.azure.com&lt;/a&gt;) is also available but it's currently in beta (as I’m writing this article) and doesn't offer AAD features yet. It's important to point out that going through the Azure management site isn't the only solution for registering a custom application with AAD so that users can authenticate. When working with Office 365/SharePoint APIs, you can simplify the overall process by using the Microsoft Office 365 API Tools, which is another topic that will be covered in this article. &lt;p&gt;Let's get started by taking a look at how to register a custom application with AAD using the Azure management site. Once you see how to manually register an application with AAD, you'll then learn about the Microsoft Office 365 API Tools and see how they can be installed and used to register an application from within Visual Studio.&lt;br&gt; &lt;h3&gt;Registering an application with Azure Active Directory&lt;br&gt;&lt;/h3&gt; &lt;p&gt;In order to add AAD authentication functionality into the Expense Manager application (or any custom application), it has to be registered with AAD. The standard way to register an application is to login to your Azure account (&lt;a href="https://manage.windowsazure.com/" target="_blank"&gt;https://manage.windowsazure.com&lt;/a&gt;) and click the &lt;em&gt;Active Directory&lt;/em&gt; item on the left.&lt;br&gt; &lt;p&gt;&lt;a href="http://www.itunity.com/content/content/720/wahlin_aad-o365tools_1.png"&gt;&lt;img style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; padding-right: 0px" border="0" alt="click Active Directory to begin the process of registering an application with AAD" src="http://www.itunity.com/content/content/720/wahlin_aad-o365tools_1.png"&gt;&lt;/a&gt; &lt;p&gt;Figure 1: Login to Azure and click Active Directory to begin the process of registering an application with AAD&lt;br&gt; &lt;p&gt;Once you click on Active Directory in the Azure management site, the next screen lets you select the directory that the application should be associated with. By default you'll see a &lt;em&gt;Default Directory&lt;/em&gt; entry (Figure 2) unless you've created a custom directory.&lt;br&gt; &lt;p&gt;&lt;a href="http://www.itunity.com/content/content/720/wahlin_aad-o365tools_2.png"&gt;&lt;img style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; padding-right: 0px" border="0" alt="Select the directory that your application should be associated with" src="http://www.itunity.com/content/content/720/wahlin_aad-o365tools_2.png?w=550"&gt;&lt;/a&gt; &lt;p&gt;Figure 2: Select the directory that your application should be associated with&lt;br&gt; &lt;p&gt;Read the full article at &lt;a title="http://www.itunity.com/article/integrating-angularjs-o365-aad-registering-custom-app-720" href="http://www.itunity.com/article/integrating-angularjs-o365-aad-registering-custom-app-720" target="_blank"&gt;http://www.itunity.com/article/integrating-angularjs-o365-aad-registering-custom-app-720&lt;/a&gt;.     </description><pubDate>Sun, 07 Dec 2014 19:42:28 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/registering-a-custom-angularjs-application-with-azure-active-directory</guid><category>.NET</category><category>ActiveDirectory</category><category>Azure</category><category>AngularJS</category><category>Office365</category><category>JavaScript</category><category>Cloud</category><category>SPA</category></item><item><title>Building Applications with AngularJS, Azure Active Directory, and Office 365/SharePoint</title><link>https://weblogs.asp.net:443/dwahlin/building-applications-with-angularjs-azure-active-directory-and-office-365-sharepoint</link><description>&lt;p&gt;&lt;img style="float: left; display: inline" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/4e7b5c74c52f_746D/angular_thumb_1.png" align="left"&gt;One of my favorite features of Single Page Applications (SPAs) is the ability to integrate data from nearly any backend technology and have it display on a variety devices (desktop browser, mobile, tablet, and more). Whether you’re calling a service like &lt;a href="https://www.firebase.com/" target="_blank"&gt;Firebase&lt;/a&gt; or &lt;a href="http://azure.microsoft.com/en-us/documentation/services/mobile-services/" target="_blank"&gt;Azure Mobile Services&lt;/a&gt; or hitting a custom REST API, the data that’s returned can be integrated into your SPA regardless of &lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bc4f2922cfcb_9E75/azure_2.png"&gt;&lt;img title="azure" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 10px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="azure" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bc4f2922cfcb_9E75/azure_thumb.png" width="240" align="right" height="43"&gt;&lt;/a&gt;the language, technology, or operating system being used on the server. &lt;/p&gt; &lt;p&gt;Some of the backend technologies I’ve been spending a lot of time with from a business perspective lately include &lt;a href="http://azure.microsoft.com/" target="_blank"&gt;Azure&lt;/a&gt; and the the &lt;a href="http://msdn.microsoft.com/en-us/office/office365/api/api-catalog" target="_blank"&gt;Office 365/SharePoint API&lt;/a&gt;. Azure provides a wealth of cloud services such as websites, virtual machines, a cloud-based Active Directory, mobile services, and much more while Office 365/SharePoint provides access to mail, contacts, calendars, files, SharePoint services, and other data services. &lt;/p&gt; &lt;p&gt;We’ve been building AngularJS applications that take advantage of some of the new features provided by these cloud services and writing a series of articles about them for &lt;a href="http://www.itunity.com/" target="_blank"&gt;itunity.com&lt;/a&gt; site. The first article is titled &lt;a href="http://www.itunity.com/article/integrating-angularjs-aad-office-365sharepoint-part-1-622" target="_blank"&gt;Integrating AngularJS with Azure Active Directory and Office 365/SharePoint, Part 1&lt;/a&gt; and was writing by myself and my good friend &lt;a href="http://transmissionit.com/" target="_blank"&gt;Spike Xavier&lt;/a&gt;. I’m not able to post the entire article here, but here’s a snippet from it. The full article can be found on the &lt;a href="http://www.itunity.com/article/integrating-angularjs-aad-office-365sharepoint-part-1-622" target="_blank"&gt;itunity.com&lt;/a&gt; site.&lt;br&gt;&lt;/p&gt; &lt;h2&gt;Integrating AngularJS with Azure Active Directory and Office 365/SharePoint, Part 1&lt;br&gt;&lt;/h2&gt; &lt;p&gt;Data is everywhere in today’s business environment and employees expect to be able to access it regardless of where it lives. They don’t care if it’s stored in a database, retrieved from a service, found in a SharePoint list or library, or stored somewhere else up in the cloud. Regardless of where the data lives, they expect to be able to get to it on any operating system, with any browser, and using any device. &lt;p&gt;With the popularity of SharePoint across many organizations an enormous amount of business data is added into lists and libraries every day. If employees have access to SharePoint directly on their chosen device then a variety of techniques can be used to expose the data to them ranging from SharePoint pages, Web Parts, App parts, Pages, and more. However, if they won’t always be using SharePoint directly to access the data how can you get it to them? Fortunately, this isn’t a new problem and has been possible for many years using SharePoint Web Services or RESTful services. How does that process change though if you’re using Microsoft Azure, Office 365 and SharePoint?&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bc4f2922cfcb_9E75/office_5.png"&gt;&lt;img title="office" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 10px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="office" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/bc4f2922cfcb_9E75/office_thumb_1.png" width="240" align="right" height="56"&gt;&lt;/a&gt; &lt;p&gt;In this article series, we’ll walk you through the process of creating an external application that can interact with Microsoft Azure Active Directory, Office 365 and SharePoint. The overall goal of the series is to show developers that may be new to SharePoint how they can leverage existing HTML and JavaScript development skills to integrate with Azure and pull Office 365/SharePoint data into custom Web applications. &lt;p&gt;This first article will discuss whether or not a SharePoint-centric application or external application should be considered. It’ll also introduce an Expense Manager application and explain what it offers. Future articles in this series will discuss the technologies used by the Expense Manager application and dive into how AngularJS can be used to build a single-page application (SPA) that can be used by employees on any device throughout an organization. &lt;p&gt;Let’s get started by discussing whether an application should be embedded directly into SharePoint or if it should be external.&lt;br&gt; &lt;h3&gt;Stand-alone or SharePoint hosted? That is the question!&lt;br&gt;&lt;/h3&gt; &lt;p&gt;While it’s true that SharePoint uses SQL Server under the covers, SharePoint itself is NOT a relational database. It’s ultimately up to the developer to understand how SharePoint works in order to maximize the use of the APIs and interact with the various objects and data. &lt;p&gt;Why is this important? It’s important because SharePoint is a robust platform that can be used to build a variety of applications that run inside or outside of SharePoint. With support for RESTful services, developers can leverage their existing Web development skills to enhance, expand and extend what SharePoint can do. A fundamental understanding of the building blocks of SharePoint will save a lot of time and frustration and allow developers to do what they do best while allowing SharePoint to do what it does best. &lt;p&gt;Read the full article at &lt;a title="http://www.itunity.com/article/integrating-angularjs-aad-office-365sharepoint-part-1-622" href="http://www.itunity.com/article/integrating-angularjs-aad-office-365sharepoint-part-1-622"&gt;http://www.itunity.com/article/integrating-angularjs-aad-office-365sharepoint-part-1-622&lt;/a&gt;.      </description><pubDate>Sun, 07 Dec 2014 18:52:28 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/building-applications-with-angularjs-azure-active-directory-and-office-365-sharepoint</guid><category>.NET</category><category>AngularJS</category><category>Azure</category><category>Office365</category><category>SharePoint</category><category>JavaScript</category><category>Cloud</category><category>SPA</category><category>ActiveDirectory</category></item><item><title>Getting Started with ES6 – The Next Version of JavaScript</title><link>https://weblogs.asp.net:443/dwahlin/getting-started-with-es6-%E2%80%93-the-next-version-of-javascript</link><description>&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_8.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_thumb_3.png" width="200" height="200"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;JavaScript has come a long ways in its 20 years of existence. It’s grown from a language used to define a few variables and functions to one that can be used to build robust applications on the client-side and server-side. Although it’s popularity continues to grow in large part due to its dynamic nature and ability to run anywhere, JavaScript as a language is still missing many key features that could help increase developer productivity and provide a more maintainable code base. Fortunately, &lt;a href="http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts" target="_blank"&gt;ECMAScript 6&lt;/a&gt; (ES6) adds many new features that will take the language to the next level.&lt;/p&gt; &lt;p&gt;This is the first post in a series I’ll be writing that will walk through key features in ES6 and explain how they can be used. I’ll also introduce tools and other languages along the way that can be used to work with ES6 in different browsers as well as on the server-side with frameworks like &lt;a href="http://nodejs.org/" target="_blank"&gt;Node.js&lt;/a&gt;. The goal of this first post is to discuss the viability of using ES6 today and point out resources that can help you get started using it. Let’s kick things off by talking about a few of the key features in ES6.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;Key Features in ES6&lt;/h2&gt; &lt;p&gt;So what are some of the key features in ES6? Here’s a list of some of my favorites:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Arrow functions&lt;/strong&gt; – A short-hand version of an anonymous function.  &lt;li&gt;&lt;strong&gt;Block-level scope&lt;/strong&gt; – ES6 now supports scoping variables to blocks (if, for, while, etc.) using the &lt;em&gt;let&lt;/em&gt; keyword.  &lt;li&gt;&lt;strong&gt;Classes&lt;/strong&gt; – ES6 classes provide a way to encapsulate and extend code.  &lt;li&gt;&lt;strong&gt;Constants&lt;/strong&gt; – You can now define constants in ES6 code using the &lt;em&gt;const&lt;/em&gt; keyword.  &lt;li&gt;&lt;strong&gt;Default parameters&lt;/strong&gt; – Ever wished that a function parameter could be assigned a default value? You can do that now in ES6.  &lt;li&gt;&lt;strong&gt;Destructuring&lt;/strong&gt; – A succinct and flexible way to assign values from arrays or objects into variables.  &lt;li&gt;&lt;strong&gt;Generators&lt;/strong&gt; – Specialized functions that create iterators using &lt;em&gt;function*&lt;/em&gt; and the &lt;em&gt;yield&lt;/em&gt; keyword.  &lt;li&gt;&lt;strong&gt;Map&lt;/strong&gt; – Dictionary type object that can be used to store key/value pairs.  &lt;li&gt;&lt;strong&gt;Modules&lt;/strong&gt; – Provides a modular way of organizing and loading code.  &lt;li&gt;&lt;strong&gt;Promises&lt;/strong&gt; – Used with async operations.  &lt;li&gt;&lt;strong&gt;Rest parameters&lt;/strong&gt; – Replaces the need for using &lt;em&gt;arguments&lt;/em&gt; to access functions arguments. Allows you to get to an array representing “the rest of the parameters”.  &lt;li&gt;&lt;strong&gt;Set&lt;/strong&gt; – A collection object that can be used to store a list of data values.  &lt;li&gt;&lt;strong&gt;Template Strings&lt;/strong&gt; – Clean way to build up string values. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Looking through the features a few things may jump out at you. First off, there’s support for classes and class extension. If you’ve been working with a language such as Java, C#, C++, Python or the many others that support classes this will probably be something you welcome with open arms. By having support for classes we can eliminate some of the patterns we’ve used in the past (Revealing Module Pattern, etc.) in many cases since encapsulation of code will now be natively supported.&lt;/p&gt; &lt;p&gt;Several other key features listed include block level scope, different types of collection objects called Map and Set, built-in support for Promises (deferred/async objects), a concise function syntax referred to as arrow functions, default parameter value assignment, plus much more. I’ll be discussing these features in greater detail in future posts.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;Should I Use ES6 Now or Wait?&lt;/h2&gt; &lt;p&gt;One of the most frequent questions I get about ES6 in my training and consulting work is, “Should I use ES6 now or wait until it has better support?”. There isn’t a single “correct” answer because it depends upon a range of factors such as:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Where will your application will be deployed (client-side or server-side)?  &lt;li&gt;What browsers have to be supported?  &lt;li&gt;What’s the developer environment look like?  &lt;li&gt;What tools do developers have access to use (in an enterprise environment for example)  &lt;li&gt;Are you updating an existing app or starting a new one? &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;br&gt;The good news is that tools exist that enable you to use ES6 today in a variety of situations. However, you’ll need to factor in your unique environment and application requirements before deciding if you start using ES6 now or wait until later. I’m a big fan of the quote, “Use the right tool for the right job”.&lt;/p&gt; &lt;p&gt;To start to answer the question of whether or not you should use ES6 now or if you should wait, you need to look at where you’ll be using it. Will it be on the server with a framework like Node.js? If that’s the case then you can focus on what the V8 JavaScript engine supports. Will the code be running directly in a browser or embedded in a mobile app container like Cordova? In that case using ES6 may be more of a challenge and has to be thought through more carefully if you plan to use native browser support.&lt;/p&gt; &lt;p&gt;If you’re only updating a portion of an existing ES5/ES3 application then ES6 may not be needed given that most of the code base is already ES5/ES3. You’ll have to make that call. On the flipside, if you’re starting a project from scratch (a “greenfield” project) then I think ES6 should be seriously considered since you’ll be setting up well for the future.&lt;/p&gt; &lt;p&gt;The good news is that native ES6 support in browsers such as Chrome, Firefox, and Opera is getting better and better every week. Although Internet Explorer is playing a bit of catch up, they’re planning ES6 support as well (see &lt;a href="https://status.modern.ie" target="_blank"&gt;https://status.modern.ie&lt;/a&gt; for more details). While modern browsers support various ES6 features, ES6 as a whole isn’t quite ready for “prime time” if you need all of the key language features available at once. Here’s a snapshot in time from &lt;a href="http://kangax.github.io/compat-table/es6" target="_blank"&gt;http://kangax.github.io/compat-table/es6&lt;/a&gt; that shows the status of some of the ES6 features across browsers. The information in the image will certainly change so check the website for a more up-to-date view.&lt;br&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_2.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_thumb.png" width="927" height="504"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;br&gt;You’ll note that Internet Explorer 6-9 aren’t listed in the matrix (by default anyway) since they won’t be getting ES6 features - ever. If you still have to support one or more of those browsers your first thought is probably, “I can’t use ES6!”. Although that appears to be the case initially, it’s not true. I’ll introduce some tools that will let you convert ES6 code back to ES5 so that it works in older browsers. Of course there are always limitations that come up depending on application requirements, but at least you’ll know the alternatives out there which should allow you to make a more educated decision about moving to ES6 or sticking with ES5/ES3 for the time being.&lt;/p&gt; &lt;p&gt;If you’re one of the fortunate developers that can target a modern browser that already has some ES6 support in it, you’ll still find that some of the features aren’t supported. The story is improving every week but if you can’t count on specific features being there then it’s hard to justify moving to ES6 today.&lt;/p&gt; &lt;p&gt;As for me personally, I’m moving to ES6 now and even building some applications today that rely on ES6. Does that mean I’m ignoring all of the older browsers out there? Nope – not at all. There are techniques that can be leveraged to use ES6 today while still generating ES5 code that runs fine in older browsers. Let’s take a look at some of the tools that are available.&lt;br&gt;&lt;br&gt;&lt;/p&gt; &lt;h2&gt;Transpilers – Converting Code from One Syntax to Another&lt;/h2&gt; &lt;p&gt;Earlier I mentioned that’s it’s possible to use ES6 today while still targeting older browsers. This is made possible through special converters referred to as “transpilers” (sometimes called “transcoders”) that can convert ES6 code to ES5. By integrating a transpiler into your development workflow you can write ES6 code that automatically gets converted to ES5 code using JavaScript task managers like Grunt or Gulp. Two of the most popular transpilers are:&lt;/p&gt; &lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_4.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_thumb_1.png" width="158" align="right" height="148"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="https://github.com/google/traceur-compiler" target="_blank"&gt;Traceur&lt;/a&gt; – Open source transpiler started by Google that maps ES6 to ES5.  &lt;li&gt;&lt;a href="https://babeljs.io/" target="_blank"&gt;Babel&lt;/a&gt; – Open source transpiler that maps ES6 directly to ES5. It outputs the cleanest code in my opinion.&amp;nbsp; &lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_thumb%5B1%5D_2.png"&gt;&lt;img title="image_thumb[1]" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 5px 10px 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image_thumb[1]" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/57c59b2be72b_127DE/image_thumb%5B1%5D_thumb.png" width="240" align="right" height="93"&gt;&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;In addition to transpilers, you can also use languages such as &lt;a href="http://www.typescriptlang.org/" target="_blank"&gt;TypeScript&lt;/a&gt; to write ES6 code that gets converted to ES5 (or even ES3). TypeScript is a superset of JavaScript that lets you write “typed” ES6 code (define numbers, strings, booleans, etc.) while still allowing it to work in any browser out there by “compiling” it to ES5/ES3. I’ll be showing TypeScript code as well in this series when it applies to a specific ES6 feature.&lt;/p&gt; &lt;p&gt;In the next post in this series I’ll discuss how to get started using transpilers since I think they’re essential to understand and integrate into your workflow if you want to start using ES6 today.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;Browser-based ES6 Playgrounds&lt;/h2&gt; &lt;p&gt;&lt;br&gt;In addition to the transpilers mentioned above, there are also sites and browser extensions available that let you play around with ES6 directly in the browser:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="https://chrome.google.com/webstore/detail/es6-repl/alploljligeomonipppgaahpkenfnfkn?utm_source=chrome-ntp-icon" target="_blank"&gt;ES6 Repl&lt;/a&gt; – Chrome extension that allows you to work with ES6 code directly in the Chrome developer tools.  &lt;li&gt;&lt;a href="http://www.es6fiddle.com/" target="_blank"&gt;ES6 Fiddle&lt;/a&gt; – Website that allows you to type in ES6 code and have it converted to ES5.  &lt;li&gt;&lt;a href="https://google.github.io/traceur-compiler/demo/repl.html#" target="_blank"&gt;Traceur Transcoding Demo&lt;/a&gt; – ES6 playground based on Traceur.  &lt;li&gt;&lt;a href="https://babeljs.io/repl/" target="_blank"&gt;Babel REPL&lt;/a&gt; – ES6 playground based on Babel.  &lt;li&gt;&lt;a href="http://www.typescriptlang.org/Playground" target="_blank"&gt;TypeScript Playground&lt;/a&gt; – TypeScript playground that converts code to ES5. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;ES6 Resources&lt;/h2&gt; &lt;p&gt;In the posts that follow I’ll be discussing ES6 features and showing how they can be used. In the meantime I think it’s important to know about the different resources that are out there. Here’s a list of some sites that I refer to often:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts" target="_blank"&gt;ES6 Language Specification&lt;/a&gt; – The spec that defines all of the planned features in ES6. An unofficial HTML version can be &lt;a href="https://people.mozilla.org/~jorendorff/es6-draft.html" target="_blank"&gt;found here&lt;/a&gt;.  &lt;li&gt;&lt;a href="http://espadrine.github.io/New-In-A-Spec/es6/" target="_blank"&gt;ES6 Features in One Page&lt;/a&gt; – Short synopsis of key ES6 features.  &lt;li&gt;&lt;a href="https://github.com/lukehoban/es6features" target="_blank"&gt;ES6 Features&lt;/a&gt; – Quick look at ES6 features by Luke Hoban.  &lt;li&gt;&lt;a href="https://github.com/sindresorhus/esnext-showcase" target="_blank"&gt;ES.next Showcase –&lt;/a&gt; List of projects that are using or planning to use ES6.  &lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla" target="_blank"&gt;ECMAScript 6 Support in Mozilla&lt;/a&gt; – Details about ES6 support in Firefox.  &lt;li&gt;&lt;a href="http://kangax.github.io/compat-table/es6" target="_blank"&gt;ES6 Browser Support Matrix&lt;/a&gt; – Matrix showing ES6 support across browsers and more.  &lt;li&gt;&lt;a href="https://leanpub.com/understandinges6/read" target="_blank"&gt;Understanding ECMAScript 6&lt;/a&gt; – Online book by Nicholas C. Zakas.  &lt;li&gt;&lt;a href="https://github.com/DanWahlin/ES6Samples" target="_blank"&gt;ES6 Samples&lt;/a&gt; – A repository of samples I’ve put together that will continue to be enhanced and extended over time. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;Conclusion&lt;/h2&gt; &lt;p&gt;&lt;br&gt;Although ES6 still has a ways to go as far as browser support,&amp;nbsp; I’m excited about the different features it offers and the future of JavaScript development. Whether or not you plan on using it right away, it’s important to understand what it offers so that you’re prepared and ready for the (near) future. While this post discussed some of the factors to consider before making the jump to ES6 and covered a few features, tools, and resources, there’s a lot more to discuss.&lt;/p&gt; &lt;p&gt;Stay tuned for the next post covering ES6 tools and how they can be used to write ES6 code today while still supporting a variety of browsers.&lt;/p&gt;</description><pubDate>Sat, 06 Dec 2014 19:58:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/getting-started-with-es6-%E2%80%93-the-next-version-of-javascript</guid><category>ECMASCript6</category><category>ES6</category><category>JavaScript</category></item><item><title>My Thoughts on AngularJS 1.3 and 2.0</title><link>https://weblogs.asp.net:443/dwahlin/my-thoughts-on-angularjs-1-3-and-2-0</link><description>&lt;p&gt;
&lt;script type="text/javascript"&gt;// &lt;![CDATA[
document.write(getHtmlFragment('angularjsGetStarted'));
// ]]&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;br /&gt; &lt;img width="200" height="200" alt="" src="https://aspblogs.blob.core.windows.net:443/media/dwahlin/Windows-Live-Writer/4e7b5c74c52f_746D/angular_thumb_1.png" align="left" /&gt; I've received a ton of questions on &lt;a href="http://asp.us7.list-manage.com/track/click?u=65e00aa00c80d98f762ebeb6e&amp;amp;id=4086649803&amp;amp;e=8b4b262c4b"&gt;Twitter &lt;/a&gt;and through email about the AngularJS 2.0 announcement. Questions such as "What's going on with AngularJS?" and "Should I start a new AngularJS 1.3 project when AngularJS 2.0 looks quite different?". Many people are excited about the modern approach the Angular team is taking with 2.0, a few seem to be predicting doom and gloom, and a few more are worried about what they should do.&amp;nbsp; As a result of all the questions I decided to put together a quick post since 140 characters on Twitter isn&amp;rsquo;t really enough.&lt;/p&gt;
&lt;h2&gt;Stay on 1.3 or Move to Another Framework?&lt;/h2&gt;
&lt;p&gt;While every situation is different and maintenance certainly has to be evaluated carefully with any software project, I personally like what I've seen so far (2.0 is still very early though and may certainly change) and plan to build SPAs in the near term using Angular 1.3. Why? Because it just came out, it gets the job done very well, I don&amp;rsquo;t want to jump to another framework at this point (who's to say they won't be making the move to ES6 as well in the near future to stay relevant?), I have confidence in the AngularJS team, and Angular 1.3 makes me more productive. I'll definitely be keeping a close eye on Angular 2.0 though over the next year or so as it develops.&lt;/p&gt;
&lt;h2&gt;Jumping to ES6&lt;/h2&gt;
&lt;p&gt;Yes, AngularJS 2.0 appears to be a big jump from 1.3 - a HUGE jump some might say! But, I think it's necessary to be ready for a future that includes technologies like ECMASCript 6, Web Components, and more. Some of the features currently in 1.3 that will go away in 2.0 disappear "naturally" as a result of ES6 functionality such as modules and classes. That's a good thing in my opinion. New features announced for 2.0 provide a cleaner, more modern way of building Web applications such as moving directives to Web Components (another good thing IMO but will likely cause some app migration work). I'd recommend &lt;a href="http://asp.us7.list-manage.com/track/click?u=65e00aa00c80d98f762ebeb6e&amp;amp;id=7aaa402b46&amp;amp;e=8b4b262c4b"&gt;reading the post&lt;/a&gt; from the AngularJS team and taking time to watch some of the videos from &lt;a href="http://asp.us7.list-manage.com/track/click?u=65e00aa00c80d98f762ebeb6e&amp;amp;id=5f1dc3d769&amp;amp;e=8b4b262c4b"&gt;ng-europe&lt;/a&gt; (start with &lt;a href="https://www.youtube.com/watch?v=lGdnh8QSPPk" target="_blank"&gt;this one&lt;/a&gt; and then watch &lt;a href="https://www.youtube.com/watch?v=gNmWybAyBHI" target="_blank"&gt;this one&lt;/a&gt;). I'm excited about what they're planning even if it means extra work may possibly be required down the road to migrate from 1.3 to 2.0 (we don't know how much yet since 2.0 is in the early stages). Syntax changes that ultimately improve the way I write future applications don&amp;rsquo;t bother me although I acknowledge it can cause extra work and has to be planned for appropriately.&lt;/p&gt;
&lt;h2&gt;Things to Consider&lt;/h2&gt;
&lt;p&gt;Every company will have to consider if they stick with AngularJS 1.3 for awhile or if they jump ship and move to something else. It's not like an app has to move to 2.0 once it finally comes out. But, if part or all of the app has to be ported to a new version at some point then that's something to carefully think over. I've been in the position of maintaining a large number of apps and realize that the decision to stay on 1.3 or go in a different direction is a hard one to make. I can sympathize with companies and developers who are in that position.&lt;br /&gt;&lt;br /&gt;I don't know if the migration process will be easy or hard - time will tell. I don't currently like any of the other options any better than Angular 1.3 though (that's a very personal preference ...many other viable and capable solutions certainly exist) which is why I'm OK with using it over the next year. When 2.0 is finally released I'll have to evaluate if I (and my company&amp;rsquo;s clients) stay on 1.3 or take the time to migrate the app. I won't pretend to know what's best for your company as every company has unique requirements and it&amp;rsquo;s something&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;you have to talk over with your team. There&amp;rsquo;s no easy answer there and I totally get that. It really boils down to whether or not you're OK with using AngularJS 1.3 for awhile, if you want to learn an entirely different framework (which may possibly shift due to ES6 and other technologies being released), or if you want to write something custom. I'm fine with what Angular 1.3 offers and like the fact that at least I know what to expect (or some of what to expect) when 2.0 is released down the road.&lt;br /&gt;&lt;br /&gt;In hindsight (everyone loves to play Monday morning quarterback) I wish a more jQuery-ish approach would've been announced with a 1.x and 2.x branch. That would put to rest many of the version and migration fears that people have. Who knows - maybe the AngularJS team will end up doing something like that given that over 1600 apps inside of Google rely on Angular.&lt;/p&gt;
&lt;h2&gt;Change is Guaranteed&lt;/h2&gt;
&lt;p&gt;My good friend &lt;a href="http://asp.us7.list-manage2.com/track/click?u=65e00aa00c80d98f762ebeb6e&amp;amp;id=423aabde3d&amp;amp;e=8b4b262c4b"&gt;Shawn Wildermuth&lt;/a&gt; sums all of this up nicely in his latest post titled, &lt;a href="http://asp.us7.list-manage1.com/track/click?u=65e00aa00c80d98f762ebeb6e&amp;amp;id=2b7f0732d0&amp;amp;e=8b4b262c4b"&gt;It is Too Soon to Panic on AngularJS 2.0&lt;/a&gt;. The last paragraph in the post states the following (he has a lot of other good points so please read the whole post):&lt;br /&gt;&lt;br /&gt;"I don&amp;rsquo;t know what you should do. I don&amp;rsquo;t. I won&amp;rsquo;t pretend to. Keep an open mind and keep your ears open. See where it&amp;rsquo;s going and under the current and future risks in pinning yourself to the library. You&amp;rsquo;ll have to hook your wagon to some horse (AngularJS means to Google, ReactJS to Facebook, etc.) But ultimately as I&amp;rsquo;ve been talking about for years, be prepared for change and look forward to learning what is coming around the corner."&lt;br /&gt;&lt;br /&gt;If you work in the Web world you have to expect, be prepared for, and plan on change. Some of the other frameworks out there will likely be changing as well (maybe big changes, maybe small changes) due to the new technologies coming out. If they don&amp;rsquo;t change they&amp;rsquo;ll be considered &amp;ldquo;old&amp;rdquo; in the near future as ES6 makes its way onto the scene. The challenge is deciding on how you&amp;rsquo;ll deal with change and the approach to take moving forward. As Shawn points out, no one (including myself) has all the answers. I always go with my gut feeling whenever possible.&amp;nbsp; It&amp;rsquo;s quite possible that in a year or so I may do a pivot to another technology. I&amp;rsquo;ve had to do that many times over my career. At this point I&amp;rsquo;m happy with what 1.3 has to offer though.&lt;/p&gt;
&lt;p&gt;Some will agree with what I say and some will disagree (quite loudly in some cases). That&amp;rsquo;s part of the fun of being a Web developer.&lt;/p&gt;</description><pubDate>Fri, 31 Oct 2014 16:05:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/my-thoughts-on-angularjs-1-3-and-2-0</guid><category>AngularJS</category><category>SPA</category><category>JavaScript</category><category>ES6</category></item><item><title>Cancelling Route Navigation in AngularJS</title><link>https://weblogs.asp.net:443/dwahlin/cancelling-route-navigation-in-angularjs</link><description>&lt;p&gt;&lt;img style="background-image: none; padding-top: 0px; padding-left: 0px; padding-right: 0px; border-width: 0px;" border="0" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Media/AngularJS_thumb_1008B166.jpg" /&gt;&lt;/p&gt;
&lt;p&gt;
&lt;script type="text/javascript"&gt;// &lt;![CDATA[
document.write(getHtmlFragment('angularjsGetStarted'));
// ]]&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;This post has been updated to cover AngularJS 1.3+.&lt;br /&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Routing provides a nice way to associate views with controllers in AngularJS using a minimal amount of code. While a user is normally able to navigate directly to a specific route, there may be times when a user triggers a route change before they&amp;rsquo;ve finalized an important action such as saving data.&amp;nbsp; In this type of situation you may want to cancel the route navigation and ask the user if they&amp;rsquo;d like to finish what they were doing so that their data isn&amp;rsquo;t lost. In another situation the user may try to navigate to a view that requires some type of login or other special handling. If the user hasn&amp;rsquo;t logged in yet the app can automatically redirect them to a login screen (keep in mind that for security the server always has to double-check things since JavaScript can easily be changed).&lt;/p&gt;
&lt;p&gt;When route navigation occurs in an AngularJS application a few key events are raised. One is named &lt;strong&gt;$locationChangeStart&lt;/strong&gt; and the other is &lt;strong&gt;$routeChangeStart&lt;/strong&gt;. Starting with AngularJS 1.3+ this is the order that events fire (see &lt;a href="https://github.com/angular/angular.js/commit/f4ff11b01e6a5f9a9eb25a38d327dfaadbd7c80c" target="_blank"&gt;this commit&lt;/a&gt; by &lt;a href="https://github.com/tbosch" target="_blank"&gt;Tobias Bosch&lt;/a&gt; for more details):&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;&lt;strong&gt;$locationChangeStart - - $routeChangeStart - - $locationChangeSuccess - - $routeChangeSuccess&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Both events allow route navigation to be cancelled starting with AngularJS 1.3+ by calling &lt;strong&gt;preventDefault()&lt;/strong&gt; on the &lt;strong&gt;event&lt;/strong&gt; object.&amp;nbsp; Let&amp;rsquo;s take a look at the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event first and see how it can be used to cancel route navigation when needed.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;The $locationChangeStart Event&lt;/h2&gt;
&lt;p&gt;&lt;br /&gt;If you dig into the AngularJS core script you&amp;rsquo;ll find the following code that shows how the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event is raised as the &lt;strong&gt;$browser&lt;/strong&gt; object&amp;rsquo;s &lt;strong&gt;onUrlChange()&lt;/strong&gt; function is invoked:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;$browser.onUrlChange(&lt;span class="kwrd"&gt;function&lt;/span&gt;(newUrl, newState) {
    $rootScope.$evalAsync(&lt;span class="kwrd"&gt;function&lt;/span&gt;() {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; oldUrl = $location.absUrl();
        &lt;span class="kwrd"&gt;var&lt;/span&gt; oldState = $location.$$state;

        $location.$$parse(newUrl);
        $location.$$state = newState;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; ($rootScope.$broadcast(&lt;span class="str"&gt;'$locationChangeStart'&lt;/span&gt;, newUrl, oldUrl,
            newState, oldState).defaultPrevented) {
            $location.$$parse(oldUrl);
            $location.$$state = oldState;
            setBrowserUrlWithFallback(oldUrl, &lt;span class="kwrd"&gt;false&lt;/span&gt;, oldState);
        } &lt;span class="kwrd"&gt;else&lt;/span&gt; {
            initializing = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
            afterLocationChange(oldUrl, oldState);
        }
    });
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!$rootScope.$$phase) $rootScope.$digest();
});&lt;/pre&gt;
&lt;style type="text/css"&gt;&lt;!--
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
--&gt;&lt;/style&gt;
&lt;p&gt;&lt;br /&gt;&lt;br /&gt;The key part of the code is the call to &lt;strong&gt;$broadcast&lt;/strong&gt;. This call broadcasts the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event to all child scopes so that they can be notified before a location change is made. To handle the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event you can use the &lt;strong&gt;$scope.$on()&lt;/strong&gt; function (in a controller for example) or you can use &lt;strong&gt;$rootScope.$on()&lt;/strong&gt; (in a factory or service for example). For this example I&amp;rsquo;ve added a call to &lt;strong&gt;$on()&lt;/strong&gt; into a function that is called immediately after the controller is invoked to watch for location changes:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;function&lt;/span&gt; init() {
    
    &lt;span class="rem"&gt;//initialize data here..    &lt;/span&gt;

    &lt;span class="rem"&gt;//Make sure they're warned if they made a change but didn't save it&lt;/span&gt;
    &lt;span class="rem"&gt;//Call to $on returns a "deregistration" function that can be called to&lt;/span&gt;
    &lt;span class="rem"&gt;//remove the listener (see routeChange() for an example of using it)&lt;/span&gt;
    onRouteChangeOff = $scope.$on(&lt;span class="str"&gt;'$locationChangeStart'&lt;/span&gt;, routeChange);
}

&lt;span class="kwrd"&gt;function&lt;/span&gt; routeChange(&lt;span class="kwrd"&gt;event&lt;/span&gt;, newUrl) {
   ...
}&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;This code listens for the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event and calls &lt;strong&gt;routeChange()&lt;/strong&gt; when it occurs. The value returned from calling &lt;strong&gt;$on&lt;/strong&gt; is a &amp;ldquo;deregistration&amp;rdquo; function that can be called to detach from the event. In this case the deregistration function is named &lt;strong&gt;onRouteChangeOff&lt;/strong&gt; (it&amp;rsquo;s accessible throughout the controller in this example). You&amp;rsquo;ll see how the &lt;strong&gt;onRouteChangeOff&lt;/strong&gt; function is used in just a moment.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Cancelling Route Navigation with $locationChangeStart&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;routeChange()&lt;/strong&gt; callback triggered by the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event displays a modal dialog similar to the following to prompt the user:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/7dac51414bc7_13775/image_4.png"&gt;&lt;img title="image" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/7dac51414bc7_13775/image_thumb_1.png" width="549" height="262" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s the code for &lt;strong&gt;routeChange()&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;function&lt;/span&gt; routeChange(&lt;span class="kwrd"&gt;event&lt;/span&gt;, newUrl, oldUrl) {
    &lt;span class="rem"&gt;//Navigate to newUrl if the form isn't dirty&lt;/span&gt;
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!$scope.editForm || !$scope.editForm.$dirty) &lt;span class="kwrd"&gt;return&lt;/span&gt;;

    &lt;span class="kwrd"&gt;var&lt;/span&gt; modalOptions = {
        closeButtonText: &lt;span class="str"&gt;'Cancel'&lt;/span&gt;,
        actionButtonText: &lt;span class="str"&gt;'Ignore Changes'&lt;/span&gt;,
        headerText: &lt;span class="str"&gt;'Unsaved Changes'&lt;/span&gt;,
        bodyText: &lt;span class="str"&gt;'You have unsaved changes. Leave the page?'&lt;/span&gt;
    };

    modalService.showModal({}, modalOptions).then(&lt;span class="kwrd"&gt;function&lt;/span&gt; (result) {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (result === &lt;span class="str"&gt;'ok'&lt;/span&gt;) {
            onRouteChangeOff(); &lt;span class="rem"&gt;//Stop listening for location changes&lt;/span&gt;
            $location.path($location.url(newUrl).hash()); &lt;span class="rem"&gt;//Go to page they're interested in&lt;/span&gt;
        }
    });

    &lt;span class="rem"&gt;//prevent navigation by default since we'll handle it&lt;/span&gt;
    &lt;span class="rem"&gt;//once the user selects a dialog option&lt;/span&gt;
    &lt;span class="kwrd"&gt;event&lt;/span&gt;.preventDefault();
    &lt;span class="kwrd"&gt;return&lt;/span&gt;;
}&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Looking at the parameters of &lt;strong&gt;routeChange()&lt;/strong&gt; you can see that it accepts an &lt;strong&gt;event&lt;/strong&gt; object and the new route that the user is trying to navigate to. The &lt;strong&gt;event&lt;/strong&gt; object is used to prevent navigation since we need to prompt the user before leaving the current view. In this example we&amp;rsquo;re checking if the form is dirty (changes have been made) and if the user hasn&amp;rsquo;t saved the changes yet. In cases where the form is dirty the user can be notified and given a change to stay on the current view.&lt;/p&gt;
&lt;p&gt;As the code in &lt;strong&gt;routeChange()&lt;/strong&gt; executes a modal dialog is shown by calling &lt;strong&gt;modalService.showModal()&lt;/strong&gt; (see my &lt;a href="http://weblogs.asp.net/dwahlin/archive/2013/09/18/building-an-angularjs-modal-service.aspx" target="_blank"&gt;previous post&lt;/a&gt; for more information about the custom &lt;strong&gt;modalService&lt;/strong&gt; that acts as a wrapper around Angular UI Bootstrap&amp;rsquo;s $modal service). From there the route navigation is cancelled at the end of the function (event.preventDefault()) since the user needs to choose if they want to stay on the view and finish their edits or leave the view and navigate to a different location.&lt;/p&gt;
&lt;p&gt;If the user selects &amp;ldquo;Ignore Changes&amp;rdquo; then their changes will be discarded and the application will navigate to the route they intended to go to originally. This is done by first detaching from the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event by calling &lt;strong&gt;onRouteChangeOff()&lt;/strong&gt; (recall that this is the function returned from the call to &lt;strong&gt;$on()&lt;/strong&gt;) so that we don&amp;rsquo;t get stuck in a never ending cycle where the dialog continues to display when they click the &amp;ldquo;Ignore Changes&amp;rdquo; button. A call is then made to &lt;strong&gt;$location.path($location.url(newUrl).hash())&lt;/strong&gt; to handle navigating to the target view. If the user cancels the operation they&amp;rsquo;ll stay on the current view.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;The $routeChangeStart Event&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event isn&amp;rsquo;t the only game in town with AngularJS. Within &lt;strong&gt;angular-route.js&lt;/strong&gt; you&amp;rsquo;ll find the following function that raises a &lt;strong&gt;$routeChangeStart&lt;/strong&gt; event as a route is about to be changed:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;function&lt;/span&gt; prepareRoute($locationEvent) {
    &lt;span class="kwrd"&gt;var&lt;/span&gt; lastRoute = $route.current;

    preparedRoute = parseRoute();
    preparedRouteIsUpdateOnly = preparedRoute &amp;amp;&amp;amp; lastRoute &amp;amp;&amp;amp; preparedRoute.$$route === lastRoute.$$route
        &amp;amp;&amp;amp; angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
        &amp;amp;&amp;amp; !preparedRoute.reloadOnSearch &amp;amp;&amp;amp; !forceReload;

    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!preparedRouteIsUpdateOnly &amp;amp;&amp;amp; (lastRoute || preparedRoute)) {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; ($rootScope.$broadcast(&lt;span class="str"&gt;'$routeChangeStart'&lt;/span&gt;, preparedRoute, lastRoute).defaultPrevented) {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; ($locationEvent) {
                $locationEvent.preventDefault();
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;br /&gt;&lt;br /&gt;Looking through the code you&amp;rsquo;ll see that a call is made to &lt;strong&gt;$rootScope.$broadcast&lt;/strong&gt; to raise the &lt;strong&gt;$routeChangeStart&lt;/strong&gt; event.&lt;/p&gt;
&lt;p&gt;How does this event fit in with &lt;strong&gt;$locationChangeStart&lt;/strong&gt; since they sound quite similar? When &lt;strong&gt;$locationChangeStart&lt;/strong&gt; fires you get access to the new URL the user is trying to go to as well as the old URL as strings. When &lt;strong&gt;$routeChangeStart&lt;/strong&gt; fires you can get access to the raw route definition defined using &lt;strong&gt;$routeProvider &lt;/strong&gt;(more on this in a moment). This can be useful if you want to cancel a route based upon data provided in the route definition.&lt;/p&gt;
&lt;p&gt;For example, let&amp;rsquo;s say that before a user navigates to certain routes they need to be redirected to a login page if one of our AngularJS factories determines that they haven&amp;rsquo;t logged in yet. Keep in mind that there&amp;rsquo;s no such thing as client-side security in this scenario and the redirect could always be hacked (quite easily) using browser developer tools. As a result your server-side code should always double-check security for secured pages/views, data, and more. But, a factory can certainly track if a user has logged in or not and then redirect them. If someone hacks the script the server would detect it assuming things are setup correctly. Let&amp;rsquo;s take a closer look at the &lt;strong&gt;$routeChangeStart&lt;/strong&gt; event and how it can be used to cancel route navigation or redirect a user to another route.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Cancelling Route Navigation with $routeChangeStart&lt;/h2&gt;
&lt;p&gt;&lt;br /&gt;How do you determine whether or not a route has to be handled in a special way as a user tries to navigate to it? Although AngularJS doesn&amp;rsquo;t have anything built-in, you can always add your own properties onto routes defined in an app. For example, here&amp;rsquo;s an example of a route that includes a custom property named &lt;strong&gt;secure&lt;/strong&gt;:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;$routeProvider.when(&lt;span class="str"&gt;'/customeredit/:customerId'&lt;/span&gt;, {
    controller: &lt;span class="str"&gt;'CustomerEditController'&lt;/span&gt;,
    templateUrl: viewBase + &lt;span class="str"&gt;'customers/customerEdit.html'&lt;/span&gt;,
    secure: &lt;span class="kwrd"&gt;true&lt;/span&gt; &lt;span class="rem"&gt;//This route requires an authenticated user&lt;/span&gt;
});&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This code specifies that the route requires extra handling and requires the user to be logged in before navigating to it. In addition to marking a route as &amp;ldquo;secure&amp;rdquo;, you could also define additional information such as allowed roles or any other special requirements (keeping in mind that the server always has to double-check security and that you would never want to push anything super sensitive security-wise down to the client). As a route is about to change you can listen for the &lt;strong&gt;$routeChangeStart&lt;/strong&gt; event and use the event parameters to get access to the route definition - including any custom properties. Here&amp;rsquo;s an example of hooking up to the event using &lt;strong&gt;$rootScope.$on()&lt;/strong&gt; in Angular&amp;rsquo;s&lt;strong&gt; run()&lt;/strong&gt; function:&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;app.run([&lt;span class="str"&gt;'$rootScope'&lt;/span&gt;, &lt;span class="str"&gt;'$location'&lt;/span&gt;, &lt;span class="str"&gt;'authService'&lt;/span&gt;,
    &lt;span class="kwrd"&gt;function&lt;/span&gt; ($rootScope, $location, authService) {
            
        &lt;span class="rem"&gt;//Client-side security. Server-side framework MUST add it's &lt;/span&gt;
        &lt;span class="rem"&gt;//own security as well since client-based &amp;ldquo;security&amp;rdquo; is easily hacked&lt;/span&gt;
        $rootScope.$on('&lt;span class="str"&gt;$routeChangeStart'&lt;/span&gt;, &lt;span class="kwrd"&gt;function&lt;/span&gt; (&lt;span class="kwrd"&gt;event&lt;/span&gt;, next, current) {&lt;br /&gt;
          &lt;span class="rem"&gt;//Look at the &lt;strong&gt;next&lt;/strong&gt; parameter value to determine if a redirect is needed&lt;/span&gt;        
        });

}]);&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;When &lt;strong&gt;$routeChangeStart&lt;/strong&gt; fires you get access to the event object, the next route, and the current route. It&amp;rsquo;s quite similar to &lt;strong&gt;$locationChangeStart&lt;/strong&gt; although the parameter data is very different and provides a lot more information. In the case of &lt;strong&gt;$routeChangeStart&lt;/strong&gt; the &lt;strong&gt;next&lt;/strong&gt; parameter shown in the previous code will give you access to the following:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/7dac51414bc7_13775/image_2.png"&gt;&lt;img title="image" style="background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;" border="0" alt="image" src="https://aspblogs.blob.core.windows.net/media/dwahlin/Windows-Live-Writer/7dac51414bc7_13775/image_thumb.png" width="345" height="273" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Notice that by going through the &lt;strong&gt;$$route&lt;/strong&gt; property you can get to the raw route definition data including the custom &lt;strong&gt;secure&lt;/strong&gt; property. While going through any property that starts with &lt;strong&gt;$$ &lt;/strong&gt;is generally frowned upon due to the &amp;ldquo;private&amp;rdquo; nature of these properties (they could change in future versions), there isn&amp;rsquo;t a viable alternative at the present time when you need to get to the route data as the &lt;strong&gt;$routeChangeStart&lt;/strong&gt; event is fired. I hope that will change in the future and that route data will be made more publicly accessible.&lt;/p&gt;
&lt;p&gt;If you don&amp;rsquo;t like that option you could always have a factory or service (such as &lt;strong&gt;authService&lt;/strong&gt; in the code above) store information about special routes and then evaluate the &lt;strong&gt;newUrl&lt;/strong&gt; parameter passed by the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event to determine if a given route needs to be cancelled or redirected. That would involve some string comparisons but could certainly get the job done.&lt;/p&gt;
&lt;p&gt;As &lt;strong&gt;$routeChangeStart&lt;/strong&gt; fires you can use the following code to trigger a redirect to another view if needed. Notice that the &lt;strong&gt;secure&lt;/strong&gt; property shown earlier is checked and used to determine if the path needs to change:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (next &amp;amp;&amp;amp; next.$$route &amp;amp;&amp;amp; next.$$route.secure) { 
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!authService.user.isAuthenticated) { 
        $rootScope.$evalAsync(function () { 
            $location.path('/login&lt;span class="str"&gt;'&lt;/span&gt;); 
        }); 
    } 
} &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Notice that the call to &lt;strong&gt;$location.path()&lt;/strong&gt; is wrapped in the &lt;strong&gt;$evalAsync()&lt;/strong&gt; method so that the location changes properly and everything stays in sync. If you don&amp;rsquo;t include that little bit of code things won&amp;rsquo;t work properly.&amp;nbsp; If you want to completely cancel route navigation you can also call &lt;strong&gt;event.preventDefault()&lt;/strong&gt; as shown earlier with the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; event code. That&amp;rsquo;s a new feature that&amp;rsquo;s now available in AngularJS 1.3+.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;br /&gt;&lt;br /&gt;&lt;/h2&gt;
&lt;p&gt;The key to canceling routes is understanding how to work with the &lt;strong&gt;$locationChangeStart&lt;/strong&gt; and &lt;strong&gt;$routeChangeStart&lt;/strong&gt; events and cancelling or redirecting as needed . You can see this code in action in the &lt;a href="https://github.com/DanWahlin/CustomerManagerStandard" target="_blank"&gt;Customer Manager application&lt;/a&gt; available on Github (specifically &lt;a href="https://github.com/DanWahlin/CustomerManagerStandard/blob/master/CustomerManager%2Fapp%2FcustomersApp%2Fcontrollers%2Fcustomers%2FcustomerEditController.js" target="_blank"&gt;customerEditController.js&lt;/a&gt; and &lt;a href="https://github.com/DanWahlin/CustomerManagerStandard/blob/master/CustomerManager%2Fapp%2FcustomersApp%2Fapp.js" target="_blank"&gt;app.js&lt;/a&gt;). Learn more about the &lt;a href="https://weblogs.asp.net/dwahlin/learning-angularjs-by-example-the-customer-manager-application" target="_blank"&gt;application here&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 19 Oct 2014 17:08:00 GMT</pubDate><guid isPermaLink="true">https://weblogs.asp.net:443/dwahlin/cancelling-route-navigation-in-angularjs</guid><category>AngularJS</category><category>JavaScript</category><category>SPA</category></item></channel></rss>