Thursday, August 21, 2014

Var

Introduction


Sometimes I get lazy. Sometimes I get so lazy, I write a blog post with a 3-letter title. Sometimes I'm so lazy, I don't want to specify the type of a variable in the declaration so I use the keyword var and let the compiler determine the type for me. Yeah, I'm that lazy. Bow down all ye wannabe lazy folk and worship my laziness! The C# keyword var is my friend and my lazy-enabler, so let's discuss it today.

Details

First, a quick sample:

var thingy = new List<int>();

Normally the type of our variable would be List<int>, so you'd see that on both the left and right side of the = sign. However, the var keyword lets us implicitly set the type of the variable based solely on what's on the assignment side of the equation. Some of you might think "i hate stupid dynamic types; compilers and strong types are here for a reason!". Well, I agree with you, and guess what? var variables are in fact strongly typed! You get full intellisense on them in the Visual Studio editor, and the compiler determines the variable type and enforces it at compile type just as it would any other strongly typed variable.

Why?

Why might you want to use var in your own projects? Laziness is the best reason I've got. Let's say that later on you want to change the type of thingy from List<int> to List<long>. If you used var, you only have to change code on the right side of the equation. I know it's a small benefit, but like I said, I'm lazy and I think nearly every good programmer is in some fashion lazy. Less maintenance = more time for the beach! (or for you hardworking folks, more time for new features I guess).

It's also great for saving some typing in foreach loops. Check out this sample:

foreach (var item in bob.Possessions)
{
Console.WriteLine(item.ToString());
}

In this sample, maybe bob.Possessions is a collection of objects of type Possession, but hey it really doesn't matter. The key takeaway here is you don't need to know the exact class name to start up your foreach, and you've saved yourself some typing.


var is indeed for us lazy folks!

Why Not?

var isn't good for everything. I hate to use an incredibly abstract example, but this is about all I can come up with at the moment: Pretend you have an interface called IRepository, used to provide common methods for storing objects "somewhere". You have a class called MongoRepository that implements IRepository and stores your objects in MongoDB, and you have a class called SqlRepository that implements IRepository which stores your objects in SQL Server. Now if you have something like this currently in your code:

IRepository repository = new MongoRepository();


you wouldn't necessarily want to change this to use var. The reason is is because you have an interface that your concrete implementations must realize. Your local variable, being of type IRepository, enforces the contract (interface) but not the type (MongoRepository). If you instead use var, the type of your local variable will be MongoRepository instead of IRepository, which kind of decouples the class from the interface in an abstract sort of way and makes your code less resilient to change.

One more potential drawback: some people might find your code more confusing. Not me personally, but some people. I just find the code more succinct.

Limitations

var variables must be method scope.
var variables must be initialized where declared.

What's Next?

Lookup how to use var with LINQ!
Lookup how to use var with dynamic! (covered in a previous blog post).
var with a using statement is the bee's knees!

Resources

Implicitly Typed Local Variables

Wednesday, August 20, 2014

jquery advanced lesson

Now that we've seen the cheese of HelloKitty, lets add the pizza sauce and toppings to make a more complete pie.

So you've got some code for the greatness of HelloKitty, lets add some graphical images to it that're numbered and hot-swap the display on the fly when you click the numbers.  I'm a fan of graphics, lets see what we can do.

To do this you'll need a few toys for jquery:
jquery.easing.1.3.js has some cool transitional effects.
jquery.slideviewer.1.2.js slidify's the graphics in a way i'd like to see them.

Heck, lets throw in some CSS for good nature.  Here's some css i've named look.css, it's been "borrowed" from teh interwebz:




So we have some css, time to do some includes of the new jquery files besides the .css file.  Your new code should look something like:



The new changes:
   1) the <link> tag and info to hook in your .css file.
   2) a couple of new <script> tags to use jquery.easing and jquery.slideviewer.
   3) new jquery to load the gallery and use the slideView option.  this does a pretty cool transition effect when you click each number below the viewed graphic.
   4) the div tag that holds the ul (unordered bullet list) with links to images out on teh interwebz i'd found along with some alt tags for each one for a hover over effect when you hover over the number.
   5) chances are your images aren't the same size either, i tweaked a little bit on the widths and heights to make it look better than it started with.

Now you're wondering: i'm not coding this crap, show me some results!  Here are some screenshots:








Tune in next time when we attempt to write our own plugin. Using a plugin is one thing, writing one should be epic!

Wednesday, August 13, 2014

jquery install + basics

Why JQuery you say?  24 million + websites out there use it (source : http://www.smashingmagazine.com/2012/05/31/50-jquery-function-demos-for-aspiring-web-developers/)
Also add javascript library functionality (aka you don't have to invent the wheel) which can speed up your dev time.  Kind of a win/win situation to me.

So you want to use some JQuery on your site eh.  You have a couple of options: go download and host the file itself (Option 1) or trust in Google's up-time and let them host it.

Option 1:
To start, go to www.jquery.com/download and snag the jQuery 2.1x code.  Why you ask?  IE 6/7/8 are deader than fried chicken, that's why.

As small as the .js file is (242kb) short of being on dialup you shouldn't have any issues downloading the uncompressed version.

your code would look something like:
    <script src="~/scripts/jquery-2.1.1.js"></script>

Option 2:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

So now we have something hooked into our code to do a little bit of work with JQuery, lets do a little bit of generic type coding for fun.  What i want to do is hide some paragraph text based on clicking on it as well as changing the link color and font size based on a button click.  to do so, coding time:





Try the code out for yourself: here's what it looks like rendered:














Lets click the line Delete me!.  here's the result:










After clicking Delete me too!.:








Lets hit the button to change colors/font size:







Tune in next time where we try some more of the advanced features available to us.

Yield Return

Introduction

You're all familiar with yield return by now right? You know, that yellow traffic sign that means you have to yield to oncoming traffic, then return from whence you spewed forth never to return. Wait, what's that you say? This is a .Net coding blog not a traffic blog? Oh right, so maybe I meant the yield return statement within C#. I'll admit that while I had heard of yield return before this week, and I had even read a little bit about it online, I didn't really understand what it was and what it was for. I don't know about you, but if I start to read about something and I can't get a feel for why I would use it, I care less about how to use it. So, in addition to showing you what yield return does and how to use it, I'll cover a useful scenario where you might want to use it.

What it Be

yield return <x> lets you return an enumerable type from a function call, 1 element at a time. If you're wondering how it lets you do so 1 at a time without losing it's place the next time you call, it's because .Net keeps track of your place so the next time you call the method within an iteration loop, it picks back up right after where you left off with the previous yield return statement. Here's a quick contrived example to help explain:

using System;
using System.Collections.Generic;

namespace BlogYield
{
    class Program
    {
        public static IEnumerable<int> GetRandoms(int count, int min, int max)
        {
            Random rnd = new Random();
            for (int index = 0; index < count; index++)
            {
                int random = rnd.Next(min, max + 1);
                yield return random;
            }
        }

        static void Main(string[] args)
        {
            foreach (int random in GetRandoms(10, 0, 100))
                Console.WriteLine(random);
            Console.ReadKey();
        }
    }
}



This is a full console application in C# that displays 10 random numbers in the range 0 to 100. The function GetRandoms returns an IEnumerable of type int, and proceeds to loop through count times producing random numbers. Notice that neat little bit of yield return w/in the loop? This means that the first time you execute the function, it will go through all the lines of the function in sequence; create the Random object, start the for loop, create the random number, return the first random number. Now the second time the function is called (within the loop in the Main function), the loop within GetRandoms continues on to the next iteration, a new random integer is set, and yield return is called with the next item. Nifty huh? I know there are better ways to accomplish this, a single for-loop being foremost in my mind, but this really does have some good uses. I promise! Let's look at one now that you know the mechanics.

Use Case: Merging Lists

Merging multiple lists that contain the same type can be a bit of a chore. In drops yield return to the rescue! Have a look at this example:

        public static IEnumerable<T> MergeLists<T>(params IEnumerable<T>[] lists)
        {
            foreach (var list in lists)
            {
                foreach (var item in list)
                    yield return item;
            }
        }

//...
//now we call it...
            var list1 = new List<int>();
            list1.Add(2);
            list1.Add(4);
            var list2 = new List<int>();
            list2.Add(0);
            list2.Add(100);
            foreach (var number in MergeLists<int>(list1, list2))
                Console.WriteLine(number);




As you can imagine, our output is 2, 4, 0, 100 (on separate lines). And, thanks to the magic of generic methods (I suppose I'll have to cover those in the blog at some point) and params, we can pass in any number of lists of any type, so long as they're all the same type and all the "lists" are enumerable. Pretty freakin sweet! Your original lists remain untouched, life is good.

[A quick note: I got this idea from here and just modified it a little to fit my own purposes. Thank you John K!]

What's Next?

Find some other uses for yield return and practice using it. I'm sure you'll think of something if you try. Or, another good exercise might be to try to recreate the above MergeLists method on your own. Even if you don't use a generic method or the params keyword, it will still help cement your understanding of yield return. Lastly, check the resources at the bottom of the article, especially the yield C# reference. They go into a bit more detail about how yield return works than I did, as I just glossed over it so I could get to a practical example quickly.

Resources

A Practical Use of "yield" Keyword in C#
yield (C# Reference)

Thursday, August 7, 2014

Website Optimization: Bundling and Minification

Intro

Website optimization is a goal of the highest order for web developers, and if it's not for you it should be. Why? Users don't like to wait. If a user waits more than a few seconds for a website, chances are good they'll go to a different website. You don't want that to happen to your websites do you? I'll assume not. If you don't like users then I suppose you do want this to happen, but I can't please everyone. Hey, just ignore the advice if that's you!

There are quite a plethora of ways to optimize websites. The server side code could be slow, the database behind it (if there is one) could be slow, internet connections can be problematic, javascript on your pages can be pokey, and you could just be forcing users to download too much stuff when they hit your site. This article concerns just a portion of the last item there, too much crap to download. Lots of things can cause your site to have a bloated download size or too many files to download; too many images, large images, uncompressed static files, server-side controls that render bloated html content to the client, too many and/or too large scripts and css files and more. Once again, this last item is what we're dealing with.

I hope you have a good sense from the above section that there can be quite a number of reasons for a slow site. Keep in mind we're covering just one of them here! If you're developing websites, I strongly encourage you to do some more research on teh interwebs to see what all else you can do to speed up your websites.

What is Bundling?

Bundling is pretty much what it sounds like; you bundle things together. In this case, I'm talking about bundling together javascript files and css files so that there are fewer hits to your server. Put on your pretending cap for a moment and picture a world where your website has just a single .js file. A user who visits your site will only download that 1 js file, so you've cut down on their outbound connections and your inbound connections. FTW! Now picture in yer noggin what that js file would look like if you have anything larger than a basic site: it would be a jumbled mess and it would be extremely difficult to find anything. That there fill will be huge! This is where bundling comes in. ASP.Net bundling lets you, with server-side code, specify group(s) of javascript or css files to bundle together at runtime. This means that you can keep them files separated (thanks Offspring!) in the development environment so your site is better organized and your code easier to manage, but your users get served much fewer file(s) when they view your page.

What is Minification

Minification is a podunk form of compression. In the web world, it means you strip js and css files down to a bare minimum of text that still functions the same. Take for example this line of js:

var myVariable = 3;

It doesn't seem like much, but this line is 19 characters long. Compare it to this line:

var m=3;

This new line is 8 characters long, and means the same thing. The variable name is different but that's it. Now going back and making all your js look like this will probably get you punched by your co-workers. Instead, let ASP.Net handle it for you! You can keep your js code looking nice and pretty on the development side, while serving your users much more compressed-looking code that works exactly the same.


Code!

Let's see how to go about using the built-in bundling and minification in .Net. Fire up VS Express and create a new ASP.Net Web Application. Mine is named blogbundlemin.
 

Pick the MVC template and change authentication to "No Authentication":


After a few seconds you should now have yourself a basic website template. Expand the scripts folder that VS made for you in your website and create a few js files. It doesn't matter what you put in them, but here is what I ended up with (zz_1.js, zz_2.js and zz_3.js):

The contents are pretty slim too:

zz_1.js:
var myVariable1 = 1234;

zz_2.js:
var myVariable2 = "purple";

zz_3.js:
var myVariable3 = "something or other";


Now open up the App_Start folder. In there is a special file that ASP.Net has already generated for you called BundleConfig.cs. Open up that file. You'll see that there's already a method in this class called RegisterBundles(), and there's some code in there already that is adding bundles. Go ahead and drop some code in there at the top of the method:

            bundles.Add(new ScriptBundle("~/bundles/local").Include(
                "~/Scripts/zz_*"));


This tells .Net to create a bundled named "~/bundles/local", and include in this bundle all the files named "~/Scripts/zz_*".

Great! Now we have a cool bundle, but how do we use it in one of the pages of our site? Open up Views/Shared/_Layout.cshtml. For those not familiar with MVC, this is like a master page from the world of web forms. Most if not all pages in the site will use this _Layout page to use a common layout and theme throughout the site. Towards the bottom of the file you can see a couple of lines that look like @Scripts.Render; add one for your own bundle. Here's what your code should look like:

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/local")
    @RenderSection("scripts", required: false)


Now run the project in Internet Explorer. Once the site finished loading, hit F12 to bring up developer tools. Now click on the weird little "network" icon on the left then click the Play button.


Now hit Ctrl-F5 to force IE to refresh all its local content for this page, then click the stop button. Your developer tools should look like this:



You can see your lovely bundle in there! If you double-click this line then click the "Response body" link you'll see what's in the bundle:


Yes that's right ladies and germs, .Net has both minified your content (it put all 3 variable declarations on one line, got rid of the trailing semicolon, and removed unnecessary whitespace)  as well as bundling all 3 files together. Nifty!

What's Next?

You can bundle css files too. It's just as easy as bundling js files. Give it a whirl!

Can you figure out how to turn on and off bundling? Hint: there are at least 2 good ways to do it.

You can also go super-bold and explore other ways to optimize websites. Heck, just play around with the IE developer tools some more if you're bored, they're fun.

Resources

ASP.Net Bundling and Minification

Thursday, July 31, 2014

Configure TFS (web version) for builds.

Yay! You've gotten your TFS (web version) installed and your code checked in.  Time to automate your builds so when you check in your code the phrase "works on your machine" will apply to "works on that web machine" as well :).

To configure TFS for builds:

Step 1: open up VS2013 Express for Web and open your project in question that's been checked in:

Step 2: go to the Team Explorer tab and click on Builds.
Step 3: Click on Builds, you should see the following screen:
Step 4: Click on New Build Definition:

Step 5: options! options! options!  Want to change your build name to something pertinent?  Go fer it!  For my purposes every time I check in some code I want it to build to verify what I wrote is compatible with what's checked in.
     a)  For this i'm clicking on the Trigger menu item and selecting Continuous Integration as the option for me.
     b)  Click on Source Settings:   If you wish to exclude certain paths in your code for building you can do that here. The active paths listed will work for my purposes.
     c)  Click on Build Defaults:  needing to build out your files to a particular location?  Here's where you can do that for your project.  I don't require that for my project so I'm going with the top option.
Step 6:  I'm going to rename my build process so I click on General and rename my build definition name.  I'll use "Build On Check In" for a meaningful name for keeping up with my project management.  Now save the Build Definition.
Now you should see on the right within Team Explorer under All Build Definitions the name of your project, for my purposes "Build On Check In".  Right click on it and choose "Queue New Build".  You should see a screenshot like the following:
Step 7:  You should see a screen like the following screenshot.  For my project purposes all options listed will work well for my project.  If you need additional parameters for a more specialized build they can be entered on the Parameters tab.
Step 8:  click Queue when you're ready to send up your new build definition to the server.  Huzzah! You should now have a build definition.
     a)  Log into your *visualstudio.com website to verify for yourself, here's the one I'd just created:
     b)  Click on Build, you should see your new build option on the lower left hand side.

Time to verify the build works, aka I get to break code on purpose!  Compiled my code and received the error expected, lets see what happens when I check in knowingly bad source code:
When I go to the web tab with my visualstudio account info, error!
Huzzah!  Fix your code and check it back in.  You should see a successful build like:
Yay, configuration o' builds complete.





Friday, July 25, 2014

Install TFS Web Based Version + Check in some code!

TFS (Team Foundation Server) vs TFS (Team Foundation Service).  Micro$oft, WTH?  Naming conventions aside, you now have options for project management:  Server (you get the pleasure of hosting) or Service (to the cloud!)

I could come up with clever reasons to use TFS for home, or let Google (yeah the irony) come up with reasons: http://blogs.msdn.com/b/msgulfcommunity/archive/2011/01/25/10-reasons-to-deploy-team-foundation-server.aspx.  Or regale you of tales of 9+ hours trying to configure the desktop version of TFS for local usage: aka: Tidwell not approved!

TFS as Team Foundation Service:
Go to http://www.visualstudio.com/products/visual-studio-online-user-plans-vs to create a MS account if you don't have one already. 

to do so click on Create Account Now:
At this step you'll need to name your account.  For personal use i'm going with dtidwelltfs which will work out to dtidwelltfs.visualstudio.com

then you'll get to the main page to manage your projects within Team Foundation Service:
Time to create a new project!  I'll use the generic ChessBlog (a project Peter had used in the past for a different blog):
after clicking Create Project:
Huzzah!  Click Open with Visual Studio to connect to get to your source code for binding.  You'll get the typical Launch App popup:
I happen to have 2 versions of Visual Studio 2013 installed: VS2k13 for Desktop and VS2k13 for Web.  This project is web based, I'll open for Web.
  
Double Huzzah!

Microsoft requires you to be logged into your VS account, get ready for yet another popup:
And another huzzah for good measure.  Within VS2k13 for Web you should hopefully have a Team Explorer tab available to you like the following:
I've filled in my local path to my source code and click Map & Get.  You should see the following after doing so:
Yeah buddy!  Mapping complete, time to send your code to the cloud.  Hopefully Source Control Explorer is open, if not open it.  You should be able to add items in your folder via right clicking and selecting Add items to folder, then selecting/deselecting any coding items you want part of your TFS project.
After getting your code into the project, right click and choose Check In Pending Changes.  After selecting that you should see:
Success!  At this point you might be wondering: It's showing up in the explorer window but is it really there?  Go back to your TFS webpage and you should see something like the following:
Click on your project (BlogChess) and you should see:

That should cover the basics of installing TFServices.  Tune in next time when we configure TFServices for bulids/tests!