Tech Junkie Blog - Real World Tutorials, Happy Coding!: June 2016

Sunday, June 26, 2016

In the previous blog post we got AngularJS to work with a module and a controller.  However, we put everything in the global scope.  The problem with that is that there are many JavaScript libraries that might be using the same variables as we are, or if we are working with other developers, there might be some unforeseen conflicts.  The way we can mitigate this problem is to wrap our modules and controllers in an anonymous function.  Think of an anonymous function as a wrapper or a container to hold our modules and controllers.  Another term developers like to refer to anonymous function is an IIFE.  Whatever it's called it's always good practice to avoid putting things in the global environment if it can be avoided.

Here are the steps to take the modules and controllers out of the global environment:

1.  First let's wrap the module in an anonymous function.  The source code for the app.js file should look like the following


(function(){
    'use strict';

    var app = angular.module('bankApp',['bankController']);
    
})();


The code above wraps the application in anonymous function and assigned to the variable call "app"

Saturday, June 25, 2016

The previous blog post we setup the AngularJS folder structure and pulled in the necessary dependencies using bower. In this post we are going to add AngularJS to our application. We will app an AngularJS application and controller to our simple banking application.

Here are the steps to setup AngularJS in our application.

1.  Create an app.js file in the app/js folder, app.css in the app/css folder

Bower is a JavaScript tool to get client dependencies in your project using npm packages.

The requirement for bower is that you need to install Node.js first.  You can follow along in the this blog to install node.js, After node.js is installed open the command line and type the following command

npm install -g bower

Sunday, June 19, 2016

"Bootstrap is the most popular HTML, CSS, and JS Framework for developing responsive, mobile first projects on the web."  - getbootstrap.com

Brief Introduction:

Bootstrap is a front-end framework using HTML, CSS and JavaScript to build menus, navigations, layouts, forms, tables, and etc.  What is special about Bootstrap is that mobile-first, and responsive design is it's default behavior.  Okay, hold on, let me put my professor's glasses on!

Okay class here goes:

Mobile-First Design:  You design your site for mobile devices first so the desktop version is second class citizen.

Git is an open sourced version control system, that a lot of open source projects have a repository on.
To install Git on Windows follow the directions in this blog.

1.  Go to http://www.git-scm.com

2.  Click on "Download for Windows" if you are using Windows, or "Downloads" if you are using other OS.  After you click on the button, save the download to a location on your desktop.

Suppose you have an enum type like the one below, and you want to bind the enum type to a DropDownList control in a Web Forms application.  How would you do this?  There's an easy way to do this with just a few lines of code.  You'll be amaze at how simple it is.

First of all here is our markup code in our .aspx page

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="Sandbox.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>


The GridView data grid control is probably the most popular and flexible data grid control in the ASP.NET arsenal.  In this tutorial we will create a new GridView data grid on a web form.

Here are the steps:

1. Click on the "Design" tab in main window of Visual Studio


string dobStr = ddlMonth.SelectedValue + "/" + txtDay.Text + "/" + txtYear.Text;
SqlParameter dob = new SqlParameter("DOB", Convert.ToDateTime(dobStr));
dob.SqlDbType = SqlDbType.Date;
cmd.Parameters.Add(dob);

Next: ASP.NET: Getting The Inserted ID Back With Scope_Identity()


padding: top right bottom left

padding:100px 75px 50px 25px;

Long hand version
padding-top:100px;
padding-right:75px;
padding-bottom:50px;
padding-left:25px;

All four sides 100px
padding:100px;


In this blog we will get the current page file name that the user is currently on.

string[] currentUrl = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
string pageFileName = currentUrl[currentUrl.Length-1];

In this example we will use the SqlDataAdapter to fill a DataTable then bind the data to a GridView

 1. Drag a GridView into your ASP.NET page

2. Use the following code to the fill the dtProducts DataTable with the adapter SqlDataAdapter, then bind it to the GridView1 control.


        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dtProducts = new DataTable();

              string connString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

              using (SqlConnection conn = new SqlConnection(connString))
                {
                    SqlCommand cmd = new SqlCommand("SELECT * FROM Products", conn);
                    conn.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dtProducts);

                    GridView1.DataSource = dtProducts;
                    GridView1.DataBind();

                }
        }


Next: SqlDbType.Date

Namespace:

System.Collections.Generic

Declaration:

Dictionary<string, string> account = new Dictionary<string, string>();

Adding Items:


account.Add("id","1");
account.Add("username", "jackd");

Use in ArrayList: Namespace:

SQL Server as well as other DBMS has an order of evaluation that can throw you off. Especially when you have more than one comparison in the WHERE clause. In this example I will show you the difference between using a parentheses and not using one, and how by using parentheses can give the results that you want.  Suppose you want to get the products with CategoryID 1 and 2 that are priced less than 15 dollars in the Products table in the Northwind database. Here is the query without the parentheses:

SELECT CategoryID,ProductName,UnitPrice
FROM Products
WHERE CategoryID = 1 OR CategoryID =2 AND UnitPrice < 15

When you run the query above you would expect that all the records retrieved will have a unit price of less than $15 dollar but that is not the case. Below is the result from the query.

Retrieve records with NULL value in the ShippedDate column in the Orders table in Northwind

SELECT OrderID, ShippedDate
FROM Orders
WHERE ShippedDate IS NULL

Retrieve records that is does not have NULL value in the ShippedDate column in the Orders table in Northwind

SELECT OrderID, ShippedDate
FROM Orders
WHERE ShippedDate IS NOT NULL


Let's say you want to know the orders that takes place in the Northwind database table Orders tables that occurs during the Christmas Eve 1997-12-24 and the New Years Day the following year in 1998-01-01. Here is the SQL to query the OrderID between those date range:

SELECT OrderID, OrderDate
FROM Orders
WHERE OrderDate BETWEEN '1997-12-24' AND '1998-01-01'

The Categories table is a perfect example of how sometimes you have to populate the DropDownList control to data from the database. In this example we will populate the DropDownList control to the Categories table in the Northwind database.

 1. Drag the DropDownList control into a .aspx page.

In this example we will pass an input parameter to determine the result of the query.  We will pass in supplier id to get all the products that are provided by the supplier.

Here is the code

Use Northwind
GO
CREATE PROCEDURE dbo.selProductsBySupplierID
@SupplierID int
AS
SELECT DISTINCT p.ProductID,
p.ProductName,
p.UnitPrice
FROM Products p
INNER JOIN Suppliers s ON
p.SupplierID = @SupplierID
GO

So you have following connection string to the Northwind database in your Web.config and you want to connect to the database in the code behind instead using query builder.

  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.
SqlClient"/></connectionStrings>

Here is how you would do it

1. Get the connection from the Web.config file programmatically, you can look at this blog to find out how perform this step by step.  But here is the code to get the connection string from the Web.config file

string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

Out of the box the ASP.NET provider databases works with the local database file call aspnetdb.mdf, however in a production environment you cannot use this file because you need to work with the production database. To create the provider databases on a full version of SQL Server perform the following steps.

1. Navigate to the .NET Framework version that you want to use. Version 4.5 and Version 2 has the provider database wizard. I am using version 4.5 so the path is C:\Windows\Microsoft.NET\Framework\v4.0.30319

2. Double click on the file aspnet_regsql.exe, the ASP.NET SQL Server Setup Wizard will apear, click "Next" to continue

So you have to work with multiple connection strings that you want to use in the Web.config file and you want to use it in the code behind file.    Below are the steps to retrieve multiple connection strings in the web.config file programmatically.

1. Make sure you have connection strings in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="AdventureWorksConnectionString" connectionString="Data Source=(local);
Initial Catalog=AdventureWorks;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>


So you have a connection string that you want to use in the Web.config file and you want to use in the code behind file.  You can do that with a single line of code in your .cs file.  Below are the steps to retrieve a connection string in the web.config file programmatically.

1. Make sure you have a connection string in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True" 
providerName="System.Data.SqlClient"/>
  </connectionStrings>


The SqlDataSource control provides you with a quick and easy way to access database data.  Most of the time you don't even have to write a single line of code.  Now this can a be a good thing and a bad thing, depends on how you look at things.  Most of the configuration and querying is performed via a configuration wizard.

Here are the steps to creating a SqlDataSource:

1. In a ASP.NET project/web site drag a SqlDataSource control in under "Data" in the "Toolbox" tab into a .aspx page.

A little bit fancier, you want to specify the language and character set:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        
    </body>
</html>

This is the bare minimum you need to write a HTML5 page:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
</body>
</html>

Previous: HTML5 Tags

Not Supported in HTML5:
  • <tt>
  • <strike>
  • <noframes>
  • <frame>
  • <frameset>
  • <dir>
  • <center>
  • <big>
  • <basefont>
  • <applet>
  • <acronym>

In my previous post we've created the Northwind products page using the SqlDataSource data control, even though there's nothing wrong with the solution.  SqlDataSource is a an old technology and is not meant to be an enterprise solution.  SqlDataSource is the stone age of .NET data access technology.  The future of .NET is the Entity Framework.

The goal of the Entity Framework is to create a conceptual model of your data store so that you can work with tables and rows as objects, or entities.  In essence the developer does not know or care what the data store is, he does not have to be a dba to work with the data.

To demonstrate the Entity Framework let's create the Northwind products page using the Entity Data Model of the Northwind database.

Here are the steps:

1. Open the Northwind project you created with the SqlDataSource

You can use Visual Studio for all of your web server needs for local development, but it's essential that you familiar yourself with a full blown IIS version.  In this tutorial I will show how to install IIS on a Windows 7 machine.

1. Open the "Control Panel"

2. Select "Programs and Features"

I could go on, and on about ASP.NET features and how awesome it is, but most of the time you come to a blog to learn about real world situations.  So why not create a web application base on the Northwind database.

Just from looking at the database tables we know that we could divide the web site into two sections. The e-commerce side of the business and then the internal side of the business. So the e-commerce site deals with the products are being offered by the Northwind corporation, and the internal side of the site deals with the sales team and the employees.

If you look on the web you will eventually find an example that refers to the Northwind sample database in one of the their examples.  What they fell to tell you is where to find this sample database and how to add to your database.

Follow these steps to add the Northwind sample database to your SQL Server:

1. Go the URL http://www.microsoft.com/en-us/download/details.aspx?id=23654 and download the Northwind and pubs sample database from Microsoft.

The purpose of this blog is to show you the bare bones of ASP.NET.  Often times when you search for a tutorial on the web you see that the tutorials are way too complex or an overkill of what you are trying to do at that moment.  So the in this blog series I want to cut through all the fat and just show you how to get things done quickly.

The best way to start an ASP.NET web application is to create an empty project.  In this tutorial I will show you how to create an empty web application project in Visual Studio 2012.

You can download Visual Studio 2012 at http://www.microsoft.com/visualstudio/eng/downloads#d-2012-editions  you can get a 90 trial by registering with microsoft.com.  Another alternative is to download the free Visual Studio Express version at http://www.microsoft.com/visualstudio/eng/downloads#d-2012-express 

On the previous blog we went over how to create a new virtual machine for CentOS in VirtualBox.  In this blog we will go over how to install the CentOS ISO file on the new virtual machine that we've just created. Below are the step by step instructions of how to install CentOS on VirtualBox.

Step-By-Step Instructions:

1. Launch VirtualBox, right-click then select "Settings"

In previous blog we've installed the CentOS operating system on VirtualBox however, when we reboot, it takes us to a text prompt.  In this blog we will be installing a graphical desktop environment to our operating system using "yum".  Follow the steps below to get the Gnome desktop in your CentOS.

1.  Make sure you have internet connection
2.  Click "Start" on your "CentOS" VM

Saturday, June 18, 2016

A lot of people think that you can only create one kind of ASP.NET MVC  project, the one with the sample application.  But the reality is that you can create an Empty ASP.NET MVC, you just need to do more work.  However, it is cleaner and you can add what you need, instead of having everything in place already like the default template.  So you might run into more errors with the empty project, but I think you will learn more about MVC than if you just have the default template.  Plus it's more streamline.  I always start with an empty project on my MVC projects.  In order to follow this tutorial you must have Visual Studio 2017 installed.

In this blog we will add the KnockoutJs JavaScript library to our MvcApp project.  KnockoutJs is a great lightweight data binding library.  Follow the steps below to add KnockoutJs to your ASP.NET MVC project.

Step-By-Step Instructions:

1.  Right-click on the project's "References" node, then select "Manage NuGet Packages"

In our previous blogs we've created an ASP.NET MVC from scratch.  In this blog we are going to use Entity Framework as the ORM (Object Relational Mapping) as a conduit to our database, so that we can query our data as an object.  An ORM as the name implies maps database tables, views, and stored procedures as objects in a programming language so that developers can work with the data as objects.

Step-by-Step Instructions:

1.  First we need to add the Entity Framework 6.1.3 to our ASP.NET MVC, we accomplish by right-click on "References" then select "Manage NuGet Packages"

In our previous blog we've added a _ViewStart.cshtml layout to our project, which is the default layout for our pages if no layout is specified for the page.  In this blog we will add BundleConfig for the JavaScript libraries which includes JQuery, and Bootstrap that we've added to our NorthwindCafe project in the previous blogs.  A configuration bundle allows you to group files that belongs in the same libraries together so that they can called with just one line of code.  In this blog we will be creating configuration bundles for JQuery, and Bootstrap to the NorthwindCafe project.

Step-By-Step Instructions:

1.  Right-click on the folder "App_Start", then select Add → New Item → Visual C# → Class, name the class BundleConfig.cs

In the previous blog we've created an empty ASP.NET MVC  project.  It's a great starting point but, it's missing a lot things that we will need later.  In this blog we will add JQuery to the empty ASP.NET MVC  project that we've just created.

Step-By-Step Instructions:

1. Open the empty ASP.NET MVC project that you've just created

2.  Right click on the the "References" node in the "Solution Explorer", then select "Manage NuGet Packages"

In ASP.NET MVC there is a default layout file that the application use when one exists.  If you look at the markup at the top of the "Index.cshtml" file you will see that there is a markup to specify the layout of the page in the code below.

@{
    Layout = null;
}

The code above tells ASP.NET MVC to not assign any layout to the page because it is being set to null. In this blog we will build on our existing NorthwindCafe project and add a default layout view to the project so that each page in the project will have a common layout.  This is similar what you would a master page for in web forms.

In the previous blog we've added the Bootstrap library to our empty ASP.NET MVC project.  Now let's add another commonly used JQuery library to our project.  In this blog we will add the JQuery UI library to our empty project.

Step-By-Step Instructions:

1. Open the empty ASP.NET MVC project that you've just created

2.  Right click on the the "References" node in the "Solution Explorer", then select "Manage NuGet Packages"

In the previous blog we've created added the JQuery library to an empty ASP.NET MVC project. In this blog we will add the Bootstrap to the empty ASP.NET MVC project that we've just created.

Step by Step Instructions:

1. Open the empty ASP.NET MVC project that you've just created

2.  Right click on the the "References" node in the "Solution Explorer", then select "Manage NuGet Packages"

A lot of developers assumed that they can only configure the BundleConfig class to use only local resources in their MVC project.  That is not the case, in fact it is quite easy to use a cdn version of your JavaScript libraries instead of the one in your local folder.  In the previous blog we went over how to create the BundleConfig class from scratch.  In this blog we will go over how to configure MVC to use the cdn resource instead of your local resource files.

Step-By-Step Instructions:

1.  Open the NorthwindCafe project
2.  Open the BundleConfig.cs file under the folder App_Start

Search This Blog