Monday, May 8, 2017

.NET Literacy Day 4: Start! (Really!)

A Fresh Start

I'm excited for today. I finally have time to focus my attention back on .NET. I plan to get back to the Vidly project, but since I have had a gap between my first completed C# course (Beginners Guide to OOP With C# and Visual Studio 2017), the start of Mosh's MVC5 course (The Complete ASP.NET MVC5 Course) I decided to take another run at the basics with C# Basics for Beginners: Learn C# Fundamentals by Coding, by Mosh Hamedani.

Hello World

As with most tutorials, Mosh starts out with a Hello World console app. Even though this is just a console app, there are a number of files involved.

AssemblyInfo.cs

When the app is compiled it creates an executable. This is called an assembly. Under properties, the AssemblyInfo.cs file contains titles, descriptions, version numbers and so on, that describe the assembly.

References

The references section contains assemblies that are available for use in the project. By default, Visual Studio includes commonly used assemblies that are part of the .NET framework.

App.config

App.config is an xml file that is a good place to store database connection strings or other application specific information. This is also where you would specify the debug listener so you can see System.Diagnostics.Debug.WriteLine() messages.

Program.cs

The default C# template, called Program.cs references several assemblies with the using command. Some of these won't be used by our hello world app. For example, Linq is for data manipulation. If you mouse over System.Linq, you will see a message saying the Using directive is unnecessary. 

If  you click the Show potential fixes link, all of using directives will be highlighted. For a hello world app, we only need System, so I'll go ahead and remove the other 4.

Namespace

A namespace is a way to group classes together. The using directive allows you to reference classes in an external assembly's namespace. For example, using System allows our program to reference things like System.Console.WriteLine() by leaving off the namespace (i.e. Console.WriteLine()). It is perfectly valid to forego the using directive and type System.Console.WriteLine(), but your code will quickly become verbose. In Program.cs, the default namespace name is the same as the solution, HelloWorldConsole in my case. 

static void Main(string[] args)

This is the program entry point. If Main is not capitalized, it won't be recognized as the entry point to the program. The one-line HelloWorldConsole application will be written in Main() like this:

Console.WriteLine("Hello World!");

Running in Debug Mode

If you attempt to run the hello world app using [F5], you will notice the console window closing almost immediately. Using [CTRL][F5] will launch the app in debug mode, which prompts for a key press to close the console window.

Riffing: System.Diagnostics

The term riffing means to take a subject and improvise on it. With every lesson project, I like to explore outside the bounds of the assignment. In section 1, Mosh was introducing students to the broader concepts like namespaces and assemblies, so there isn't much to explore in the coding direction; however, while googling namespace for more information, I came across System.Diagnostics.Debug.WriteLine().

Adding that to the HelloWorldConsole app...
...produced no results. Only "Hello World" showed in the console.

The crowd-sourced explanation for this method said that it only displays when running in debug mode, which sounds incredibly handy. The truth is a bit more complicated, as you have to set up a listener to hear messages sent on this channel.

I found a blog post that explains how to add a debug listener to App.config. As instructed, I pasted their example code into the section of App.config.

<system.diagnostics>
  <trace autoflush="true" indentsize="4">
    <listeners>
      <add name="configConsoleListener"
           type="System.Diagnostics.ConsoleTraceListener" />
    </listeners>
  </trace>
</system.diagnostics>

After that, the debug message showed up in the output.

These messages are great because they do not show up in the release build. How do you toggle the debug/release build? The drop down is at the top of the screen:


With the compile mode set to Release the debug message is hidden:
Cool!



Friday, April 28, 2017

.NET Literacy Day 3: GitHub Solution Cloning / Relocation Fallout

Hm. Still not done with the fall-out from cloning my repo and moving it into a new location. Everything in VS looked okay at first, but there was a green squiggly green line under my solution. Mousing over it revealed this message:

Once again, VS automation facilitates the solution, but ... this process seems really messy. I have to think that I have either done something wrong, or I'm not taking the best approach. Time to Google.

The Microsoft Git Quickstart was somewhat helpful, in that it confirmed what I knew. I found this interesting question on Stack Overflow asking whether Git repos should be at the project level or solution level. Visual Studio facilitates storing at the solution level, so I'll stick with that for now. Well, since no quick advice on approach is forthcoming, I'll charge ahead and research this later. I'm either going to get this repo working, or hit a wall. Either way, I'm going to go through this exercise again start to finish so I understand what is involved when I clone a solution.

Back to my squiggly line... Following the instructions, I right clicked on the solution and chose "Manage NuGet Packages". VS found the missing packages and facilitated the install. Even after the action completed, the green squiggle remained with the same message. There were a number of updates available, so I installed those as well. Green squiggle was still there. I right clicked on the solution and chose Clean and the green squiggle disappeared. Several supporting files were changed during the NuGet update, so I did a Commit / Push to get those changes out to the remote repository.

So! Ready to go, right?

Wrong. Ok... What the heck? Right click the solution, choose Restore NuGet Packages and I'm told everything is fine.

Clearly, I've got configuration issues. Hm. Stack Overflow seems to think I need to fix the relative paths in my .csproj file, That was part of the problem. There were references to a  ..\packages folder, which did not exist. The error message mentions Microsoft.Net.Compilers.1.3.2, which I did not see in my solution's \packages folder. How are packages missing? Shouldn't they have been part of the solution in Git? I browsed for the package with the NuGet manager and installed it.

One frustrating hour later... the package installed had a different folder name. I found the original package path in Program Files under Microsoft Web Tools. The vidly.csproj file is pointing to the right path, but VS still says the wrong path. I tried putting the missing package in the "wrong" path and it still did not care. The same error message appeared. Very frustrating.

Sigh... this is technology in the raw. You want to jump right in and start something new, but you are hamstrung by the setup. Time to cut my losses.

Goals for Day 4

Tomorrow, I'm going to create a new repo in GitHub, clone it locally and rebuild this basic project. Then, I'm going to move the project to a new folder and see what happens. I need to understand all of the dependencies these prefab projects have and where they are located. 



Wednesday, April 26, 2017

.NET Literacy Day 2: More GitHub fun

Time does like to slip by, doesn't it? One quick media project for the swim team and suddenly its Wednesday. Tonight I started by trying to clone my Vidly repo, which I had deleted from my local hard drive (intentionally).

Linking Directly to Revisions

Last time, I was considering the best way to create and link to projects and I discovered (thankfully) that I am able to link to specific revisions in GitHub. I decided to reset my local folder structure, but had to stop before I finished. 

GitHub Desktop

After adding Vidly to GitHub Desktop
In my (admittedly few) previous dealings with GitHub, I would always clone by downloading a zipfile, then unpacking it where I wanted it. This time I decided to download the GitHub desktop and see what it is all about. 

The interface is very sparse, especially when compared to SourceTree. (SourceTree is the Atlassian desktop product for their Git eco-system, which includes their cloud source hosting environment BitBucket.)

I provided my GitHub credentials to GitHub Desktop and saw a few of my repos right away. I'm pretty sure it found them in a default folder on my local machine. Vidly wasn't there, of course, so I popped back over to the GitHub site to get the URL, and added it to GitHub Desktop. From there, cloning the repo locally was easy.

Git Solution Cloning Fallout...


Back in Visual Studio, Team Explorer, I was able to add the local Git repo using the repo URL that I copied from the GitHub site.

From there, I attempted to open Vidly, but Visual Studio complained that a number of components were missing. Fortunately, VS facilitated installation. After that was done, the project itself couldn't find its own files. I needed to edit the Vidly.sln to correct the path since I cloned into a different repository.




Sunday, April 23, 2017

.NET Literacy Day 1: Vidly

The Course Project "Vidly" on GitHub

I made it through the first five videos in the The Complete ASP.NET MVC 5 Course, and even followed along building the shell of the Vidly app that we will be working on for this course. (I ended up spending the bulk of my time configuring Git, which I detailed in a separate blog.)

To introduce us to the course, instructor Mosh set up a video store app that he called "Vidly". It will have a login wrapper with two security levels, a paginated/sortable/searchable list of customers. We will be able to add/delete customers and edit the list of movies based on security level.

With pageant running, I was able to use TortoiseGit to push my local project up to BitBucket.

Here is check-in number 1
https://github.com/brienmalone/vidly

It is nothing to look at, really. It is just a simple MVC app with one object that has two properties. I'll go into the actual course material in tomorrow's post.

Saturday, April 22, 2017

.NET Literacy Day 1: Git / GitHub

Configuration Day: Git, Visual Studio 2017 and GitHub

Visual Studio 2017 has built-in support for Git and TFS. The tutorial talks about how to set up Git for your project. I don't even remember being asked to configure it. Either way, it automatically created a local git repo for my first project. I want my code to live in GitHub for safekeeping (and sharing). I found this stack overflow question that  appeared to have the commands I needed.


git init --bare repo.git
git push --mirror ssh://yourserver/~/repo.git

I had trouble authenticating on the remote GitHub repo from CMD.EXE. GitHub complained about validation because I didn't have the ssh agent running in the background to serve up the ppk key. I actually took care of this exact problem for a project, but I can't remember the ssh command to host the key (Did I do it from BASH? Probably...). I remember finding a lot of information on this topic before, but I also remember that SSH from DOS is a pain, so I abandoned this approach for some Windows-based tools.

GitHub

I started by creating the remote repo on GitHub. The landing screen contained a lot of useful information, including how to push an existing repository from the command line. I wasn't familiar with the --bare or --mirror options from stack overflow.The instructions from BitBucket looked a lot more familiar:

git remote add origin git@github.com:brienmalone/vidly.git
git push -u origin master

But... given the difficulty I was having with authentication from the command line, I opted to install some native Windows tools to help me out.

Git Tools for Windows

I'm not sure if Command-line Git was installed by Visual Studio, or if I did it at some point, but Git was available on the command line. (I'm working on a brand new laptop and don't remember installing it.) I have used Subversion and TortoiseSVN for source control for years, so I installed TortoiseGit for its familiar interface. I needed the putty keygen and pageant to serve the ssh key, so I installed PuTTY for Windows. Finally, I also installed Atlassian SourceTree, which is a very nice, free GUI. (Atlassian has its own cloud git service called BitBucket, which is nice, but I am sticking with GitHub for its ubiquity.)

Pageant

There are plenty of tutorials that explain how pageant works, so I won't go into detail here. In a nutshell, I run pageant, add my PPK key (created with the PuTTY keygen), install the openSSH version of the same key on BitBucket and I'm off and running with whatever tools I want to use (except CMD LOL).



.NET Literacy Day 0: Udemy

The Plan: Online Learning 

I'm a huge fan of online learning. Among my favorites are Lynda.com, The Teaching Company, Pluralsight, Udemy and Code Academy. To learn .NET, I have turned to Udemy.

Udemy has piles of tutorials for ASP.NET. It is often hard to tell the good from the bad, and the recent from the dated. The ratings and number of students are a good place to start. I'll list a few of my favorites so far below.

 I decided to pick up a range of courses that cover C# basics, .NET 4.5 (4.5.1, 4.5.2, 4.6 and Core), courses featuring Visual Studio 2017 back to 2013. Prospective employers won't always be on the bleeding edge, so it is good to have exposure to environments that were new 3-5 years ago as they will be common today.

 A few weeks ago, I worked my way through an excellent course by Tom O., Beginner's Guide to OOP With C# and Visual Studio 2017. This was a phenomenal place to start. I am familiar with design patterns and other object oriented programming concepts, but only through the limited window of ColdFusion scripting. Tom walks you through polymorphism, inheritance, properties, interfaces, and abstract classes with fun examples. What I liked most was that he leaves gaps for us to fill on our own. In one lesson, he creates an archer object with a count of arrows property and a method to shoot them. Call the shoot method enough times and the arrow count will go negative. This bugged me, so I figured out how to stop it from happening. The example code is littered with little annoyances like this that will drive born-to-code developers nuts - in a good way! The best teachers give students the tools to solve problems and demonstrate without over-explaining.

The course I'm starting now is The Complete ASP.NET MVC 5 Course, by Mosh Hamedani. Mosh has some of the most used, highest rated courses on Udemy. From the introductory material that I've seen, he is pleasant and easy to understand. In the coming weeks, I will be posting riffs on (i.e. my own modifications of) the examples he gives in his lessons on GitHub. (I will be setting this up tomorrow.)

Many years ago, I started working on a .NET project using the then "brand new" MVC 5. In this blog, I even kept track of the MVC 5 books that were coming out (and shamed the upcoming publications whose release dates slipped over and over again LOL!) I'm very excited to finally come back around to this topic.

Friday, April 21, 2017

My Quest for .NET Literacy

Start.

I have flirted with C# and ASP.NET over the years, but I've finally reached a point where I want to jump into the stack with both feet. I will be documenting my journey here and on GitHub.

Background

My first web development job started with ASP Classic back in 2000, thanks to a friend with an ambitious start-up. Unfortunately, the start-up went belly-up after a year, so I went back to a previous employer in a new role, as their web developer. Macromedia ColdFusion already had a foothold there. My boss was open to ASP, but I soon realized that rewriting their existing code would be a colossal waste of time with little net gain. Besides, ColdFusion was very easy to pick up. Look at query syntax...

In ASP Classic:




sSQL = "SELECT foo FROM bar"
sConnString="Provider=SQLOLEDB;Server=SOMESERVER\SQL2008R2;Database=WebDB;Uid=sa; Pwd=Password;"

Set connection = Server.CreateObject("ADODB.Connection")
connection.Mode=adModeRead
connection.Open(sConnString)
connection.execute(sSQL)

...and in ColdFusion:

<cfquery datasource="datasource" name="someQuery" timeout="60">
SELECT foo FROM bar
</cfquery>

On learning an equally simple CFMAIL tag replaced the rats nest of CDONTS code, I was hooked. Thus started a now 16 year career in web development, rooted in ColdFusion.

So, Why ASP.NET and C#?

In a nutshell, employability. ColdFusion jobs are harder and harder to find these days. We are fast becoming the COBOL programmers of the 21st Century.

While ColdFusion 2016 is nice enough to work with, the Microsoft stack is light-years ahead... Visual Studio vs Eclipse/ColdFusion Builder, .NET libraries vs CF libraries, Entity Framework vs roll-your-own service/gateway patterns, MVC vs FW1, ColdBox, ColdSpring, yadda-yadda... there is just no comparison. Add to that the quality and quantity of .NET online instructional resources, experts, and open source projects... The whole ecosystem is so much healthier.

To be fair, ColdFusion is far easier for a novice to pick up, thanks to its loose syntax and curious occasionally-typed variables, but these same features also lead to bad habits that newbies should avoid. Forget to define your function parameters? Meh. Its CF. You don't have to. (Good luck debugging THAT code.) Didn't scope your variable? CF will take a shot at finding it (...by cycling through every scope. Woohoo! Efficiency!) SO... While it is easier, I can't recommend ColdFusion as a good starting point for serious developers. You're far better off starting with a more rigid, structured language and picking up CF afterward if you need it for a particular job.

Goal

C# and ASP.NET literacy.

"Come again?"
To be clear, this won't be ASP.NET and C# for ColdFusion developers. This is just me eating the .NET elephant one bite at a time. Also, while individual posts may be useful for beginners, don't expect that by following each post from beginning to end, you will reach the same target that I do. I have a lot of experience and will be skipping over some fundamentals. The upcoming blog posts will simply be a running commentary as I learn. I have found that explaining concepts as I learn them helps cement them in place. If my posts happen to help new coders come to terms with these new concepts, then its wins all around.

Cheers,
Brien Malone
4/21/2017

Thursday, February 16, 2017

ES6 Arrow Notation 'this' Scope Bug with FiddleJS

I just ran into an interesting bug. I've been ramping up on ReactJS and as part of that, one of our senior devs recommended that I get a handle on ECMAScript 6. He pointed me to a nice ECMAScript 6 course on Pluralsight that I really enjoyed.

One of the exercises explored the "this" behavior inside arrow notation and how it differs from behavior within traditional function definitions.
'use strict';
var price = 5.99, quantity = 10;
var productView = {
   price : 9.99,
      quantity : 10,
      traditionalFunction() {
        return this.price;
   },
      arrowNotation : () => this.price
};

console.log('Traditional Notation ', productView.traditionalFunction());
console.log('Arrow Notation ', productView.arrowNotation());

In JSFiddle, the traditional notation returned the expected result (9.99), but the arrow notation says 'undefined' instead of 5.99.

















Running this same code in Chrome or Firefox (or even Plunkr) worked fine!


I thought maybe I needed to add babel to pre-compile down to ES5, but according to the babel website, JSFiddle already runs it for you. I'm not at all familiar with Babel, but the Babel "Try It Out" tool translates the arrow notation into the traditional notation, but swaps "undefined" for this.


Ah-ha! It turns out Babel _is_ the problem. The 'undefined' message is Babel's behavior. Apparently someone else noticed this almost a year ago (Mar 2016), but it wasn't addressed in the forum. I added my two cents and the screen shots above to the thread. When I have more time, I'll dig around to find the bug reporting channels.