4.12.2017

AngularJS CRUD, Entity FrameWork & Web API Step-By-Step Part One

Introduction

I am a full-stack web programmer for the State Department. We work with AngularJS 1.2 mixed with WEB API, WCF and SQL Server - our own hybrid architecture.

It is how I learned this tech. But I wanted to create other Angular based projects, some to help my friends with their hobbies (feral Cats), others to simply solidify my AngularJS understanding - just before I take the leap into AngularJS 2.0…

So I created lots of CRUD apps, and I like the John Papa project structure - so this post is about building an AngularJS CRUD project using the MVC and WEBAPI template, and Entity Framework

Project Requirements

The project will be based on this table at the website wikipedia. This is a table that lists countries by population and captures the change by year in population.

Scope of Step #1

This step simply gets the database up and running.

Data Model

In this project example, I am going to use the Entity Framework Database First - using Microsoft SQL Server.

Scripts

The database scripts are as follows:

CREATE TABLE COUNTRY(
    COUNTRYID int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    COUNTRY varchar(100) NULL,
    CONTINENTIAL_REGIONID int NULL,
    STATISTICAL_REGIONID int NULL
) 
GO

CREATE TABLE UN_CONTINENTAL_REGION(
    CONTINENTIAL_REGIONID int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED ,
    CONTINENTIAL_REGION varchar(250) NULL
) 

GO

CREATE TABLE UN_STATISTICAL_REGION(
    STATISTICAL_REGIONID int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    STATISTICAL_REGION varchar(250) NULL
    )

CREATE TABLE dbo.[POPULATION](
    POPULATIONID int IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED ,
    COUNTRYID int NULL,
    YEARID int NULL,
    POPULATION int NULL
    )
GO

CREATE TABLE YEAR_DOMAIN(
    YEARID int NOT NULL PRIMARY KEY CLUSTERED
    )
GO

ALTER TABLE COUNTRY  WITH CHECK ADD  CONSTRAINT FK_COUNTRY_UN_CONTINENTAL_REGION 
FOREIGN KEY(CONTINENTIAL_REGIONID) REFERENCES 

UN_CONTINENTAL_REGION (CONTINENTIAL_REGIONID)
GO

ALTER TABLE COUNTRY CHECK CONSTRAINT FK_COUNTRY_UN_CONTINENTAL_REGION
GO

ALTER TABLE COUNTRY  WITH CHECK ADD  CONSTRAINT FK_COUNTRY_UN_STATISTICAL_REGION 
FOREIGN KEY(STATISTICAL_REGIONID) REFERENCES 
UN_STATISTICAL_REGION (STATISTICAL_REGIONID)
GO

ALTER TABLE COUNTRY CHECK CONSTRAINT FK_COUNTRY_UN_STATISTICAL_REGION
GO

ALTER TABLE POPULATION  WITH CHECK ADD  CONSTRAINT FK_POPULATION_COUNTRY 
FOREIGN KEY(COUNTRYID) 
REFERENCES COUNTRY (COUNTRYID)
GO

ALTER TABLE POPULATION CHECK CONSTRAINT FK_POPULATION_COUNTRY
GO

ALTER TABLE POPULATION  WITH CHECK ADD  CONSTRAINT FK_POPULATION_YEAR_DOMAIN 
FOREIGN KEY(YEARID) REFERENCES YEAR_DOMAIN (YEARID)
GO

ALTER TABLE POPULATION CHECK CONSTRAINT FK_POPULATION_YEAR_DOMAIN
GO

These scripts will create five tables. COUNTRY, UN_CONTINENTAL_REGION,POPULATION,YEAR_DOMAIN and UN_STATISTICAL_REGION.

Probably overkill, but this is for illustration of multiple technologies in a very simple application.

Need some data scripts to populate the database:

INSERT INTO YEAR_DOMAIN
(YEARID) VALUES(2015);

INSERT INTO YEAR_DOMAIN
(YEARID) VALUES(2016);

INSERT INTO YEAR_DOMAIN
(YEARID) VALUES(2017);

INSERT INTO UN_CONTINENTAL_REGION
(CONTINENTIAL_REGION) VALUES('ASIA');

INSERT INTO UN_CONTINENTAL_REGION
(CONTINENTIAL_REGION) VALUES('AMERICAS');

INSERT INTO UN_CONTINENTAL_REGION
(CONTINENTIAL_REGION) VALUES('AFRICA');

INSERT INTO UN_CONTINENTAL_REGION
(CONTINENTIAL_REGION) VALUES('EUROPE');

INSERT INTO UN_CONTINENTAL_REGION
(CONTINENTIAL_REGION) VALUES('OCEANIA');

INSERT INTO UN_STATISTICAL_REGION
(STATISTICAL_REGION) VALUES('Eastern Asia')

INSERT INTO UN_STATISTICAL_REGION
(STATISTICAL_REGION) VALUES('Southern Asia')

INSERT INTO UN_STATISTICAL_REGION
(STATISTICAL_REGION) VALUES('Northern America')

INSERT INTO UN_STATISTICAL_REGION
(STATISTICAL_REGION) VALUES('South-Eastern Asia')

INSERT INTO UN_STATISTICAL_REGION
(STATISTICAL_REGION) VALUES('South America')

INSERT INTO UN_STATISTICAL_REGION
(STATISTICAL_REGION) VALUES('Australia and New Zealand')

DECLARE @CNREGID INT, @STATREGID INT
SELECT @CNREGID=CONTINENTIAL_REGIONID FROM 
    UN_CONTINENTAL_REGION WHERE CONTINENTIAL_REGION='ASIA'
SELECT @STATREGID=STATISTICAL_REGIONID FROM 
    UN_STATISTICAL_REGION WHERE STATISTICAL_REGION='Eastern Asia'

INSERT INTO COUNTRY
(COUNTRY, CONTINENTIAL_REGIONID,STATISTICAL_REGIONID)
VALUES('CHINA',@CNREGID,@STATREGID)

SELECT @STATREGID=STATISTICAL_REGIONID FROM 
    UN_STATISTICAL_REGION WHERE STATISTICAL_REGION='Southern Asia'

INSERT INTO COUNTRY
(COUNTRY, CONTINENTIAL_REGIONID,STATISTICAL_REGIONID)
VALUES('INDIA',@CNREGID,@STATREGID)

SELECT @STATREGID=STATISTICAL_REGIONID FROM 
    UN_STATISTICAL_REGION WHERE STATISTICAL_REGION='South-Eastern Asia'

INSERT INTO COUNTRY
(COUNTRY, CONTINENTIAL_REGIONID,STATISTICAL_REGIONID)
VALUES('INDONESIA',@CNREGID,@STATREGID)

SELECT @CNREGID=CONTINENTIAL_REGIONID FROM 
    UN_CONTINENTAL_REGION WHERE CONTINENTIAL_REGION='AMERICAS'
SELECT @STATREGID=STATISTICAL_REGIONID FROM 
    UN_STATISTICAL_REGION WHERE STATISTICAL_REGION='Northern America'

INSERT INTO COUNTRY
(COUNTRY, CONTINENTIAL_REGIONID,STATISTICAL_REGIONID)
VALUES('UNITED STATES',@CNREGID,@STATREGID)

SELECT @STATREGID=STATISTICAL_REGIONID FROM 
    UN_STATISTICAL_REGION WHERE STATISTICAL_REGION='South America'

INSERT INTO COUNTRY
(COUNTRY, CONTINENTIAL_REGIONID,STATISTICAL_REGIONID)
VALUES('BRAZIL',@CNREGID,@STATREGID)


SELECT @CNREGID=CONTINENTIAL_REGIONID FROM 
    UN_CONTINENTAL_REGION WHERE CONTINENTIAL_REGION='OCEANIA'
SELECT @STATREGID=STATISTICAL_REGIONID FROM 
    UN_STATISTICAL_REGION WHERE STATISTICAL_REGION='Australia and New Zealand'

INSERT INTO COUNTRY
(COUNTRY, CONTINENTIAL_REGIONID,STATISTICAL_REGIONID)
VALUES('AUSTRALIA',@CNREGID,@STATREGID)

DECLARE @COUNTRYID INT;
SELECT @COUNTRYID=COUNTRYID FROM COUNTRY WHERE COUNTRY='CHINA'
INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2015,1376048943)

INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2016,1382323332)

SELECT @COUNTRYID=COUNTRYID FROM COUNTRY WHERE COUNTRY='INDIA'
INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2015,1311050527)

INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2016,1326801576)

SELECT @COUNTRYID=COUNTRYID FROM COUNTRY WHERE COUNTRY='UNITED STATES'
INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2015,321773631)

INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2016,324118787)


SELECT @COUNTRYID=COUNTRYID FROM COUNTRY WHERE COUNTRY='INDONESIA'
INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2015,257563815)

INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2016,260581100)

SELECT @COUNTRYID=COUNTRYID FROM COUNTRY WHERE COUNTRY='BRAZIL'
INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2015,207847528)

INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2016,209567920)

SELECT @COUNTRYID=COUNTRYID FROM COUNTRY WHERE COUNTRY='AUSTRALIA'
INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2015,23968973)

INSERT INTO dbo.[POPULATION] (COUNTRYID,YEARID,POPULATION)
VALUES(@COUNTRYID,2016,24309330)

Scope of Step #2

This step is to get the Visual Studio Solution created.

Visual Studio

One of my colleagues loves to do his web development in JetBrains WebStorm - he swears by it, but I am a life long Visual Studio junkie. As of this writing, I am coding this post using Visual Studio 2017 Community Edition - a first for me, I usually use Professional or Enterprise, but heck, the Community version is so well loaded I love it.

Creating The Project

Open Visual Studio.

  1. Create New Project.
  2. When the dialog appears, select Web from the Installed Templates treeview. The middle list will populate, with varying options. Please select ASP.NET Web Application (.NET Framework)
  3. Select a Name, I am picking WorldPopulation along with a location to place the solution.

  4. When the next dialog pops up, among the templates - select Empty BUT look at the checkboxes below. We need to add in some CORE References. Make sure to check MVC and Web API.

  5. Do not select Add Unit Tests - we will do that but will not use the VisualStudio.TestTools.UnitTesting - rather we will use NUnit.

So, what are those other templates? Lots of tutorials simply skip explaining that. I will take a shot at explaining so you can have an understanding of what you are NOT doing at this point in time.

Note: Also see ASP.NET Web Application Projects and Web Application Projects versus Web Site Projects in Visual Studio.

The Empty template is simply what the name says, a empty web project, bare bones. This template creates an ASP.NET web application that includes a Web.config file, but no other files. Use this project template when you do not require the functionality built into the standard template.

The Web Forms template is server based web applications. All the code resides in the IIS server and gets rendered to the client. It is older technology and not used much for modern development.

According to Microsoft, it is:
Use this project template to create a web application that is based on ASP.NET Web Forms pages and that includes the following functionality. You can choose not to use any of these features when they are not required for your application.
  • A master page.
  • A cascading style sheet.
  • Login security that uses the ASP.NET membership system.
  • Ajax scripting that uses jQuery.
  • Navigation that uses a menu control.
By default, the ASP.NET Web Application project template includes the following:
  • Folders to contain membership pages, client script files, and cascading style sheet files.
  • A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time.
  • A master page (the Site.master file).
  • Web pages named Default.aspx, Contact.aspx, and About.aspx. These content pages are based on the default master.
  • A global application class (Global.asax file).
  • A Web.config file.
  • A Packages.config file.
  • For more information, see ASP.NET Web Application Projects and Web Application Projects versus Web Site Projects in Visual Studio.

The MVC template, that is Microsoft’ Model-View-Controller template. There are many incarnations of this approach, MVVM, etc., but basically the View (what you see in the web browser) is separate from the Controller (logic) and the Model (data). That is a simplistic explanation.

Use this project template to create web applications that use a model-view-controller pattern, using the ASP.NET MVC 3 release. The MVC pattern helps separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. In addition, this project template promotes test-driven development (TDD).

The Web API is what my friend Van told me once is “Microsoft’ replacement for WCF”. It is much easier to implement, lightweight, flexible. More on this later.

The Single Page Application is a design where there is a single web page that the user sees but portions of the page can load as needed.

When selecting those templates the Solution takes on a predefined structure and loads a lot of predefined files to get the developer up and running quickly. If CORE References is selected for MVC then components needed to do MVC applications are added but the structure of the solution is not populated with a lot of predefined components which a developer doesn’t necessarily need.

WorldPopulation Project

Now that the WorldPopulation (or whatever you called your own implementation of the solution) has been created, it should have one project with the same name.

That project should have 5 Folders:

  1. App_Data
  2. App_Start
  3. Controllers
  4. Models
  5. Views

The App_Start folder will have two files in it

  1. RouteConfig.cs
  2. WebApiConfig.cs

These are critical to how our application will work. More on that later.

Now we need to add two more projects to the solution.

  1. WorldPopulation.EF (for Entity Framework, or maybe Datalayer)
  2. WorldPopulation.UnitTests

Adding Projects


Add Unit Test Project

  1. In the Solution Explorer scroll to the top, select Solution WorldPopulation.
  2. Right-click the WorldPopulation solution.
  3. When the context-menu pops up, select Add.
  4. When the second context-menu expands, select New Project.
  5. In the template selector, change to Visual C#.
  6. In the middle listing of templates - select Class Library (.NET Framework)
  7. In the Name enter WorldPopulation.EF
  8. Press OK

Add Unit Test Project

  1. In the Solution Explorer scroll to the top, select Solution WorldPopulation.
  2. Right-click the WorldPopulation solution.
  3. When the context-menu pops up, select Add.
  4. When the second context-menu expands, select New Project.
  5. In the template selector, change to Visual C#.
  6. In the middle listing of templates - select Class Library (.NET Framework)
  7. In the Name enter WorldPopulation.UnitTests
  8. Press OK

NuGet Packages

For this example, I am going to use NuGet. I know that Bower and NPM has more recent updates, but for some of the non-web portions NuGet is awesome (plus I like it).

  1. In the Solution Explorer scroll to the top, select Solution WorldPopulation.
  2. Right-click the WorldPopulation solution.
  3. When the context-menu pops up, select Manage NuGet Packages for Solution.
  4. Click Browse at the top.
NuGet Package WorldPop WorldPop.EF WorldPop.UnitTests
Entity Framework X X X
NLog X X X
NLog.Config X X X
NUnit X
NUnit3TestAdapter X
AngularJS.Core X
AngularJS.Route X
bootstrap X
FontAwesome X
lodash X
jQuery X
toastr X

jQuery may already installed by other packages like Bootstrap or by the MVC references. Select jQuery in the NuGet package manager and choose the highest available version, then select update if the installed version is below thehighest available one.

When the NuGet package installation step is completed, you will see several additional folders in the WorldPopulation Project:

  1. Content
  2. Fonts
  3. Scripts

Content Folder

This folder mainly contains CSS related files, style sheets.

Fonts

The name is self-descriptive. The customized fonts provided by the Font Awesome libraries are stored within this folder.

Scripts

JavaScript files, AngularJS, Moment.JS, jQuery, etc., all are stored in this folder.

The other NuGet packages such as NLog or Entity Framework are added to the project references.

Scope of Step #3

In this step, we will create the Data Context by connecting to the database and retrieving the model into Visual Studio.

Project WorldPopulation.EF

  1. Select the WorldPopulation.EF Project.
  2. Right click the project and click Add on the popup context menu.
  3. Select New Folder, and enter Interfaces.
  4. Repeat steps 1-3, only enter Models instead of Interfaces for the new folder name this time.
  5. Select the Models folder you just created.
  6. Right-click and select Add from the first context menu, then New Item from the second.
  7. Select Data from the templates category on the left, then when it is filtered select ADO.NET Entity Data Model.
  8. For the name enter WPModel. Then click *Add.
  9. When the next dialog opens, select EF Designer from database.
  10. Click Next.
  11. In the Choose Your Data Connection dialog, enter the SQL Server connection information where you created the tables in Step #1.
  12. Let the settings be the default for the App.Config in my case, my SQL Server database was named DEV so the name of the connection string in App.Config is DEVEntities.
  13. In the next dialog, Choose Your Database Objects and Settings -we are only selecting the tables. Expand the tables, schema. Select:
TABLE NAME
COUNTRY
POPULATION
UN_CONTINENTAL_REGION
UN_STATISTICAL_REGION
YEAR_DOMAIN


Additional Options Yes/No
Pluralize or Singularize Generated Object Names Yes
Include Foreign Key Columns in the Model Yes
Import selected Stored Procedures and functions into the entity model No

MODEL NAMESPACE DEVModel

Remember DEV is my database name, so whatever you choose will be here

  1. Click Finish

Visual Studio will chug along as it reads the database, getting the model and generates the classes.

When it is done, you will see a visual representation of the SQL Server tables and their relationships in an EDMX file within the Models folder (remember how I had you select it before you started adding the ADO.NET Entity Data Model).

Under the file WPModel.tt you will see the class files for each table in the database.

Under the file WPModel.Context.tt is the WPModel.Context.cs this is the datacontext. I am not going to spend a lot of time explaining this, but you need to read more on this from the MSDN or EntityFramework Tutorial


Scope of Step #4

We need to create our Repository, a tiny one.
We will be working in the WorldPopulation.EF Project. We will be implementing the Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10) which basically is

“The repository pattern is an abstraction. It’s purpose is to reduce complexity and make the rest of the code persistent ignorant. As a bonus it allows you to write unit tests instead of integration tests.”

Repository Pattern Resources

Steps to Pattern Implementation

  1. Select WorldPopulation.EF Project.
  2. Select the Interfaces Folder.
  3. Right click the context menu, click Add select Class.
  4. Enter IRepository.cs. Click OK.
  5. Open the file IRepository.cs. Modify class IRepository to public interface IRepository.
  6. The interface should be similar to the following:

    
    using WorldPopulation.EF.Models; 
    using System.Collections.Generic;
    namespace WorldPopulation.EF.Interfaces
    {
    public interface IRepository
    {
    List GetCountries();
    COUNTRY GetCountry(int countryID);
    }
    }

  1. Select the Models Folder.
  2. Right click the context menu, click Add select Class.
  3. Enter Repository.cs. Click OK.
  4. We are creating the Repository Pattern and implementing the Interface above in the folder Models in the file named Repository.cs.
  5. Be sure to add the following namespace reference at the beginning of the file:
  6. WorldPopulation.EF.Interfaces;
  7. Type the following code into the file Repository.cs :

using WorldPopulation.EF.Interfaces;
using System.Collections.Generic;
namespace WorldPopulation.EF.Models
{
     public class Repository : IRepository
     {
          private DEVEntities dbConn;
          public Repository()
          {
               dbConn=new DEVEntities();
          }

          public List<COUNTRY> GetCountries()
          {
               throw new NotImplementedException();
          }

          public COUNTRY GetCountry(int countryID)
          {
               throw new NotImplementedException();
          } 
     } 
}

Scope of Step #5

Now we get into the grit.

I still consider myself new to [TDD]TDD (Test-Driven Development).

Update Unit Test

  1. Add reference to WorldPopulation.EF project.
  2. Select WorldPopulation.UnitTests. Rename the file Class1.cs to DatalayerUnitTests.cs.
  3. Open the file DatalayerUnitTests.cs
  4. Add using NUnit.Framework; to class.
  5. Above the class name public class DatalayerUnitTests add the attribute [TestFixture].
  6. Create private member private IRepository repo; You will need to add a reference to the namespace using WorldPopulation.EF.Interfaces;.
  7. Create a new void method named Setup() with the attribute [Setup].
  8. Add a method named public void Setup() just below the [Setup] attribute. In this method add the following line:
    repo=new Repository(); You will need to import using WorldPopulation.EF.Models; namespace.
  9. Now create our first failing unit test.
        [Test]
        public void GetCountries_ExpectNone()
        {
            repo.GetCountries();
            Assert.That(repo!=null);
        }

NOTE This unit test as written will fail. When you open the repo.GetCountries() implementation, the code is

        public List<COUNTRY> GetCountries()
        {
            throw new NotImplementedException();
        }

Technically, we should be using a MOCK Interface for this but I am short on time so I am going to violate TDD and have the Unit Test become a Integration Test by accessing the data.

Modify the implementation as follows:

        public List<COUNTRY> GetCountries()
        {
            return dbConn.COUNTRies.ToList();
        }

Scope of Step #6

Switch to the WorldPopulation Project.

  1. Select Controllers folder.
  2. Select Add from the context-menu.
  3. Select Controller… from the second context-menu.
  4. Select Web API 2 Controller - Empty* then press Add.
  5. When the next dialog appears type WorldPopulation and the new controller name should be WorldPopulationController.
  6. Press the Add button.
  7. You should see a new file added into the folder Controllers with the name WorldPopulationController.cs.
  8. When the file opens, expand the curly braces.
  9. Create a Controller Constructor to instantiate the IRepository interface. You may need to add a reference to the WorldPopulation.EF project
        private IRepository repo;

        public WorldPopulationController()
        {
            repo=new Repository();
        }
  1. Now to create a method that will be used by the presentation layer (WEB SITE).
  2. Below the constructor, type the following attribute (type a few spaces first) [HttpGet]
  3. Below that attribute type [ActionName("GetCountries")]
  4. Now type below that attribute, type in:
        public IEnumerable<COUNTRY> GetCountries()
        {
           return repo.GetCountries();
        }

The entire function should look like:

        [HttpGet]
        [ActionName("GetCountries")]
        public IEnumerable<COUNTRY> GetCountries()
        {
           return repo.GetCountries();
        }

Scope of Step #7

Step #7 will begin to add some basic navigation components to the main web project. A HomeController a basic layout page and the default index.cshtml page.

Starting with the HomeController

Controller classes in AMVC are used to prepare the Model that will be mapped to a view for a particular resource. In this example, AMVC created the following Home Controller that will be used to return the default view for our application.

  1. Select Controllers folder.
  2. Select Add from the context-menu.
  3. Select Controller… from the second context-menu.
  4. Select MVC 5 Controller - Empty then press Add*.
  5. When the next dialog appears type Home and the new controller name should be HomeController.
  6. Press the Add button.
  7. You should see a new file added into the folder Controllers with the name HomeController.cs.
  8. Open the *HomeController.

You should see the following:

        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
Now we are going to add some view to the project.
  1. Select the Views folder. Right-Click and choose the Add from the context-menu.
  2. Select MVC 5 Layout Page (Razor). In the popup, select _LayoutPage as the file name.
  3. Paste the following code into the new _LayoutPage.cshtml file:
 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("World Population", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav"></ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - WorldPopulation</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>

7.30.2011

Setting up OS/X Path for Android Development and Logging

Let's assume the default shell is in use on Darwin, bash, and you have installed the Android SDK for OS/X, installed Eclipse and the ADT. Now the you need that nice set of tools in the Android SDK/platform-tools directory, it's a lot easier if you add them to your profile. I found this a nice easy way to do it, if you have the profile it will append if not it will create it: 1.) Open TextEdit

2.) If the Users/
/(YOUR_FOLDER)/.bash_profile - exists, then open this file. 3.) Assuming no previous path information exists, then type the following:
PATH=/Users/(SUBSTITUTE_YOUR_PATH)/android-sdk-mac_x86/platform-tools:$PATH
4.) Save the file as /Users/(YOUR_FOLDER)/.bash_profile - if this does not exist, or open the .bash_profile in step #1 if the file exists.

SETTING UP LOGCAT
This can be easily be done in Eclipse as another view, but I like having it running in a background Terminal on my Apple.

1.) Open a Terminal window.
2.) Type: adb logcat

You will get a window output similar to below (depending on your emulators, and what debuggers you have setup)

 



The line in the logcat output:
D/Suduku  (  538): Debug Msg: Exit Clicked

Is coming from the emulator running, and the code I added to my Android application for this debugging information is as follows:

    private static final String TAG="";
    private void msg(String s)
    {
        Log.d(TAG,"Debug Msg: " + s);   
    }

When the user presses the "Exit" - in the onClick() method I have added the call to the method msg() as follows:

            case R.id.exit_button:
                msg("Exit Clicked");
                finish();
                break;

This sends the string "Exit Clicked" to the method msg(), which then sends the string to the debugging variable TAG - captured in the logcat output.

7.22.2011

Setting up Kinect Sensor on the PC

Microsoft Research has released the Kinect for Windows SDK BETA (32/64 bit versions).  Connecting the Kinect sensor to the PC is quite easy, but there are some things to consider.  The Xbox360 game console that has the Kinect sensor, the connector is not USB compatible. 

power-supply-adapter-cable-for-xbox-360-kinect-sensor-us_3

You must purchase an external power supply for the Kinect sensor (I had to call Microsoft Xbox Technical Support to verify this, because the information on the web was inconsistent).

On the channel9 video, that shows you how to setup the Kinect sensor – it refers to the Microsoft Store and a device that does not exist (USB Cable), but the picture shown is the Kinect Sensor Power Supply, which has a female connector for the Kinect jack and a USB output connector.

KinectSensorPS

The price for the Kinect Sensor Power Supply at the Microsoft Store is 34.95, but I purchased mine from Amazon for 11.64, with next day Prime Shipping (3.99).  Neither product description is very helpful, and the one from Amazon only had a 3-star rating based on one review by a person who was trying to use it for a totally different purpose than the Kinect Sensor.

My workstation with the Kinect operating:

Kinect_Workspace

7.21.2011

Windows Mobile: Changing Input Type Automatically

When developing an application, minimization of user input on the phone is critical.  If you develop an application that requires digital input (such as a calculator program) but the initial keyboard state is alphabetic, the user has to select the “123” key.

To automatically change the state for a specific textbox field use InputScope.

 

<TextBox Height="72" HorizontalAlignment="Left" Margin="136,32,0,0" Name="txtPrice" Text="0" VerticalAlignment="Top" Width="260" >
<TextBox.InputScope>
<InputScope>
<InputScopeName NameValue="Digits"/>
</InputScope>
</TextBox.InputScope>
</TextBox>





sample_dam_calc




 



REF: Windows Phone 7 Jump Start (Session 3 of 19): Building a Silverlight Application, Part 2

11.04.2009

Microsoft Certification...SIGH


I Loathe Tests! All my life I have had serious test anxiety. No matter how hard I would prepare and know the subject matter inside out, when it came to the test - poof - I would forget everything!

It's quite frustrating - I mean it impacts everything in this world, tests are the metric of how good we are at something. I don't necessarily agree with that, I mean some people are excellent on tests but their performance in the real world is horrible, and other's like me are horrible on tests but we can do quite well in the real world.

But, now testing is everywhere in job interviews - instead of checking references they want to see how you perform on a test.
Microsoft, Oracle, Sun all these corporations are making boatloads of money selling CERTIFICATIONS which mean no more than the paper they are written on.
But, it's the pony we have to dance to, so now I must do so - since DIMHRS is ending.

I did make a seriously flawed tactical mistake on deciding to live in Virginia. Yes, there are a lot of positions in my industry - I didnt realize how many required TS/SCI (secret agent code speak for CLEARANCE). The catch 22 of this situation is they want you to have one "TS/SCI REQUIRED' not like they are willing to sponsor for the process - DUH!!

That's why people covet these items as tickets to job security. No company wants to let go of an employee with a TS or SCI.

But, I diverge.

This is a posting on Microsoft Certifications - something I have put off for YEARS!
Microsoft has offered this to me so many times, even free when I was at some of their Windows Conferences. But, I was so secure, I didn't have a crystal ball to see the need for it (just like I ignored Sun Microsystems when they came to our corporate offices to talk about some new language called Java!).

Now - I think I better have that certification in my back pocket. I am not really sure it helps - but who can say!
So I looked over the Microsoft Learning Website, because I knew I wanted MCSD (Microsoft Certified Solution Developer).

MCSD no longer exists. It has been replaced by MCPD - or Microsoft Certified Professional Developer.
Ok, no problem. There is a core test that I have to take no matter what track I was following, EXAM 70-536. This is quite a comprehensive exam, and while I know a lot on it - I think I will need to review for some of it.

I mean the software I developed for DIMHRS was .NET 1.1 and 2.0, and this exam does include VS2008 (.NET 3.5).

Here is a sample of what the test covers:

  • Developing applications that use system types and collections
  • Implementing service processes, threading, and application domains in a .NET Framework application
  • Embedding configuration, diagnostic, management, and installation features into a .NET Framework application
  • Implementing serialization and input/output functionality in a .NET Framework application
  • Improving the security of .NET Framework applications by using the .NET Framework security features
  • Implementing interoperability, reflection, and mailing functionality in a .NET Framework application
  • Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application


At least Microsoft does post material to help prepare for the test. While classroom is offerred (that is their money maker, along with books) I prefer online training - and it is available:


  1. 5161AE: Advanced development with the Microsoft .NET Framework 2.0 Foundation (16 Hours)
  2. 5160AE: Core development with the Microsoft .NET Framework 2.0 Foundation (14 Hours)

Microsoft also makes the following available to help ensure success:

Practice Tests
Microsoft Online Resources
  • Learning Plan: Get started with a step-by-step study guide that is based on recommended resources for this exam.
  • Product information: Visit the Microsoft Visual Studio site for detailed product information.
  • Microsoft Learning Community: Join newsgroups and visit community forums to connect with peers for suggestions on training resources and advice on your certification path and studies.
  • TechNet: Designed for IT professionals, this site includes how-to instructions, best practices, downloads, technical resources, newsgroups, and chats.
  • MSDN: Designed for developers, the Microsoft Developer Network (MSDN) features code samples, technical articles, downloads, newsgroups, and chats



Apple Develpment Tools


Well, I know this blog is for Microsoft .NET technologies - but since I purchased a NEW Apple for the SOLE PURPOSE to try and supplement income by writing iPhone/iTouch applications - I will have to expand this blog's scope. It has been several years since I had touched Objective C. It has not changed too much, but there are some great resources online, and I bought a book written by Stephen Kochan called Programming in Objective C 2.0. The same book is available from Apple in PDF format - Objective C Programming Language. This is an excellent book, and with my C background its a breeze to pickup the language. So, this posting is about the plethora of development tools on the Apple Platform for n00bs (a MMORPG term).

  1. INSTALLATION
  2. How Do I Install Apple Developer Tools on My MACDave Taylor has a nice posting about how to install the development tools that come on the Apple Discs. This is for the truly n00bish! I mean, the disc is labeled, and any developer knows what they need - but I put it here for those that may need it (10 years from now when my mind is further gone I will come back to this posting, if I recall the URL!!)

  3. SOFTWARE
  4. MAC DEVELOPER PROGRAM
    Cant get the tools needed until you join this. I have had an ADC Membership for years, the free one - but now I have to upgrade to one of the packages that costs. At least it doesnt cost as much as the Microsoft MSDN Premiere subscription!!!

  5. XCode Development Tools
  6. To do programming on the MAC platform, all you really need is XCode.

  7. iPhone Development

  8. BLOGS

  9. Books
  10. Beginning iPhone 3 Development: Exploring the iPhone SDK by Jeff LaMarche

9.11.2008

SINGULARITY

Singularity is a new OS from Microsoft Research written in Sing# (an extension of the C# Spec., almost all of the Singularity kernel is written in Sing# - (Bartok Compiler, with a small portion (around 5%) written in assembly and C++). Don't expect it to become a product from Microsoft, but I wouldn't be surprised to see this technology in some form showing up in future variations of their OS Products (such as MIDORI, or MinWin). It has many aspects that make it a very interesting Operating System.

 

image

  • A type-safe operating system, so no more blue screens.
  • No Shared Memory. They have implemented an approach called SIP, or Software Isolated Processes.
  • No dynamic code loading. OH MY - no more DLL's what will we do!!!!! Singularity does not use a CLR it has a highly optimized Bartok Compiler for the Sing# language bypassing MSIL and going straight to native machine code since there is no non-compiled, dynamically loaded code in the operating system.
  • Yes, written in C#, but since it is Microkernel based - a stripped down version - with many namespaces removed. SUCH as System.Windows.Forms (YES, it looks like DOS)
  • OS is based on a Micro-Kernel, and according to Galen Hall - they got around the issues of microkernel(see below) architecture because of type-safe foundation.

    Introduction
    Fifteen years ago, in 1992, two heavyweights in the field of operating system design were entangled in what would become a classic discussion on the fundamentals of kernel architecture (Abrahamsen (no date)). The heavyweights in question were Andrew S. Tanenbaum, the author of “Operating systems design and implementation” (Tanenbaum & Woodhull, 2006) and Linus Torvalds, the then-young and upcoming writer of what would become one of the most successful operating system kernels in computer history: the Linux kernel. Like most of his colleagues at that time, Tanenbaum was a proponent of the microkernel architecture, while Torvalds, more of a pragmatist than Tanenbaum, argued that the monolithic design made more sense. The discussion gained an extra dimension because of the fact that Torvalds had studied Tanenbaum’s book in great detail before he started writing the first version of the Linux kernel.
    In May 2006, Tanenbaum accidentally reignited the debate by publishing an article titled “Can we make operating systems reliable and secure?” (Tanenbaum et al., 2006). In this article, Tanenbaum, who had just released the third major revision of his microkernel-based operating system MINIX, argues that microkernels may be making a comeback. Torvalds replied on a public internet forum (Torvalds, 2006), putting forward the same arguments used 14 years earlier.
    In this article, I will try to make the ‘microkernel vs. monolithic kernel’ debate more accessible and understandable for laymen. I will explain the purpose of a kernel, after which I will detail the differences between the two competing designs1. Finally, I will introduce the hybrid design, which aims to combine the two. In the conclusion, I will argue that this hybrid design is the most common kernel type in the world of personal computers2 today.

    What is a kernel?
    Every operating system has a kernel. The task of an operating system’s kernel is to take care of the most basic of tasks a computer operating system must perform: assign hardware resources to software applications in order for them to complete the tasks the users want them to do. For instance, when you browse through the world wide web, your browser needs processor time to properly display the web pages, while also needing space on your hard drive to store commonly accessed information, such as login credentials or downloaded files. While it is the task of the operating system to properly spread the computer’s resources across running applications, it is the kernel that performs the actual act of assigning.
    You can compare it to a chef cooking a dish in a modern kitchen. The various ingredients (the computer applications) need to be prepared using kitchen appliances (the system resources) in order to form the dish (the operating system) after which this dish can be served to the people attending the dinner (the users). In this analogy, the chef is the kernel because he decides when the ingredients are put into the kitchen appliances, while the dish is the operating system because it depends on the dish which ingredients and kitchen appliances are needed. This analogy also stresses the symbiotic relationship between kernel and operating system: they are useless without each other. Without a recipe, a cook cannot prepare a dinner; similarly, a recipe without a cook will not magically prepare itself.

    Differences between kernel types
    An important aspect in operating system design is the distinction between ‘kernelspace’ and ‘userspace’. Processes (each computer program is a collection of processes) run in either kernelspace or userspace. A process running in kernelspace has direct access to hardware resources, while one running in user space needs to make a ‘system call’ in order to gain access to hardware (Cesati & Bovet, 2003). For instance, when you want to save a document in a word processor, the program makes a system call to that part of the kernel which manages hard drive access, after which this access is granted or denied (in other words, the document is stored on the hard drive or not). Because hardware can in fact be damaged by software, access to it is restricted in the above manner.

    In a monolithic design, every part of the kernel runs in kernelspace in the same address space. The definition of address space is beyond the scope of this article, but one consequence of all parts of the kernel running in the same address space is that if there is an error (‘bug’) somewhere in the kernel, it will have an effect on the entire address space; in other words, a bug in the subsystem that takes care of networking might crash the kernel as a whole, resulting in the user needing to reboot his system.

    There are two ways to solve this problem. The first of the two is to ‘simply’ try to keep the amount of bugs to a minimum. In fact, proponents of the monolithic design often argue that the design itself forces programmers to write cleaner code because the consequences of bugs can be devastating. The major problem to this approach is that writing bug-free code is considered to be impossible, and the 6 million lines of code in for example the monolithic Linux kernel allow for a large number of possible bugs.

    Microkernels approach the problem in a different manner in that they try to limit the amount of damage a bug can cause. They do this by moving parts of the kernel away from the dangerous kernelspace into userspace, where the parts run in isolated processes (so-called ‘servers’) which cannot communicate with each other without specific permission to do so; as a consequence, they do not influence each other’s functioning. The bug in the networking subsystem which crashed a monolithic kernel (in the above example) will have far less severe results in a microkernel design: the subsystem in question will crash, but all other subsystems will continue to function. In fact, many microkernel operating systems have a system in place which will automatically reload crashed servers.

    While this seems to be a very elegant design, it has two major downsides compared to monolithic kernels: added complexity and performance penalties.

    In a microkernel design, only a small subset of the tasks a monolithic kernel performs reside in kernelspace, while all other tasks live in userspace. Generally, the part residing in kernelspace (the actual ‘microkernel’) takes care of the communication between the servers running in userspace; this is called ‘inter-process communication (IPC)’3. These servers provide functionality such as sound, display, disk access, networking, and so on.

    This scheme adds a lot of complexity to the overall system. A good analogy (Microkernels: augmented criticism (no date)) is to take a piece of beef (the monolithic kernel), chop it into small parts (the servers), put each of those parts into hygienic plastic bags (the isolation), and then link the individual bags to one another with strings (the IPC). The total weight of the end result will be that of the original beef, plus that of the plastic bags and string. Therefore, while a microkernel may appear simple on a very local level, at a global level it will be much more complex than a similar monolithic kernel.

    This complexity also creates performance issues (Chen & Bershad, 1994). Simply put, the communication between the servers of a microkernel takes time. In a monolithic design, this communication is not needed as all the servers are tied into one big piece of computer code, instead of several different pieces. The result is that a monolithic kernel will generally out perform a microkernel (provided they are similar feature-wise). This explains why Torvalds chose to write Linux in a monolithic fashion; in the early ‘90s, computer resources were much more limited than they are today, and hence anything that could increase performance was a welcome addition.

    As an answer to these concerns, a new type of kernel design was devised. This design combines the monolithic and microkernel design in that it has characteristics of both. It keeps some subsystems in kernelspace to increase performance, while keeping others out of kernelspace to improve stability. That part of a hybrid kernel running in kernelspace is in fact structured as if it were a microkernel; as a consequence, parts which run in kernelspace can actually be ‘moved out’ of it to userspace relatively easily. Microsoft Corp. has recently demonstrated this flexibility by moving large parts of its audio subsystem in the Windows operating system from kernelspace to userspace (Torre, 2005).

    The hybrid design has been heavily criticised. Torvalds (2006) and Rao (2006) said the term hybrid was devised only for marketing reasons, while Mikov (2006) argues that the fact that hybrid kernels have large parts running in kernelspace outweighs the fact that it is structured as a microkernel.

    I disagree with these criticisms on the basis that if system C combines aspects of both systems A and B, it is a hybrid of those two systems. As an analogy, consider the mule (the offspring of a female horse and a male ass). The mule carries characteristics of both an ass as well as a horse, and hence it is classified as a ‘hybrid’.

RDK is available at CodePlex?  Well it is - that is a working version of the OS.  (Requires Virtual PC2007 or - from the manual:

"If you want to boot Singularity onto a physical PC, you need a PC with at least 512MB of RAM and a Pentium II or later processor. If you want to pursue this, please contact singrdkq@microsoft.com for more information." HA HA HA)

This is it booting...

 

image

Check out this interview of Jim Larus and Galen Hall the architects of this OS.


Singularity: A research OS written in C#