Thursday, August 28, 2014

C# Tuple

Intro


What's a Tuple? In the world of .Net, it's a somewhat-generic structure that can hold a number of elements that you define upon declaration/creation. Yeah that's a helpful description, I know. I aim to please! I really can't think of much else to say about these things that will clear up the fog of war, so let's just see a quick sample:

        private Tuple<int, string, int> DoStuffWithNumbers(int num1, int num2)
        {
            int product = num1 * num2;
            string description = "i've done crazy things with numbers";
            int modulus = num1 % num2;
            return new Tuple<int, string, int>(product, description, modulus);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var thing = DoStuffWithNumbers(84, 9);
            Response.Write(thing.Item1 + "::" + thing.Item2 + "::" + thing.Item3);
        }



The above method DoStuffWithNumbers needs to return 3 values. Sure, we could do that with 3 out parameters, but that's a pain! I could also declare a class, maybe call it StuffWithNumbersResult, and give it 3 properties; but yeah, I'm still just as lazy as I was last week so I don't want to create a new class just for that. In comes the Tuple. The method just returns an object (a Tuple) with 3 properties; an int, a string, and another int. The Page_Load method calls DoStuffWithNumbers in the first line, then in the 2nd line it accesses the Tuple via properties Item1, Item2, and Item3. It's not the prettiest way to accomplish things, but it's at least simple. And hey, you still get strongly-typed variables (the method-scope variable "thing" is strongly typed as Tuple<int, string, int>), and you have less coding than you might otherwise.


Why, and Why Not?

The why should be pretty easy to figure out from the above sample. It saves you some coding and by extension a little bit of program complexity. The why not should also be easy to discover. What does thing.Item1 mean? You have to dig into the code to find out, rather than having something more meaningful. For example, if you had declared a StuffWithNumbers class with properties Product, Description, and Modulus, that's a lot more readable than thing.Item1-3. Thus, your code is probably just a wee bit harder to maintain, especially if it's not you doing the maintenance.

Anything Else?

Why of course there's more to it! There's a slightly easier syntax for creating your Tuple which I'm about to show you:

return Tuple.Create(product, description, modulus);

This here line of code can be used in place of the last line from DoStuffWithNumbers() from up above. It's just a slightly simpler way of creating your Tuple without having to use the angle-bracket syntax of generics.

That's about it! Happy Tupling...

What's Next?

Nothing else to say really. Check out the link below though for a few nitpicky details about Tuples. I didn't cover everything, but I covered the fun stuff.

And hey, with great coding power comes great responsibility to future devs who have to maintain your work. Translation: Use Tuples sparingly. If used in excess, they can make your code pretty tough to follow.

Resources
Tuple Class (System)

Wednesday, August 27, 2014

jquery advanced: roll your own plugin

PREFACE:

So we've hidden some text, changed the size/color of other text at the click of a button, and made a pictorial slideshow.  Now what?  Our second adventure in jquery required the usage of some extra plugins, this adventure we'll learn how to write our own jquery plugins to use!

CODING CONCEPT:

Let's go for some more cheese:  reversing the text of list items we have displayed to the user.  It being football season, let's pick on four different teams from the NFL!

ACTUAL CODE:


The plugin code! Please note I've named the file jquery.reverseme.js

The html code used to call the .js file above:

Our final end product when rendered in a browser:


SOURCE:

http://www.sitepoint.com/how-to-develop-a-jquery-plugin/

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