So You’re About to Graduate with a Degree in Computer Science…

Introduction

I’m going to relax and write a free-form blog post today about preparing for a career in the field of Computer Science. This post is directed at students that are getting close to graduation or are thinking ahead about how they are going to turn their expensive degree into a job that is both satisfying to work at and earn an excellent income.


How Prepared are Students Fresh out of College?

I’m afraid that this question is more complicated than it seems.  Technically the core Computer Science courses taught at major universities are more than adequate to get you started in the field of software development.  However, competition is tough, and you want to rise above the “average” student.  You also don’t want to spend a lot of time finding a job.  It’s better to be able to choose from a list of jobs.  Knowledge that is taught in the classroom is just the foundation that you need to build your career on.  You’ll need to learn some practical knowledge before you can really shine, and you’ll need to make sure you fully understand the principles that you learned in college.  What principles am I talking about?  Object oriented programming principles for one.  Database design principles, data structures, coding practices, etc.

What all this means is that you’ll have to do some studying outside the classroom.  You’ll also need to do a few example programs to gain a full understanding of the subjects you’ve been taught.


Does this Stuff get Easier when I get into the Working World?


As you get more practice at building software it definitely gets easier.  Some techniques are still hard, and the ever-changing technology world makes learning new things a constant task.  It also makes it an interesting and challenging career.  As a student, most people are just learning about the syntax of their first language.  Once you’ve written a few programs, the syntax will come automatically, like riding a bicycle.  At first, riding a bicycle is all about focusing on balancing.  After a while, you don’t think about balancing any more.  It’s automatic.  The same applies to programming.  Once you know the syntax, then the next challenge is learning how to apply algorithms to solving the total problem.  This is really just a challenge in breaking the problem down small enough to solve with an algorithm you have in your tool box.  Once you have that down, you just get so good at it that you can think up solutions to big problems in minutes.


Is there any Way to Prepare Myself Now?

Yes there is.  There are two primary directions in the software development field and you’ll need to choose one field or the other so you can focus your efforts.  One field is the .Net field with Microsoft products like Visual Studio, IIS, C#, Visual Basic, SQL Server, etc.  The other field is unix based systems with PHP, Ruby, Python, Apache, Oracle, MySQL, etc.  There are other fields as well, but I’d stick to one of the two main paths.  I have developed software from both fields at one time or another.  I rarely use my knowledge from both fields.  Normally a company will pour their resources into one or the other and it’s difficult to try and learn both at the same time.

Currently, I’m working for a company that uses Microsoft products and I’m working in the .Net field.  So I’m going to give some pointers on how you can prepare yourself to get a good job with some .Net knowledge coupled with your college degree.

As of this writing this is what you should learn outside of class:

1. MS SQL server
2. C#
3. An ORM using LINQ queries (Entity Framework is an easy ORM to learn)
4. MVC website programming

Start off slowly.  Ease into it.  If you try to bite off too much you’ll get frustrated and give up.  What you want to do is learn how to install some free software, experiment with it on a small scale and then think up a project that want to build using the techniques you learned.  This is important, and it’s can be listed on your resume as a hobby.  Hobbies that involve your career will impress a person looking at your resume.  It makes the statement that you are serious about your career and you are interested in the job that you are seeking.  


OK, I’m Sold, How do I get Started?

Start with MS SQL server express.  Type “download ms sql server express” into google and look for microsoft’s download center.  Download the software and install it on your PC.  As of this writing SQL Server Express 2012 is the current version available.  Avoid using any pre-release or Technology Preview versions.  These could have bugs and will only distract you from learning what you really should learn: How to create and access a database.

OK, now, let’s assume you installed SQL Server and you want to proceed.  Open the Server Manager Studio console and get familiar with how it works.  This is an interface into your database.  Right now you don’t have any databases created, so right-click on the “Databases” node and select “New Database”.  Give it a name (I’ll call mine “sampledata”) and create it.  Next, create a table inside the new database.  Open your database node (“sampledata”) by clicking on the “+” symbol next to it.  You’ll see what looks like a subdirectory named “Tables”.  Right click on that and select “New Table”.  Give it a name (I’ll call mine “students”).  You’ll be presented with a designer interface where you can create fields (called columns).  Name the first column “id”, then make it an “int”.  Name the second column “Name”, then make it a “char(50)”.  You should see something like this:

Now click on the save button and name the table “student”.  Close the current window.

Next, we’re going to put some data into that table that we created.  Open the subdirectory named “Tables” and right click on the node named “dbo.student”, select “Open Table”.  Now put some data into your table.  Here’s a sample of what I typed into my table:


What are you learning?  You’re beginning to learn the basic tasks of setting up a database.  Next, let’s do a simple select query.  Click on your table node and then click the “New Query” button. There is a little drop-down list in the tool bar that is above your “Object Explorer” window and it should say “sampledata” in it.  That is the current database that will be queried.  If this drop-down does not have your database selected, then just select your database.  Then your queries will be performed against tables in your database.  Now type this into the query window:

select * from student

Hit the F-5 key, or click on the “! Execute” button.  You should see this at the bottom of your query window:


Now you can experiment with your query to select all the students and order by “name”, select students with “id” less than 3, etc. etc.  Create a second table that is related to the first table you created.  Then fill it with data and learn how to join two tables together.  Do some research on inner join and outer join.  Practice your queries by adding more related tables and test joining them together.  You should fully understand what an outer join is and the difference between a left and right outer join.  You could spend a day learning this knowledge, but it will become the knowledge that sets you apart from a newly minted college student.


Is that all?

Nope.  That’s just the beginning.  Next, you should download Visual Studio for web development.  The free version.  Type “visual studio express” into google and find the Microsoft products screen.  Currently “Express 2013 for Web” is available as well as “Express 2013 for Windows”.  Download “Express 2013 for Web” and install this on your machine.  You’ll need an MSN account to download it, this is free.  It’s a bit time consuming, but I’m going to teach you how to connect to that database that you just installed and created.

Once you’ve installed Express, start it up and create a new MVC4 project.  You’ll need to look under the “Visual C#” section then under “Web” and select “Visual Studio 2012” and finally click on the “ASP.NET MVC4 Web Application” type.  Give it a name and click “OK”.  Next it will ask you what type of MVC application you want, choose an empty project with razor in the drop-down.

In your solution explorer (the panel in the top right corner of visual studio) right click on the “controllers” directory and “add”, then click on “controller”.  Leave the dropdown as an “Empty MVC Controller”  and name it “HomeController”.  Click the “Add” button.  You should see a window with a little bit of code an din the middle is a “return View();” line of code.  Right click on “View()” and select “Add View” then click the “Add” button.  This will create a matching view for this controller.  Now you’ll see a cshtml web page.  At this point, you have a working website and it will startup a virtual webserver and a webpage will appear withe word “Index” on it.  Yeah!

OK, seriously.  Let’s connect to a database and read something, then print it on the web page.  Right-click on the “Models” directory in your “Solution Explorer” window, then “add -> New Item”.  Click on the “Data” item and click “ADO.NET Entity Data Model”:


Just click the “Add” button and leave the default name “Model.edmx”.  Click “Next” to generate from a database.  Now you’re going to need a new connection.  This is the tricky part.  Click the “New Connection” button and select a “Microsoft SQL Server” datasource.  Click “Continue” and another window appears.  You should be able to select your server from the “Server Name” list.  It should match the name that appears in the SQL server connect to database window.  The server name is also shown in the top of your “Object Explorer” of the SQL Server Management Studio window.  You can correct the name by typing it into the “Server name” text/drop-down control.  If it is correct, then you can select the database (leave the “use windows authentication” radio button alone).  Select your database and click “OK”.  Then click the “Next” button.  Now you’ll see this window (assuming all went as planned):


Now drill down into the tables and check all the tables you wish to access from your program and click the “Finish” button.  

If your table does not contain a primary key, then you’ll have to do some research (because EF will not allow tables without primary keys).  This is easy to fix by going back to the SQL Server console, right-click on your table and select “modify”, then right click on the “id” field and make it “set primary key”.  If your data has unique values in that field, you can save your changes.  If that field contains data that is null or duplicated, you’ll need to fix the data first, then come back and add the primary key. Sounds frustrating?  You’re learning a very important lesson about database design.  Set the primary key first, then put data in the table.

If you need to update or add tables to your entity framework, you can double-click the edmx file in the solution explorer of visual studio and then right-click on the blank window and select “Update Model from Database”.  That will take you back to the window pictured above and you can check all tables that you want to add to the edmx file.  You should see a little graphical representation of your table in the context window.  Now make sure you click on the model1.edmx window to ensure that it is currently selected, then click on the save button.

Now you have knowledge of how to setup an Entity Framework context.

Next, let’s go back to the HomeController.cs file and add a using at the top.  I’m trying to minimize the amount of code here, so I’m going to cheat and access the database directly from the controller.  Normally you’ll create classes in your Model directory and they will access your data and return it to your controller.  

Type this after your last using statement:

using TestMVC4Application.Models;

Now type this inside your controller (assuming you added a table named student to your context):

public ActionResult Index()
{
    using (var db = new sampledataEntities())
    {
        var studentNames = (from s in db.students select s.Name).ToList();

        return View();
    }

}

The “sampledataEntities()” name came from the context.  If you double-click on your edmx file and click on the background window, you’ll see the properties in the lower right that will tell you your “Entity Container Name”.  That is the context name.  Very important knowledge.

In the code above, I opened a context and called it “db”.  Entity framework renamed the table with an “s” on the end.  It creates a class with the table name and it creates a list with the same name and an “s” on the end.  Lesson to take from this is to always name your SQL Server tables in singular form (like “student” or “teacher, not “students” or “teachers”).  That will save you some headaches later when attempting to find the right names in your LINQ code.

Now your program will run, but nothing new will happen.  You’ll still get a webpage with “Index” printed on it.  However, you can now put a break-point on the “return View()” line of code and run your program.  There is a gray bar on the left side of the window.  Click on that bar at the line of code you wish to break on and it will turn the line red.


Now run your program.  When it stops at the red line, you can hover your mouse cursor over the studentNames variable and see that it has items in it.  Now add a line to put your studentNames into the viewbag variable:

public ActionResult Index()
{
    using (var db = new sampledataEntities())
    {
        var studentNames = (from in db.students select s.Name).ToList();

        ViewBag.studentNames = studentNames;

        return View();
    }

}

The ViweBag object is part of razor and it allows you to transfer data to the view.  Now double-click on your view called “Index.cshtml” (it’s located in the Views folder in the Solution Explorer.

Add a line to your view:

@{
    ViewBag.Title = “Index“;
}

<h2>Index</h2>

@ViewBag.studentNames[0]


This will print the first student name (it’s at index zero of an array of students).  Run your program and see for yourself.

If you got this far, then you have just learned a little MVC programming.  You learned a little C# programming.  You learned how to setup and use an ORM called Entity Framework.  You learned a little bit of Razor.  You also learned how to connect to a database server and read data into your application.

Now it’s time to run with it.  Find a web application that you want to build.  Something that is not too big, but big enough to be a challenge.  Design and build your database, test your queries using the SQL Server Management Studio console.  Add tables to your edmx context in your C# application.  Try out your queries in LINQ inside your controller.  Add controllers and views.  Tweak the HTML inside the view to display your data in a more attractive format.   If you can’t figure out how to do something, Google it.  There are a lot of Entity Framework LINQ sites that show how to do queries.  There’s a lot of examples of MVC programming and Razor.

You need a project that will hold your interest for a while.  Once you’ve built something that performs a real task, you’ll have a working knowledge of these technologies.  These are valuable tools that you should put on your resume.  Make sure your confident with these technologies and go nail down that job you really wanted.



 

Fluent NHibernate Using Multiple Database

Summary

This time I’m going to show how to use tables from two different databases in one context.  It’s difficult to find information on this subject and many links point to an article that uses a dictionary of context’s with all kinds of fancy configuration and code to map things.  After an hour of hunting around in that rabbit hole (technically, the technique being presented works across different database servers, where the version I’m looking for is multiple databases in one server), I stumbled onto something that Fluent NHibernate has that makes it all soooo clear.  Inside the class mappings for each table you can specify the exact table mapping in the database.  This can be used in situations where you want to use a different name for your class object table name than the database table name.  It can also be used to define which database your table is accessed from.


Setting Up

The ERD I’m going to use looks like this:



I’m trying to keep this simple, so there are really no integrity constraints as shown in the diagram above.  Each class can have one teacher, and each student can only be in one class (but classes can have more than one student).  This is not really practical, but it’s just a minor example.  Technically, I could have shown this example with two tables, but I want to demonstrate two tables in one database and one table in a different database.  The databases are named facultydata and studendata.

Don’t forget to populate your database with some data.  I hand-typed this data into the three tables shown:




On to the Code

Here’s the class for the Student table with the mappings.  This is where the magic occurs:

public class Student
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int classid { getset; }
}

public class StudentMap : ClassMap<Student>
{
    public StudentMap()
    {
        Id(u => u.Id);
        Map(u => u.Name).Nullable();
        Map(u => u.classid).Not.Nullable();
        Table(“studentdata..student“);
    }

}

Notice the addition of the “Table” mapping.  Also notice that I introduced the database name right in the table mapping string.  NHibernate will replace the tablename in any “where” clause of it’s queries with the whole text inside this mapping.


How do I do the LINQ Query?

No difference.  Here’s the query that I used:

using (ISession session = NHibernateHelper.OpenSession())

{
    var query = (from t in session.Query<Teacher>()
            join c in session.Query<Class>() on t.Id equals c.TeacherId
            join s in session.Query<Student>() on c.Id equals s.classid
            select new 
            { 
                TeacherName = t.Name,
                ClassName = c.Name,
                StudentName = s.Name

            }).ToList();
}

That is the only change from previous NHibernate blog examples.  You can download the entire Visual Studio 2012 project here: 

NHibernateMultipleDatabases.zip


What if I have Two Tables with the Same Names?

For this situation, I would use the mapping to indicate which table is being referenced, then change the class name to reflect which table.  Let’s say that you had a student table in two different databases (who knows why, but this stuff happens).  You can name each class with a combination of database name and table name like StudentdataStudent and FacultydataStudent.  When you form your LINQ query, you’ll use the long name version of your tables and the ORM will map to the table in the correct database.

 

Entity Framework 6 vs. NHibernate smackdown!

It’s time for a performance test between EF-6 and NHibernate.  Previously I did a smackdown between EF-6 and LINQ-to-SQL (see this article: Entity Framework 6 vs. LINQ-toSQL smackdown!).  This time I’m going to show the performance of inserts between EF-6 and NHibernate.

I used the same tables and data as in the previous blog posting.  The code I used for NHibernate to insert records looks like this (I also created code for select, update and delete):

using (db.BeginTransaction())
{
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 1000; i++)
        {
            Person personRecord = new Person()
            {
                first = firstnames[i],
                last = lastnames[i],
                department = 1
            };

            db.Save(personRecord);
        }
    }
    db.Transaction.Commit();
}

Here are the results from the CRUD tests comparing EF-6 with NHibernate (I also threw in the latest test run of LINQ-to-SQL for comparison):


OK, now for a few caveats:

1. I ran each test 5 times and chose the fastest time.
2. LINQ-to-SQL is not optimized for maximum speed.
3. These times are based on my machine at the time that I ran these programs.
4. These tests are only for general cases.
5. I put the select query in a loop to run 1000 times to obtain a measurement.

Generally speaking it appears that NHibernate is quite a bit faster than either EF-6 or LINQ-to-SQL for CRUD operations.  The select query is not a very good test.  In fact, the bulk of the time could be attributed to the looping code itself since my guess is that a select is all done within the ORM once the data has been cached.  A more effective test would involve 5 to 10 large tables of data using multiple types of select cases (like subqueries and outer joins, order by’s and group by’s).  Another test that should be performed as a baseline, would be a direct sql query without the aid of an ORM.  This should be faster than all of these ORMs.

To obtain the code, download this zip file containing all 3 test projects:

ORMSpeedTestProjects.zip

If you download and use these projects, don’t forget to change the configuration settings for each project to point to your database!


 

JQuery Stuff

I was the “bug person” the other day, (which means that I get to fix bugs for the day) when I came across a bug involving a check box.  Basically, the check box didn’t work.  Clicking on the check box caused the page to refresh and remain unchecked.  As I dug into the JQuery code that was attached to the check box click event, I found something rather interesting.  There are a lot of ways to check a check box to see if it is checked or not.  The code that was used was by the section of code I was fixing was incorrect.

First, the HTML code:

<input type=”checkboxid=”MyCheckBox” />My Check Box

Next, the JQuery:

$(document).ready(function () {
  $(‘#MyCheckBox‘).click(function () {

    var test1 = $(‘#MyCheckBox‘).prop(‘checked’);
    var test2 = $(‘#MyCheckBox‘).attr(‘checked’);
    var test3 = $(‘#MyCheckBox‘).checked;

  });

});

The question here is what are the results of “test1”, “test2” and “test3” when the check box is checked?  As it turns out, test1 is the only valid output (returning true).  The other two will return an “undefined” output.

The problem with test2 is that there is no “checked” attribute defined in the html.  So let’s define it:

<input type=”checkbox” id=”MyCheckBoxchecked=”checked” />My Check Box

Now the results have changed.  First, the check box is already checked (due to the fact that the html tells it to be checked).  Second, test2 now returns “checked” instead of undefined.  Check1 returns false, as expected and test3 still returns “undefined”.

At this point, you can see where the attr is returning the attribute of checked (which is normally equal to “checked” or “”).  If you perform a true/false comparison with this value, you will get some iffy results.  To guarantee a true false, use the following code:

if ($(“#MyCheckBox“).is(“:checked“)) {
  alert(‘checked‘);
}
else {
  alert(‘unchecked‘);

}

This will give the correct true/false results.

Of course, using the property method also guarantees a true/false result:

if ($(“#MyCheckBox“).prop(“checked“)) {
  alert(‘checked‘);
}
else {
  alert(‘unchecked‘);

}

Test3 does not work under any of these samples.  I would avoid using it.  I personally use the “prop” or property to check for true/false, because I don’t have to worry about the colon that is required when using the “is” statement.  it’s very clean and simple.  I also leave the checked=”checked” off the check box, unless I need to initialize it to true to start with.

The bug I was fixing used the attr inside an if statement and assumed that true/false was the result.  I changed it to use the property instead, and now there is one less bug.  😉

 

Fluent NHibernate with MS SQL Server

Summary

I’m currently researching all my options regarding ORM’s.  In my previous posts I talked about NHibernate and how to setup a simple example.  This time I’m going to demonstrate how Fluent NHibernate works and how you can use it to avoid setting up xml documents for mapping your tables.

Project Setup

Create an empty console application in Visual Studio.  Go to your NuGet window (Tools -> NuGet Package Manager -> Manage NuGet Packages For Solution…).  Search for FluentNHibernate and add the package to your project.

Next, create a subdirectory inside the project called “domain”.  Now create a cs file named “product.cs” and copy this code into it:

using FluentNHibernate.Mapping;

namespace FluentNHibernateBlogPost
{
    public class Product
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Category { get; set; }
        public virtual bool Discontinued { get; set; }
        public virtual int Store { get; set; }
    }

    public class ProductMap : ClassMap<Product>
    {
        public ProductMap()
        {
            Id(u => u.Id);
            Map(u => u.Name).Nullable();
            Map(u => u.Category).Nullable();
            Map(u => u.Discontinued);
            Map(u => u.Store);
        }
    }

}

Next, add a cs file called “store.cs” and copy this code into it:

using FluentNHibernate.Mapping;
using System.Collections.Generic;

namespace FluentNHibernateBlogPost
{
    public class Store
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Address { get; set; }
        public virtual string City { get; set; }
        public virtual string Zip { get; set; }
    }

    public class StoretMap : ClassMap<Store>
    {
        public StoretMap()
        {
            Id(u => u.Id);
            Map(u => u.Name).Nullable();
            Map(u => u.Address).Nullable();
            Map(u => u.City).Nullable();
            Map(u => u.Zip).Nullable();
        }
    }

}

Now we need the session factory.  Create a cs file in the root directory and name it “SessionFactory.cs”, copy this code into it (modify your connection string to match your database, you can copy it right out of the xml file from the previous project, if you got that to work):

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace FluentNHibernateBlogPost
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    _sessionFactory = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2005
                    .ConnectionString(“Server=localhost;Initial Catalog=sampledata;Integrated Security=True“))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
                    .ExposeConfiguration(config =>
                    {
                        SchemaExport schemaExport = new SchemaExport(config);
                    })
                    .BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }

}

Now you can write a query and access your data.  For this sample, I’m going to use the exact same query that I did in my previous blog post just to demonstrate that the output will be identical.  Modify your Program.cs file to look like this:

using System;
using System.Linq;
using NHibernate;
using NHibernate.Linq;

namespace FluentNHibernateBlogPost
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                var query = from p in session.Query<Product>()
                            join s in session.Query<Store>() on p.Store equals s.Id
                            where s.Id == 2
                            select p;

                foreach (var item in query)
                {
                    Console.WriteLine(item.Name);
                }
            }
            Console.ReadKey();
        }
    }

}

That’s it.  That is the entire program.  No XML files.  No embedded properties, no copy always properties.  No special configuration files.  Just code.  One of the advantages that I’m looking for in this example is that this project will be easy to merge when multiple developers alter tables.  When hand-merging occurs, the developer will be looking at C# code and not attempting to decipher xml.

You can download the entire project here: FluentNHibernateBlogPost.zip