Web components is a term that encompasses three new W3C standards. These three standards give us the ability to create custom elements.
The custom elements spec allows you to create new HTML tags that you can add to your page. They behave like any existing HTML Tag. To use this spec, you create a new ES6 class that inherits from an existing element. Then you can define what’s in that custom element and add it to your application as a new tag.
This term used to describe the virtual DOM used in React. Now it referrers to the ability to create an encapsulated DOM tree. This is used in conjunction with the custom elements spec to create components.
HTML templates allow you to create snippets of HTML with slots where you can add your own custom markup. This makes it easier to encapsulate boilerplate html and DRY up your code.
If you want to learn how to make a native web component, my favorite set of tutorials is on the Mozilla Developer Network.
I also built a few simple native web components that you can check out:
There are two popular ones out there. The first, and most popular, is Polymer. Polymer’s goal is to add a layer of syntactic sugar to the existing web components spec. Polymer also includes polyfills that allow you use your components across different web browsers. If you want to learn more, check out the Polymer Project.
The other library is Stencil.js. Stencil was built by the folks at Ionic. Ionic builds a popular mobile and Progressive Web Application (PWA) framework. Their existing method of using Angular was too slow for a modern PWA. To alleviate this problem, they moved to web components. They also built a library to help them along the way. Stencil makes use of TypeScript and TSX (TypeScript JSX) to build components in a way that feels familiar to folks using React or Angular. It takes the best concepts of Angular and React and combines them together.
I also have some Stencil demos available. I have a component library and I consume that library from a React application.
There are a couple of situations where web components are really helpful. The first is when you’re building component library for use in lots of different projects. This can include your own personal library of components, a core library of components for your company, or set public set of components. Companies that make component libraries, like Ionic or Telerik, have much to gain from web components.
The second situation is if you want to build a progressive web application. PWAs are rated on their “time to paint”, ie. how fast you can get content to show when you load the application. Applications that rely on frameworks can take up to several seconds to load. Web components load instantaneously. Even in my trivial demo code, there’s a noticeable different in a page built with web components and one built in React.
As we learn how to do more with web technologies, web standards evolve. Component based frameworks have become the dominant paradigm for building modern web apps. While component based frameworks like React and Angular are great, sometimes you don’t want or need the bulk. Web components combine several standards to build components using native browser technology. To make things easier, you can use libraries like Polymer and Stencil to help you out. Break free of framework churn by using the platform and building web components.
Being a developer is committing to a lifetime of learning new skills. Over the past few weeks, I’ve been working on grokking cloud architecture on Azure. Like many devs on the Microsoft stack, I’ve played around with Azure. I built a few resources and watched some demos, but until recently, I hadn’t taken the time to really invest in the skill set. I never felt like I had a good understanding of Azure as a whole. In this post, I’m going to talk about my experiences learning about Azure over the past few weeks.
The toughest part of learning Azure is that it’s huge. “The cloud” is nebulous by definition, and Azure doesn’t disappoint. Azure isn’t a single thing, but collection of many different products and services. This abundance makes it tough to get started.
When thinking about Azure, you can divide the services into a few large buckets.
Here’s a high level overview of what’s in Azure:
In Azure, you can build virtual machines, virtual networks, load balancers, and other virtual appliances. If it exists in a data center, you can probably make one in Azure.
App services host specific kinds of applications without the need to configure servers. You usually run these on top of VMs, but you don’t need to configure them. You just pay for the compute resources. Azure has app services for web applications, apis, mobile apps, and functions.
Azure has several services that support security and identity. This includes several flavors of Active Directory and Key Vault, which stores application secrets. Azure also has several different mechanisms to scan for security issues.
If you have data, Azure can store in a ton of different ways. You have your basic storage accounts, which can hold blobs, queues, files, and json objects. You also have Azure SQL Server and several other hosted SQL databases (including Postgres and MySql). If you need worldwide scale, you can use Cosmos DB. Azure also has a pile of big data tools like HDInsight and Stream Analytics.
Azure has a lot of APIs you can take advantage of in your applications. This includes things like Cognitive Services, Notification Hubs, and Multifactor Authentication. You can leverage these tools to shortcut things you used to have to do yourself.
This is by no means an exhaustive list. Azure updates constantly and new offerings are added all the time.
To help navigate this landscape, I chose to base my studying on the Microsoft Azure certifications. While I still haven’t convinced myself to take the actual exams, the exam outline is a useful map for learning. I’ve always been on the fence about the actual value of developer certifications. Much of what’s covered is stuff that’s easy to look up in the docs and developer certs lack the clout of networking certifications. Software also changes so fast that certs tend to either rapidly expire or are out of date. Azure certifications update every three months, which makes it hard to find solid resources. Regardless of the value of the certifications, the outlines are useful.
Here’s the two certs I looked at
I began by working my way through a 70-532 course on Udemy. I watched all the videos and built plenty of demos while going along with the course. The course claims to prepare you for the exam, but it doesn’t some close to the level of detail you’d need. It’s an OK overview, but the more I learned about Azure, the more I felt like this course was a waste of my time.
After reviewing some other courses from Udemy, I found the platform to be hit-and-miss. Udemy also has a pretty serious piracy problem where pirates will steal courses from other people and host them on Udemy. While the Azure course I saw was decent, I can’t recommend using Udemy as a first rate source for developer content.
Here’s the course I used
After working my way through that course, I searched for other resources. Microsoft offers free Azure training through Pluralsight. It’s been a while since I’ve checked out Pluralsight and they’ve done a lot to improve the platform. The last time I used it, Pluralsight had cranked up their video acquisitions. This was good for variety, but choice overload made it nearly impossible to figure out what course to take. Nothing sucks quite like ten courses that look identical. Fortunately, Pluralsight introduced learning paths. Now, instead of sorting through hundreds of courses, you can sort through a few dozen learning paths. Each path has a handful of courses that go from beginner to advanced. You can also use their handy Pluralsight IQ function to gauge your skill level. It’s like a mini certification test. They’re also free, so check them out if you’re up for a challenge.
Azure Learning Paths
I split my time between several of the Azure related learning paths. They have a 70-532 related path, but they also had paths geared towards solutions architecture and developers. As mentioned before, I’m more interested in gaining useful skills than becoming certified. I don’t feel any obligation to stick to the certification content.
Here’s a few of the courses I looked at:
The 70-532 path has an excellent set of courses by Mike Pfeiffer.
This path dealt with Azure at the architecture level. Simon Allardice’s course gave a nice conceptual framework to hang some of the more detailed concepts on. Simon’s course directed me to Scott Allen course for a more detailed view.
Scott Allen is an excellent presenter and his advanced course in the .NET developer path does not disappoint.
Pluralsight has some great resources and a lot of the Azure content is free, so I recommend you check it out.
Besides watching courses, I built a ton of small demo projects. Like anything else, you can’t just watch a video and expect to know how to do something. You need to get your hands dirty. While watching the videos, I’d follow along with the course by building along. Additionally, I worked my way through the various exam objectives make small demo projects.
When doing demo projects, I recommend you build small. Building small helps you focus on the topic at hand while avoiding getting sunk in non-relevant details. It also gives you references you can go back to later.
Another excellent resource is Microsoft’s own Azure documentation. Our friends at Microsoft poured a lot of love into their documentation and it shows. The Azure docs have lots of reference information combined with specific tutorials. It’s worth having a tab with the Azure docs open at all times.
While I’ve worked diligently these past few weeks, I don’t feel like an Azure ninja yet. I’m going to continue to build my skills and improve. To do that, I’m going to do a few things.
Keep building demos. Practice makes perfect.
Finish the Pluralsight 70-532 course and watch some of the other advanced Azure courses.
Explore some of the services I didn’t get a chance to play with yet. I still haven’t spent much time working with Azure’s data analytics offerings yet.
Continue to subscribe to various Azure resources like BuildAzure.com and the Azure Weekly newsletter. It’s easier to keep up when the information comes to you.
Seek opportunities to get real life experience with Azure. There’s a big difference between an easy looking demo and actually using something in production.
If I had to start over again, I’d do things a little differently. First, I’d start with the Pluralsight learning paths. The Pluralsight content is free and higher quality than the Udemy content. It’s hard to argue with cheaper AND better. Other than that, I’d have spent more time building things in PowerShell and the C# API instead of using the portal. While most demos occur in the Azure portal, you’re missing out on a big part of what makes Azure cool. Azure makes it easy to represent your infrastructure as code.
My current learning process is a cycle between watching videos, building demos, answering questions, and reading docs. When I learn new things, I alternate consumption, recall, and creation. It’s not fancy, but it works.
If you’re interested in learning more about Azure and cloud technologies, head out to the Azure Docs and check out some of the free Azure training. It’s amazing what we can do with a few credits and some knowledge.
Let’s say you have a table of events. Each event has a beginning and an ending date. How would you get a list of the events that happened within each quarter?
Example: A event that begins on 2-1-2017 and ends on 8-1-2017 would have an entries for Q1 2017, Q2 2017, and Q3 2017.
If you’re dealing with a single value, you can just use DATEPART(quarter, [DateValue]), but if you’re looking to figure out if an event occurs in a range, it’s a little more complicated. Here’s how to do it.
The first step to getting this data is to get a list of quarters with their respective date ranges. One way to do this is to use a recursive common table expression. CTE’s are snippets of SQL that you can put above your main query to create tables to join against. A recursive CTE creates values by calling itself. Here’s a CTE that’ll give us a list of quarters from the start date to the current date. When using recursive CTEs, make sure you have a termination condition or you’ll have a nice infinite loop on your hands.
DECLARE @start Date = '01-01-2010'; DECLARE @End Date = GETDATE(); WITH Quarters_CTE AS ( SELECT @start as [Start], DateAdd(quarter, 1, @start) AS [End], DATEPART(quarter, @start) AS [Quarter], DATEPART(year, @start) AS [Year] UNION ALL SELECT DateAdd(quarter, 1, [Start]), DateAdd(quarter, 1, [End]), DATEPART(quarter, DateAdd(quarter, 1, [Start])), DATEPART(year, DateAdd(quarter, 1, [Start])) FROM Quarters_CTE WHERE [End] < @end ) SELECT * FROM Quarters_CTE Q
The next step is compare our events with the quarters. We want a different entry for each quarter the event occurs in. To do this you can join up with the table. You can use non-equality based comparison operators in join queries, so we filter by date range. Here’s the complete query:
DECLARE @start Date = '01-01-2010'; DECLARE @End Date = GETDATE(); WITH Quarters_CTE AS ( SELECT @start as [Start], DateAdd(quarter, 1, @start) AS [End], DATEPART(quarter, @start) AS [Quarter], DATEPART(year, @start) AS [Year] UNION ALL SELECT DateAdd(quarter, 1, [Start]), DateAdd(quarter, 1, [End]), DATEPART(quarter, DateAdd(quarter, 1, [Start])), DATEPART(year, DateAdd(quarter, 1, [Start])) FROM Quarters_CTE WHERE [End] < @end ) SELECT * FROM Quarters_CTE Q JOIN [Events] E ON e.StartDate < q.[End] AND (e.EndDate is null OR e.EndDate > q.[Start])
From there you can aggregate your data as needed.
One of the great things about modern development is how easy you can leverage code written by others. Package managers like NPM and NuGet make this process even easier. The only problem is that there’s so much available code to choose from. For example, there’s over 100,000 packages on NuGet. In my travels as a .NET developer, I’ve found a few packages that made my life a little easier. Here’s a list of 10 handy packages you use in your next project:
Refit is a library that helps you automate calls to REST APIs. To use it, you first define your APIs as an annotated interface. Then you use Refit to turn that interface into a class. I love this package because it allows you to create incredibly terse API callers.
This package should be installed by default on any .NET API project. It automatically adds swagger documentation to your API. In addition to that, Swashbuckle creates a handy web page you can use to document and explore your API. I’m a big fan of this package because it links your docs with your actual code. It becomes even more important in a microservices environment where you have lots of services to keep track of.
Polly is a fault handling library that allows you to write more resilient code. To do this, you create policies. These policies define what happens when a particular operation fails. These policies include things like Retry, Circuit Breaker, and Fallback. It’s great for operations where there’s a chance of failure, like a REST call over a flaky network connection.
LINQ is my preferred way to deal with enumerable objects. MoreLINQ adds lots of useful operators to traditional LINQ.
Dapper is a Micro OR/M made by the same folks that gave us Stack Overflow. If you hate fiddling with Entity Framework configurations and just want to write some damn SQL, Dapper is for you. It’s been around for a while, but I’ve only recently gotten a chance to use on a project. After trying it, I’m a huge fan of this approach. I’ve spent way more hours than I’d care to admit trying to shoehorn Entity Framework’s API to get the data I want. I’ve also spent countless hours trying to figure out why my five lines of C# produced 3000+ lines of sketchy looking SQL. Sometimes it’s easier to do things yourself.
Generally, when you want to unit test an operation that interacts with the file system, you would need to write a separate interface and class to abstract away the IO operations. With Filesystem Abstractions, you no longer need to do that. Filesystem Abstractions wraps System.IO in a useful interface. Instead of making your own file system access class, you can inject an IFileSystem and get access to all of the IO methods you know and love. Filesystem Abstractions also includes classes to mock the file system, so testing IO operations becomes really easy.
Moq is a handy library for mocking interfaces in unit tests. You’re probably already using this one.
Xunit is a unit testing framework for testing .NET code. It’s like MSTest and NUnit, but it has a few interesting features. One of those is the use of theories. A theory allows you to run the same test with several different parameters. It’s a handy way to test multiple values without having to write multiple tests.
MiniProfiler injects a small unobtrusive profiler into your MVC application. As you complete operations, Miniprofiler will display the time it took to complete each step. Tools like this make it easy to diagnose performance bottlenecks.
The CSV helper makes it easy to create and read delimited files. If you work in an environment where you have to create or process lots of CSVs, this package is a good one to employ.
Ever wish you could see into the future? I’d love to have known about Bitcoin eventually hitting 17k back when you could pick one up for a dollar. A $200 dollar investment at the time would make for a nice retirement today. Too bad foresight isn’t 20/20.
Even if you don’t want to know everything that happens in the future, you make predictions everyday. You predict that you’ll get paid regularly (if you’re a salaried employee). You make certain assumptions about your health and abilities. You likely predict that the technologies you’re currently learning will be useful in the future. The skill of predicting the future is essential.
It’s also a skill that most of us aren’t very good at. To improve my own prediction skills, I’ve read several books over the past year about prediction and how to discern the future. Here’s a few of the better reads.
Kevin Kelly lays out 12 different technological trends that will shape our world in the coming decades. I found this to be an interesting look ahead. Different trends include the dissolution of specific versions of software, increased personalization through automation, and the rise of virtual reality.
Nate Silver one of the top predictors of election outcomes and other events. His book talks about some of the difficulties in creating useful models. He emphasizes the importance of probabilistic thinking and enumerating your own inclinations.
In Black Swan, Taleb talks about the need to prepare for unpredictable events which he calls “black swans”. Even in situations that look stable (ie. the real estate market), certain system shocks can suddenly appear and destroy the fortunes of the unprepared. Only one of these black swan events can cancel out the gains of all previous years. Black Swans work both ways though. You can profit if you can jump onto a positive Black Swan event.
Ray Kurzweil is regarded as one of the most accurate futurists in the industry. Age of Spiritual Machines was written in 1999 and contains predictions for 2009 and 2019. While he credits himself with being mostly right, I laughed out loud at some of the predictions while I was listening to the book in my car. Even the best futurists often fail.
One of the major themes throughout all these books is the need to write down your own predictions and see how well (or poorly) you did. People have self-serving biases that distort past predictions. Writing them down prevents you from forgetting how awesome you thought MySpace and Betamax were going to be. Learning about your own fallibility makes it easier to correct your judgement and improve. To improve my own prediction abilities, and provide my future self with some entertainment, I’m going to make a series of predictions. I put a reminder in my calendar to check back over the next few years to see how well I did.
Disclaimer: Don’t bet the farm on this stuff.
We won’t see a major new JS framework this year. The market has stabilized around React, Angular, and Vue
Rationale: Web frameworks have reached a stability point. Each framework generation has offered diminishing returns and the time to learn them isn’t getting any shorter. Unless something major comes along, we probably aren’t going to see any major new web frameworks.
Web Components will move towards the mainstream
AI is over-hyped.
Rationale: With the advent of commoditized AI, people are freaking out about various doomsday scenarios. While I think AI is important, it’s probably not going to be all that different from every other major technological shift.
XR (augmented and virtual reality) will continue to advance, but people won’t find the “killer app” for it yet
Rationale: There’s a ton of long-term potential with XR, but I don’t think we’ve figured out the “killer app” yet. We’re still in the phase where people are experimenting and building stuff that’s not useful.
Analog technologies will continue to grow in popularity.
Rationale: During the late 1800’s and the 1900’s, people began to go to the woods for recreation. This was a reaction to urban life of the time. The urban populace wanted to get away from the concrete jungle. As cities incorporated more green elements (parks, gardens, etc…), the desire to camp has flattened. As technology advances, people tend modernize past activities into modern forms of recreation (camping, hunting, hiking, fishing, etc…). The current trend towards analog books, vinyl records, and table top board games is an offshoot of this broader trend.
3-4 Major cloud service providers will reach feature parity and crowd most of the other contestants out of the market.
Rationale: Most major technical markets tend to settle on 3-5 competitors. Every major technology category tends to have a large number of competitors at first who get acquired or go out of business. Cloud providers will be no different. AWS is the current champion, but I think Azure and Google will also be in the top three. I also think each cloud provider will copy the features of its main competitors so there’s not a huge difference between platforms.
The Bitcoin / crypto bubble will burst, but prices will be higher than they were before the bubble.
Rationale: This has happened several times before and will likely happen several more times. The end game will either be crypto stabilizing at high price or tanking. I’m guessing it’s going to eventually stabilize.
Crypto-currencies will move away from proof of work algorithms because they consume too much power.
XR will become commonplace as people figure out what to do with it. Augmented reality glasses will replace cell phones.
Self-driving car technology will mature, but won’t be commonplace due to regulatory issues
There will be a 1 trillion-dollar tech company.
The market capitalization of social media companies is going to tank
Rationale: The centralized nature of the big social media companies has led many people to criticize them. They are a huge target for anti-tech criticism. Social media in general will fall out of favor as more people learn about the abusive practices of the social media companies. Once enough people leave the network, it’ll trigger a spiral where the whole network tanks. Look at MySpace for reference.
Social media will fragment as people realize that they don’t want to be exposed to the whole public.
Rationale: Our society is becoming increasingly polarized while major social media companies are creating arbitrary content filtering policies. Platforms like Discourse and Diaspora allow people to build decentralized communities that can cater to their users needs.
There will be a wave of rapidly falling prices on things that were once labor intensive as AI makes labor far more effective.
There will be at least a few big crypto bubbles before crypto-currency settles on a stable valuation.
Bitcoin will lose out to another crypto-currency like Ethereum or Litecoin.
Rationale: I think Bitcoin is the Apple Newton of crypto-currencies. I think that other coins are going to innovate past Bitcoin and render it obsolete.
Analog and digital will merge due to technologies like 3d printing and the Internet of Things.
Rationale: Things that are analog will become digital and digital things will be able to become analog very easily. A big part of why analog product are succeeding in the modern age is because of technology. Just as cars and lightweight materials made camping a recreational activity, things like easy customization through automated manufacturing and platforms like Etsy will make analog products more appealing. The Internet of Things also gives us the ability to embed intelligence in our analog items.
The web will decentralize as a response to abuse by large technology companies.
There will be at least one major industry shock on par with the financial crash of 2008.
Rationale: At least one highly regulated industry will melt down. There are several industries that have consolidated power and become ossified over the past few decades. Government regulations tend to push industries into a consolidated oligarchy because larger companies are more able to bear the cost of regulatory burdens. When there aren’t many competitors to pick up the slack if one company fails, the whole industry becomes fragile. That fragility exposes the industry to “black swan” events that can cause major damage. Candidates for explosion include: banking (again), telecom, energy companies, and health insurance.
AI and other automation technologies will trigger major political shifts within the next 10-15 years
Self-driving cars will be commonplace in 10-15 years
Rationale: The technology is close today, but cultural and regulatory factors are going to slow down the adoption of self driving car technology.
Major medical breakthroughs will increase health-span and lifespan
Rationale: Life expectancy will climb to new highs and retirement will be a financial goal as opposed to something that happens due to disability. This has major political implications as social security will become even less viable.
Basic income will be standard in most industrialized countries.
Rationale: Technology creates asymmetric effects where small numbers of people can command extremely high amounts of wealth. Technology can also melt down entire industries and leave lots of people scrambling for work. While I think that we won’t have the crazy waves of unemployment that most tech skeptics portray, governments will need to simplify their welfare systems to account for people having to take regular career breaks to retrain in new skills.
The American University system will be replaced by new technology enabled educational processes
Rationale: The American university system has ever-increasing prices for ever decreasing value. Getting a college degree used to guarantee a well-paying job. Now it only guarantees a large amount of debt. People are going to look for more vocational skills training along with shorter times to marketable skills. Since people will likely be retraining several times over their careers, traditional institutions won’t be able to keep up. The technology industry is almost there today. Platforms like Pluralsight, Udemy, and Safari allow technology professionals to constantly train in new skills.
While it’s fun to make random speculations about the future of technology, it’s an important skill to be able to predict major shifts and prepare for them in advance. I’m sure I’ll come back to this post in a few years and have a good laugh at some of these predictions.
There are a few ways to implement a monolithic Angular application. The easiest way is to use the built in template. Visual Studio comes with an Angular template that includes some nice features. I prefer to use the Angular CLI, so I don’t use the included template. If you also want to use the Angular CLI, I have a post on how to use Angular CLI with a .NET Core project.
Each of the architectures in this post shines in a particular set of circumstances. Monoliths are great for small to medium sized projects, but are not ideal for larger applications. Serverless architecture is great for small apps, but not for large enterprise applications. Microservices architecture works well for large applications, but isn’t worth the overhead on small ones. Figure out the application you want to build and choose wisely.
Building web applications is hard work. Not only do you have to build the application, you need to figure out where to host it. Ever want to skip all the frustrating server provisioning and focus on your code? If so, then serverless architecture is worth a look. In this article, you will learn how to build setup a serverless Angular app using Azure.
The term “serverless” is somewhat misleading. There are still servers, but you don’t have to care about them.
Serverless architecture runs on managed services that host your code. Server level concerns like figuring out how much memory you need, fault tolerance, and scalability are abstracted away. You don’t need to pick out a VM or service tier. The service scales automatically. You upload your code and go. The service takes care of the rest.
Serverless platforms come in several different flavors including APIs like Firebase and functions as a service (FAAS). FAAS is where you host small bits of code in the cloud. Think micro-services to the nth degree. All of the major cloud providers have some flavor of FAAS. Examples include: Amazon Lambda, Google Cloud Functions, and Azure Functions. You can even host your own FAAS using OpenFAAS, though that kinda defeats the point. (comprehensive list of serverless platforms)
For the purposes of this application, we are going to use Azure Functions for our backend API.
While Angular application are complex to develop, they compile into a handful of static files. There’s no reason you can’t throw these files up on any commodity static host. In this case, we’re going to use Azure Web Sites. While this solution isn’t 100% serverless, (you have to pick a hosting tier) hosting a handful of files on the free tier is close enough for me. To add another layer of performance, we’re also going to use Azure CDN to cache the files so they load quickly.
Here’s what we’re going to do:
We start off by creating a new Azure Function app. Starting from the Azure Portal, click “New” search for “function” and click Function App. This will bring you to the new function app blade. Type in your app name (it has to be unique), add the rest of your info and click Create.
Now we’re going to make a function. Either hit the plus sign or click “New Function”. This brings you to the function template screen before. Functions can be activated by a variety of triggers including DB requests, files, and manual activation. We’re going to use the HTTP Trigger. HTTP triggers are activated by an HTTP request. Select “HttpTrigger – C#”.
You should now have this lovely boilerplate. This code can handle any http request and sends back a response.
Let’s ditch that boilerplate and drop in our API code. This is just going to be a simple GET request. Feel free to pretend we’re calling a database here instead of just returning a list.
If you’d like to test your shiny new function, click the “get function url” link and drop that into Postman. As you can see here, things are working splendidly.
You can also test using the built-in testing utility on the right side of the function window.
Now that we have our backend setup, let’s put together our front end. In this case, we’re going to set up an Angular application built with the Angular CLI. Since this post is about setting up the architecture, I’m not going to go into great detail about the application itself, which can be found in this github repo. If you’re using another front-end library like React or Vue.js, this setup should be mostly the same.
To begin, create an Azure Web App. (New -> Web App). The free tier should be adequate for our needs. We’re just hosting a few files. If you want to use your own custom domain, you’ll need to use a higher tier.
Now we need to get the static files to host. If you’re using Angular CLI (and you should be…), the command to do this is:
ng build --prod --aot
After that command runs, head over to the dist folder of your angular app. It should look something like this:
The next step is to get your static files into the web app. I used FTP, though you can download a publish profile if you want. Drop your static files into the wwwroot folder. At this point, you should be able go to the URL and your app will load.
The next step is to set up a CDN. Since these are just static files, we can use a CDN to serve them. Azure CDN also allow us to serve the site over https without having to pay for a plan that supports SSL. To set one up, go to New, search “CDN”, click “CDN”, and click “Create”.
This brings up the CDN profile blade. Type in your name, select “Standard” for your pricing tier, and select your web site from the dropdown. Then click “Create”. Now you have a CDN for your static files.
Now that we have our web app in place, we need to set up the CORS (cross origin resource sharing) headers on our function. Browsers, by default, prevent your website from accessing APIs that don’t match the url of your web application (CORS error pictured below). This feature helps to prevent Cross Site Request Forgery (CSRF) attacks, but is sometimes kind of annoying. If you want to use your function API from your web application, you’ll need to add a CORS header to your API.
To begin, go back to your function app and go to the “Platform features” tab and click “CORS”.
This brings you to the CORS screen. Add the url/s of your web app. You can use “*”, which is the wildcard route, but you shouldn’t because it’s rather insecure. It’s best to use your web app’s URL here.
At this point, we have a functioning web application, but there’s still one more issue to resolve. Like most SPA applications, Angular supports client side urls that don’t correspond to server-side resources. All of our application code is served from index.html on the root url, but we use the Angular router to map urls to parts of the application. For example, in our sample app, if we navigate from the home page to the Products page it works great, but if we hit refresh we get a 404. (error below) This is because there’s no page on the server for that URL. To fix this we need to add a URL re-write rule to redirect anything that’s not a static asset back to the index page.
To do this, we’re going to create a web.config file with our rewrite rule.
Here’s our rule (finished product):
This rule takes anything that isn’t a file, directory, or an asset (*.html, *.js, *.css) and redirects it to the index page. If you have fonts or images in your application, you should probably add rules for those file extensions as well.
Then, take that web.config file and drop it into the wwwroot folder of our web app. App urls should now redirect appropriately.
If you’d like to build an Angular application and host it for cheap in the cloud, this is a great way to do it. The serverless architecture is great for MVPs, simple applications, and proof of concept applications. It’s an easy way to get code into the world with minimum fuss.
If you’d like additional information or access to the code referenced in this post, check out the links below.
When doing a technology demo, it’s important that everyone in the room can see your screen. This usually means bumping up your view to 150%-200% depending on the screen, room, and relative blindness of the people in your audience. I demo a lot of web technologies, so I find myself showing the Chrome developer tools. Fun fact, when you zoom web pages in Chrome, that setting doesn’t apply to the developer tools. Fortunately, this is easy to fix.
To zoom in Chrome developer tools:
open the developer tools window,
hold down ctrl,
press + or – to zoom in and out.
Have you ever worked on an application with a jungle-like class inheritance hierarchy? Everything in the app inherits from two layers of classes and it’s impossible to follow a single line of functionality. You get code reuse, but at the cost of incomprehensible spaghetti code. I, for one, find that price too steep. In this post, we’re going to learn how to build code that’s easy to reuse, easy to test, and most important, easy to read.
We have many design patterns in object oriented programming. One the most useful ones is the composite reuse principle (aka. composition over inheritance). This term sounds a little opaque, but it’s not hard to understand. It means that you should design your classes as a series of loosely coupled components instead of using a multilayered class hierarchy for code reuse.
Here’s an example:
Practically speaking, this means breaking down inheritance hierarchies into plug-able services. Then you can inject those services using your favorite dependency injection framework.
While using composition may seem more complicated, there are several advantages.
If you’re using class hierarchy for code reuse, ditch that approach and favor composition instead. Your code base will thank you for it.
Like fashion, computing works in cycles. Things that were once looked at as passe come back with retro vengeance. For .NET development, the console is back. Consoles combined with lightweight editors like Visual Studio Code are becoming increasingly popular. Call me a hipster, but I’m all for this change. I hate waiting around for my editor and I never have to do that in a console or Visual Studio Code.
Unfortunately, if you’re living in the world of Windows, the default command line options are lacking. Not only are CMD and Powershell ugly, they lack basic usability features found in Linux and OSX. There is a better way. Cmder is a Windows console emulator that bundles several command line tools together into one fantastic package. It’s the Cadillac of Windows consoles.
Here’s what it looks like:
Cmder has a nice tabbed interface. You can run multiple consoles without having to deal with a bunch of windows. It also supports several different types of consoles including: CMD (enhanced with Clink), Powershell, and Bash.
You also get full control of the appearance of the shells including the font, color, etc… Cmder has many themes, but the default Monokai theme is good enough for me.
More importantly, you can create custom tasks. A custom task is a specific command window that you can define. You can specify the shell, what parameters it’s called with, and what directory is opened. You can have a command line setup for each application you work on. You no longer need to open a command line and manually navigate to your app folder each time you open up the console.
To make a custom task, do the following:
From Cmder, type Win + Alt + T. This takes you the tasks windows. You can also click the arrow next to the plus sign and click “Setup Tasks”.
This window allows you to reorder and reorganize the different defaults in Cmder. Hit the plus sign to add your own.
In this case, this is a console task that opens a specific project I’m working on.
After you setup your new task, click “Save Settings”. You should see your new shell in the list of available presets. Then you can open that exact shell whenever you want.
If you want to supercharge your Windows console, check out Cmder.