Angular Child Routes Explained

Angular 2+ has a neat way to deal with child routes but those coming from AngularJS may find them a bit confusing. In this post, I will show how to use them with <router-outlet></router-outlet>for a seamless experience.

First, lets take a look at an abbreviated version of the app-routing.ts file.

const appRoutes: Routes = [
    {
        path: 'product/:id',
        component: ProductComponent,
        children: [
            { path: 'detail', component: ProductDetailComponent }, 
            { path: 'reviews', component: ProductReviewsComponent }
        ]
    }
];

In this excerpt, there is a parent route, product/:id. This route has two different child routes: detail and reviews which will match the paths product/:id/detail and product/:id/reviews. Easy enough. However, getting them rendered correctly is the trick but very easy once you understand what is expected. The parent route is also a top level route, which means that the top level template will need a single <router-outlet></router-outlet> tag.

Then, in the template hooked to the parent product route will also need a single <router-outlet></router-outlet> tag. The second router-outlet tag will be used to render details and reviews. As an example:

<h3>{{product.Name}}</h3>
<router-outlet></router-outlet>

I like to keep these rules in mind when dealing with routes and outlets:

  1. My top-most app template will have a single router-outlet tag that will be used to render all top-level routes.
  2. Each top-level route that has children will need a router-outlet tag in it’s own template.

 

That is all there is to it. I feel that this convention is a drastic improvement over the routing used in AngularJS.

The 3 Best Self-Help Books I Have Read in 2018…so far

I read quite a bit. I read to fall asleep. I read to pass the time between Pomodoros when I am taking the short break. I read during lunch. I also listen to audio books and subscribe to Kindle Unlimited so I have plenty of options. However, I don’t typically read the most recent fad books unless I think I can get something out of them so these are not the latest but I do feel they are all three great books for different reasons.

1. You Are a Badass – Jen Sincero

I really liked the pacing and dry humor of this book. It felt like the author had been to the bottom and turned her life around and that is always inspiring. The humor, though. That is why you should read this book. It is self help in disguise. I read this one twice.

2. The 5 Second Rule – Mel Robbins

I have a huge procrastination problem. Like a lot of other people, if I have a deadline looming, my procrastination magically disappears and I get work done at a breakneck speed. Parkinson’s Law at work. The author explains a lot of the science behind the 5 Second Rule and more knowledge is always a good thing. While reading the book, I felt that it might help me with my procrastination problem but I have struggled to implement it into my daily routines. Whether I realize it or not, when procrastinating, I seem to just turn my brain off and veg out. Still, there are lessons in this book that can help anyone learn about their own procrastination problem.

3. I Will Teach You To Be Rich – Ramit Sethi

I love this book for the general common sense. Financial literacy is extremely bad in the USA and if this book were required reading in high school, it would improve that knowledge area by leaps and bounds. I have encouraged my own children to read the book since I finished it because the systems it encourages you to implement can create lasting change in your life. It doesn’t just tell you what to do, it gives you and action plan for either turning your life around or setting you up to succeed.

The Case Against Self-Aware ViewModels in ASP.NET MVC

ViewModels in ASP.NET MVC are a valuable tool and are widely considered a best practice in developing MVC applications. In this post, I will make a case for why ViewModels should NOT be self-aware.

ViewModels are a commonly used mechanism to deliver everything a View needs in a single object. Without them, you would have to push them to the View in a different manner. In a Single Page Application (SPA), this might be a moot point since you will likely be loading the View, then pulling the data separately. However, in a true MVC application, you would have to rely on the terrible ViewBag process or an equally bad mechanism to deliver that data since a Model that a View references can only be a single object. So, now that I have described why ViewModels are a good and necessary item, lets look at how to populate them. When you are working with ViewModels, I see three viable options that everyone has easy access to for loading the data into those ViewModels.

  1. Let your Controllers do it.
    BAD PROGRAMMER! Stop that! Your Controllers should be anorexic. So skinny that they could hula hoop in a Cheerio. Using your Controllers to populate data is just a really bad practice. This is not what they are intended to do. Controllers deliver Views and that is about all they should be doing. You can do this but you really shouldn’t and most experienced programmers will agree.
  2. Let the ViewModels load themselves.
    At one time, this was my preferred option and made the most sense to me. However, when you start to really look at it, it clearly violates the Single Responsibility Principle (SRP). This also makes the ViewModel object a bit less reusable. Below is an example of what this might look like.

    HomeController.cs

    public class HomeController : Controller
    {
        private IContactRepository _contactRepository = null;
    
        public HomeController(IContactRepository contactRepository)
        {
            _contactRepository = contactRepository;
        }
    
        public ActionResult Index()
        {
            HomeIndexViewModel viewModel = new HomeIndexViewModel(_contactRepository);
    
            if (viewModel.LoadViewModel())
            {
                return View(viewModel);
            }
            else
            {
                return RedirectToAction("ServerError");
            }
        }
    
        public ActionResult ServerError()
        {
            return View();
        }
    }

    HomeIndexViewModel.cs

    public class HomeIndexViewModel
    {
        private IContactRepository _contactRepository = null;
    
        public HomeIndexViewModel(IContactRepository contactRepository)
        {
            _contactRepository = contactRepository;
        }
    
        public List<Contact> Contacts { get; set; }
    
        public bool LoadViewModel()
        {
            Contacts = _contactRepository.GetContacts();
    
            return true;
        }
    }

    Note that we are already using a service (repository) to actually load the data so why muddy the waters by having the LoadViewModel method on the ViewModel class? It just doesn’t make much sense.

  3. Have an intermediary do it.
    This is really the only choice that aligns with SOLID principles. Your service knows about the ViewModel and can utilize a library like AutoMapper to make the process easier. You will have to be careful about where you place the ViewModel if your service is not in the MVC project because the MVC project knows about the service and not vice versa.

What do you think? How do you handle this problem in your own projects?

Using Unity in ASP.NET MVC 5 in Less than 5 Minutes

Unity is a dependency injection framework built by the Pattern and Practices team at Microsoft. In this post, I will give you a quick overview of implementing Unity into an ASP.NET MVC project very quickly.

What is Unity?

Unity is a very nicely integrated library from Microsoft that has both configuration-based and code-based dependency injection options. In this post, I will focus on the code-based configuration but may circle back later to do config-based. It takes almost no effort to get Unity up and running. You can contrast this with the amount of effort to get Ninject up and running in an MVC application. Neither requires a herculean effort but Unity is slightly easier, I think. You will notice they are remarkably similar, though.

Unity and ASP.NET MVC 5

Unity has a Nuget package available specific for MVC.

1. Right click the MVC project in Solution Explorer and click ‘Manage Nuget Packages…’.
2. In the Nuget Package Manager window, select the Browse tab.
3. Search for Unity.
4. Select the Unity.MVC package. I am using version 5.0.13 so if you select a different version, it may work for you just as it does now and it may not.
5. Click the Install button.

Okay, Unity is installed. How do we use it?

1. Add a folder to the project named code.
2. Add a class named MessageService.cs to the code folder.
3. Add an interface named IMessageService.cs to the code folder.
4. Open the MessageService.cs file and replace the class declaration with the code below:

public class MessageService : IMessageService
{
    public string GetMessage()
    {
        return "Hello, World!";
    }
}

5. Open the IMessageService.cs file and replace the interface declaration with the following code:

public interface IMessageService
{
    string GetMessage();
}

6. Open the HomeController.cs file and  replace the class declaration with the following code:

public class HomeController : Controller
{
    private IMessageService _messageService = null;

    public HomeController(IMessageService messageService)
    {
        _messageService = messageService;
    }

    public ActionResult Index()
    {
        ViewBag.Message = _messageService.GetMessage();
        return View();
    }
}

7. Finally, right click the Index() action and select ‘Go To View’. Replace the HTML in the view with the following code:

<div class="jumbotron">
    <h1>@ViewBag.Message</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

8. One last thing. In the App_Start\UnityConfig.cs file, add the following line to the RegisterTypes method:

container.RegisterType<IMessageService, MessageService>();

That is all there is to it. If you set a break point in the Home Controller constructor, you will see that Unity is injecting the MessageService into that constructor in place of the IMessageService interface because of the change in bullet point 8. You should see the ‘Hello, World!’ message on the home page when it launches.

If you want to skip all the copy/pasting you can download the code from here.

Using Ninject in ASP.NET MVC 5 in Less than 5 Minutes

Ninject is a great Dependency Injection framework and works wonderfully with ASP.NET MVC 5. In this post, I will show you how to get Ninject running in a MVC project in less than 5 minutes.

What is Ninject?

Ninject is a light weight, versatile dependency injection framework that can be used in .NET applications. It allows you to focus on writing software instead of writing configuration and wiring code.

What is dependency injection and why is it important?

Dependency injection is the process of configuring or setting up your application to have one object supply the dependencies of another object or objects. In short, you are configuring your application to have one object inject the dependencies other objects require in a predictable manner.

Dependency injection has a few benefits:

1. It allows you to decouple the dependency from the consumer.
2. It allows you to create more testable code.

These two benefits allow us as developers to create much better code though, it isn’t automatic. You still have to make good decisions and write good code.

Ninject and ASP.NET MVC 5

You can get Ninject running in an ASP.NET MVC application really quickly. Low barrier to entry is very important because if the process is painful, you are less likely to do it. Here we go.

1. Right click the ASP.NET MVC project in solution explorer and click ‘Manage Nuget Packages…’.
2. In the Nuget Package Manager, select the Browse tab.
3. Search for Ninject.
4. Select Ninject.MVC5 and select 3.2.1 in the Version drop down beside the Install button.
5. Click the Install button.

Now, we have Ninject installed, lets learn how to use it.

1. Add a folder to the project named code.
2. Add a class named MessageService.cs to the code folder.
3. Add an interface named IMessageService.cs to the code folder.
4. Open the MessageService.cs file and replace the class declaration with the code below:

public class MessageService : IMessageService
{
    public string GetMessage()
    {
        return "Hello, World!";
    }
}

5. Open the IMessageService.cs file and replace the interface declaration with the following code:

public interface IMessageService
{
    string GetMessage();
}

6. Open the HomeController.cs file and  replace the class declaration with the following code:

public class HomeController : Controller
{
    private IMessageService _messageService = null;

    public HomeController(IMessageService messageService)
    {
        _messageService = messageService;
    }

    public ActionResult Index()
    {
        ViewBag.Message = _messageService.GetMessage();
        return View();
    }
}

7. Finally, right click he Index() action and select ‘Go To View’. Replace the HTML in the view with the following code:

<div class="jumbotron">
    <h1>@ViewBag.Message</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

8. One last change. In the App_Start\NinjectWebCommon.cs file, add the following line to the RegisterServices method:

kernel.Bind<IMessageService>().To<MessageService>();

That is all there is to it. If you set a break point in the Home Controller constructor, you will see that Ninject is injecting the MessageService into that constructor in place of the IMessageService interface because of the change in bullet point 8. You should see the ‘Hello, World!’ message on the home page when it launches.

If you want to skip all the copy/pasting you can download the code from here.

Hello, World!

Hello! One quick introductory paragraph and I will get to what is important. My name is Jason Bentley. I have been a software engineer for nearly 20 years. I have worked for small businesses and Fortune 50 corporations. During that time, I have developed document management systems, project management systems, mobile apps and software used by realtors, utility workers, accountants, teachers, executives, and the general public. I LOVE DEVELOPING SOFTWARE! I have absolutely no idea how I got lucky enough to fall into a career I love but I feel both blessed and thankful.

There are two points in the first paragraph that I want to go further into in this one. First, as I said, I love developing software. I love starting new projects. I love the way it feels to start a new project and build it from nothing. Unfortunately, I am not so passionate about finishing projects. Especially personal projects. In the past, I have lacked discipline. I have finished a few but I really don’t know what caused me to finish those and ship the rest to the graveyard of broken dreams. There are three different systems I have started over on about a dozen times. Crazy, right? I know there are others out there that do the same thing. I am a serial starter and a terrible finisher. However, there are two of those systems that I have restarted for the upteenth time that I just feel really strongly about. I think they could be amazing if I, you know, ever get around to finishing them. Second, I fell into this career somewhat accidentally. I didn’t go to school for it. I didn’t finish college at all. I went for a while and got bored or lazy. I am not sure which. It was a long time ago. I went the self-taught path and I have no regrets. Stay with me, this is going somewhere.

Lets move to formal education. I disliked my own formal education but really enjoyed figuring it out myself. It took me about 2 years to really get up to speed in my own time between working 40-60 hours per week, raising kids, and sleeping. It took me two years to learn enough so that I could go into a programming interview and not embarrass myself. If I had only known exactly what I needed to learn, I could have probably done it in 9-12 months fairly easily, I think, and been an asset when I was hired. That is why I am making Edumacate.me. I don’t intend for it to be just another site for learning to program. There are dozens of those already. There are hundreds of career paths that can be laid out in an easy to follow set of instructions that can lead to a life of fulfillment and purpose and there are thousands of secondary skills we all need in our lives such as sales, marketing, branding, writing, and so on that will enhance our professions and lives in many different ways.

I can imagine woodworkers getting instructions on creating cabinets or hand-cutting dovetails. I can imagine software developers building projects to learn a new framework. I can imagine teachers learning new ways to educate. I can imagine entrepreneurs learning how to properly create brochures or presentations or a business plan. I can imagine people from all walks of life learning all manner of things. This is the first time in the history of mankind that virtually all of the world’s knowledge is freely available at our fingertips.

What we lack, however, is organization. I can’t imagine a topic that normal, every day people would want to learn that isn’t available on Youtube or available on a thousand different pages available to everyone for free. You have to know what to search for, however, and in what order and how to distinguish between bad sources and good sources. Organizing the Internet’s knowledge is completely doable. This is what I hope to grow Edumacate.me into: a flexible framework for the organization of the Internet’s collective knowledge into learning plans and project plans to accomplish anything!

Stay tuned.