Tech Junkie Blog - Real World Tutorials, Happy Coding!: August 2019

Saturday, August 31, 2019

When you need to do an insert into multiple database table you need to the get the ID of the insert so that you could use that ID for the next insert. Here is how you would do that with the Scope_Identity()which gets the last inserted ID back to you if you execute your query with the ExecuteScalar() method.

                SqlCommand cmd = new SqlCommand("INSERT INTO Users (" +
                    "LoginName," +
                    "FirstName," +
                     "LastName," +
                     "Password," +
                     "Email," +
                     "DOB," +
                     "Sex" +
                     ") VALUES (" +
                    "@Email," +
                    "@FirstName," +
                     "@LastName," +
                     "@Password," +
                     "@Email," +
                     "@DOB," +
                     "@Sex)" + 
                     " Select Scope_Identity();",conn);


Wednesday, August 28, 2019

A lot of examples on logging in ASP.NET Core shows you how to add console logging to your ASP.NET Core application.  But it's pretty useless in a real world application.  What you really want is to write to a file or a database.  There's a package called Microsoft.Extensions.Logging.Log4Net.AspNetCore that will make your application use log4Net.

Here are the steps to use log4Net:

1.  Right click on your NorthwindCafe.Web project and select "Manage NuGet Packages"

Managing Nuget Packages With Visual Studio





























Tuesday, August 27, 2019

In the previous post we successfully used the repository pattern to retrieve products from the database and set them to the Product objects.

In this post we are going to display those products in the Index.cshtml page

Here are the steps:

1. Open the Index.cshtml page in the Views/Home folder
2. Now declare a model of enumerable of products at the top of the page like this 

@model IEnumerable<Product>

You will noticed that the Product class has a red underline on it, when you mouse over Visual Studio will say that the Product reference is missing

Mouseover to find missing reference in Visual Studio











Monday, August 26, 2019

Now that we have our data in the database it is time for us to show the data to our users and we going to use the repository pattern to show our data.  A repository pattern is basically a conduit between the database and our business objects that has built in CRUD operations.  It is ideal for LOB applications.  There are many websites and books that explains the repository pattern better than I do.  Feel free to explore them.

Here are the steps to create a product repository for the products in the database:

1. Create a folder in the NorthwindCafe.Web solution call "Data"
2. Create an interface call IProductRepository in the "Data" folder, this will be the interface that we implement our repository from.

The code of the IProductRepository should look like this

using NorthwindCafe.Web.Models;
using System.Collections.Generic;

namespace NorthwindCafe.Web.Data
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetProducts();
    }
}

Friday, August 23, 2019

In the previous blog we created the NorthwindCafe database with Entity Framework Core.  Now we are going to seed the database so that we can work with the data.

Here are the steps to seed the NorthwindCafe database:

1.  Create a file call DBInitializer in the NorthwindCafe.Web  "Models" folder, in the file type in the following code


using System.Linq;

namespace NorthwindCafe.Web.Models
{
    public class DbInitializer
    {
        public static void Initialize(NorthwindContext context)
        {
            context.Database.EnsureCreated();

            if(context.Categories.Any())
            {
                return;
            }

            var categories = new Category[]
            {
               new Category {Name = "Coffee", Description="Coffee", Products = new Product[] { new Product { Name = "Dark Roast", Description = "Dark Roast", Price = 2.0M } } },
               new Category {Name = "Tea", Description="Tea", Products = new Product[] { new Product { Name = "Chai", Description = "Chai", Price = 1.5M } } },
               new Category {Name = "Pastry", Description="Pastry", Products = new Product[] { new Product { Name = "Cupcake", Description = "Cupcake", Price = 1.25M } } },
               new Category {Name = "Food", Description = "Food", Products = new Product[] { new Product  { Name = "Hamburger", Description = "Hamburger", Price = 5.0M } } }
            };

            foreach (var c in categories)
            {
                context.Categories.Add(c);

            }

            context.SaveChanges();
        }
    }
}


Thursday, August 22, 2019

In this post will are going to finally create the database that we have been preparing for in the last previous blog posts.  It's a two step process, first you have to add the NorthwindContext to the application in the Startup class, then you have to run the Entity Framework migration tool.

Here are the steps to create your NorthwindCafe database:

1.  Open the Startup.cs file, then type the following lines in the ConfigureServices method
 
            var connectionString = Configuration["Data:NorthwindContextConnection"];

            services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString));

The line above gets the connection string from the appSettings.json file that we've created earlier. Then use the AddDbContext method in the services instance.  Dependency injection will take care of the plumbing for you.  Using lamba expression we tell the Entity Framework to use the Sql Sever provider for Entity Framework core.

Make sure you have the following namespaces in your Startup class

using NorthwindCafe.Web.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;


Wednesday, August 21, 2019

In our previous post we created the models for our Northwind Cafe application.  In this blog we will create the DbContext class which is the conduit between your entity classes and the database.  Think of it as a bridge that the database and the entity framework has to cross to get to each other.

Follow the steps below to create the NorthwindContext:

1. Create a class in Models folder call NorthwindContext

Tuesday, August 20, 2019

In the previous post we added a configuration file call appSettings.json file to store our connection string to the database that we are going to create through Entity Framework.  Even though Microsoft provides us with the Northwind database, we don't really want to use it because it's outdated.  We are going to modernize the database by rebuilding it from scratch with the code first approach with Entity Framework Core.  If you look at the existing Northwind database you will see that there's a lot of redundant data and tables.  For example there are tables for Customers, Employees, Suppliers and Shippers.  Those are basically roles, and we will take care of those roles later on in the series using the Identity framework.  What we are going to do is start out simple with just the Products, Categories, Orders, OrderDetails table and add on to those tables as we progress in building the application.

Wednesday, August 14, 2019

I believe the last iPhone I owned was an iPhone 3?  I don't remember, but it was a while back.  It was actually a very good phone.  I love Apple products, but the price just seems to increase on each iterations and the features were less and less with each upgrades.  I found myself with a life or death situation.  Should I go to the dark side (Darth Vader breathing) an "Andriod Phone".  Oh my god, stop it I said to myself...lol  But at the time the Android phones were getting good.  So I decided to take the plunge and never looked back.

Anyways back to the present day, I have Apple envy because it has this great ecosystem, that I can't tapped into because I don't have an iPhone.  That is until I got the new iPad, which is the cheaper version of the iPad, but it's not really cheap at all it's the best iPad out there for the price.  I got it so that I can watch movies and read magazines while I was commuting.  What I found surprising was that once again I am tapped into the Apple ecosystem with my iPad.  I can sign up to all the new services that Apple is touting.  I am currently subscribed to News+ because I am a news junkie.  But if you think about it most of the new Apple services are ideal for consumption on a bigger screen.

Since I have unlimited plan on my Android phone, I used it as a hotspot for my iPad.  Put my iPad in a stylish mini bag, and I am good to go.  My iPad became a substitute for an iPhone, for less than 1K that's not bad. I know what you are thinking an Android phone and an iPad working together?  That's like the rebellion working with the empire.  But that's the closest thing to world piece right now and we should take it :)



If you want to contribute to my retirement fund you can buy it here on Amazon, it's actually a really good tablet for the price.  I mean the screen is amazing.  I got the older model and I am still using everyday. iOS is awesome, that's the one thing I like about the empire's product (I mean Apple's product).



Monday, August 5, 2019

Now that we have most of our static contents taken care of for our application, meaning we did everything we could without a database.  It's time to create our database.  But before we can do that we need a place to store our connection string to the database.  Usually we just store the connection string in the web.config file in our web application.  However, since ASP.NET Core is trying to break free from the old way of doing things, there's a new way to store configuration information which is more flexible the old web.config way.  As usual it also requires more work.

Friday, August 2, 2019

In this post we will add Tag Helpers support for our application.  Tag Helpers are programmable attributes that you can use throughout the application.

Follow the steps below to enable tag helpers:

1.  Right-click on the "Views" folder and create a "View Imports" file

Thursday, August 1, 2019

In this tutorial we will add icons to your navbar.  In the previous tutorial we added a responsive layout with bootstrap.  In this post we will add some icons to your navigation.  Font-Awesome gives you professional looking vector graphics, which are implemented using CSS.

Search This Blog