Prabir's Blog

open source geek and lover of all tech  

Recently I had released the first public version of the nuget button. It was a great start but still lacked some cool features that I wanted. So with this v0.2 release, it will address some of those lacking features.

Make sure to change the javascript url to the new version.

<script type="text/javascript">
    (function () {
        var nb = document.createElement('script'); nb.type = 'text/javascript'; nb.async = true;
        nb.src = 'http://s.prabir.me/nuget-button/0.2.1/nuget-button.min.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(nb, s);
    })();
</script>

Clickable links

Many of us have been pleased by the ease nuget has brought to the .net world on package management. But for me, there has also been one more + nuget has brought into my life. It has also allowed me to easily find the source code of the project. (Next time you install a package, make sure to check out its source code too. You are gonna a learn a lot just looking at others source code).

image

Starting from v0.2, you can now click the package name and go the the official nuget page of the package. Here is the sample effect when you hover over the package name.

Install-Package SimpleJson

<pre class="nuget-button">Install-Package Facebook</pre>

The code is exactly same as in v0.1 thus maintaining backward compatibility. The nuget button is smart enough and generates a link to http://nuget.org/List/Packages/SimpleJson

But what if I don’t host my packages in nuget.org?

The easiest workaround would be to disable the link feature in nuget button.

<pre class="nuget-button" data-nugetbutton-link="false">Install-Package SimpleJson</pre>

Add a new data- property called data-nugetbutton-link and set it to false.

Great! But I want custom links.

No problem. That’s been thought of already.

A bit of history first(As of this writing nuget doesn’t yet support pre-releases (beta release) packages, though it has been planned for v1.6.) We release Facebook C# SDK quite often, but to maintain the stability of the code, we mark some of the release as beta release and don’t publish it in nuget.org as there are lots of live facebook apps using it. But due to the popularity of nuget, the first question we get on every release is how do I get this pre-release package from nuget? My answer was, it’s not in nuget as its not a stable release and we don’t want users to just start pulling beta releases and using it in their production and nuget doesn’t support pre-release packages. Overtime I was tired of answering the same reason again and again and I simply set up a pulic nuget server that others could add. But the problem is you get different url which is not hosted in nuget.org. So here is how to get over that problem.

<pre data-nugetbutton-link="http://nuget.prabir.me"  class="nuget-button">Install-Package Facebook</pre>

Notice that it is the same data-nugetbutton-link that we used before, but this time its set to a url instead of false. This allows you to point to your own custom nuget servers or a github page.

Custom size

This one is especially for those who writes blog like me. You would most likely want to match the theme of nuget button with your own blog theme. I don’t have plans to allow customizable color - black nuget button is supposed to be a brand ;), but you can definitely set the size of the nuget button using em value for font-size – pure html again.

<div style="float:left; font-size:0.5em"><pre class="nuget-button">Install-Package FluentHttp.Core</pre></div><div style="clear: left"></div>

The above code not only sets the size, but also takes only the required length for your package.

Here are some live example of the nuget button v0.2.

Full width (default)

Install-Package FluentHttp.Core

Auto width

Install-Package FluentHttp.Core
 

Auto width with smaller size

Install-Package FluentHttp.Core
 

For more live samples and new features make sure to check out http://s.prabir.me/nuget-button/0.2.1/nuget-button.htm

When I was going through Scott Hansleman’s blog posts, I had realized that he makes extensive use the the nuget style Install-Package buttons like the one shown below.

image

I was a bit jealous and wanted to see for myself if I could have those nuget install-package buttons too. As of now I have around 18 unique nuget packages (most popular ones being Facebook C# SDK, SimpleJson and FluentHttp) hosted at nuget.org so I thought it was lame to do a print screen, a bit of editing and then pasting the image. So, I needed to come up with a new solution, a replacement to using images.

In the mean time, I seriously needed to make more people aware of nuget’s awesomeness. In Facebook C# SDK, we ship two files from the codeplex download tab – binary/assembly files (also available through nuget) and source code. But at the end of the day, the number of assembly files downloaded from codeplex always seems to be the higher than that of the source code and almost double than from nuget. (most probably VS2008 users.). So I decided that I ‘m going to start putting the Install-Package button in my blog on almost every blog post I do about Facebook C# SDK.

So my answer to both the above problems – a Javascript based solution that works with minimal amount of code the way you want too in any of your existing sites, just like Facebook’s like button, Google’s +1 button or Github’s “Fork me on Github” ribbons.

Enough of the history crap, show me the code

First of all you will need to add the following code just before the end of the body tag. nuget-button.min.js is download asynchronously using the below code.

<script type="text/javascript">
    (function () {
        var nb = document.createElement('script'); nb.type = 'text/javascript'; nb.async = true;
        nb.src = 'http://s.prabir.me/nuget-button/0.1/nuget-button.min.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(nb, s);
    })();
</script>

Then use “pre” tag and assign a class called “nuget-button” to it where ever you want the nuget Install-Package button to be rendered.

<pre class="nuget-button">Install-Package Facebook</pre>

You can see a live working example at http://s.prabir.me/nuget-button/0.1/nuget-button.htm

The best part about nuget-button is that you could now copy/paste the code and execute directly in the nuget package manager. No worries about Javascript being disabled coz pre is a standard html tag and will still get rendered.

Some of you may be wondering why its named “nuget-button” when there is nothing to do with behavior of a button like clicking. For vNEXT I plan to add anchor tag for the name of the project, so when you click, it will open http://nuget.org/List/Packages/Facebook. It is just the beginning and since all the code for nuget-button is open source, make sure to fork it or send suggestions/patches at https://github.com/prabirshrestha/nuget-button.

Here is a live sample showing nuget-button working in my blog.

Install-Package Facebook

And before I forget, nuget button is super lightweight (less than 3kb) with no dependencies on any javascript framework and yes it work on IE6 too.

This is a follow up article on Organizing Javascript codes from a C# perspective using namespaces. If you haven’t read the previous article I strongly recommend it do so.

In this article I will discuss on how to structure the Javascript codes using Object Oriented Programming (OOP) concepts which you are highly familiar with in C#.

Lets start first by writing a C# class. (These naming conventions are not of C# standards and never try to write one in this way. Its been written only as an example to map with Javascript codes for convenience.)

namespace A.B
{
    using System;

    public class Test
    {
        public Test()
        {
            Console.WriteLine("constructor");
        }

        private string private_property = "private_property (field)";
        private void private_method()
        {
            Console.WriteLine("private method");
        }

        public string public_property = "public_property (field)";
        public void public_method()
        {
            Console.WriteLine("public_method");
        }

        public static string static_property = "public static property";
        public static void static_method()
        {
            Console.WriteLine("public static_method");
        }
    }
}

First of all we need to wrap code in the namespace block A.B.

if (!A) var A = {};
if (!A.B) A.B = {}; // careful here, var is not present here, only in the first one

Please refer to the my tutorial on  Organizing Javascript codes from a C# perspective using namespaces which describes in more details.

Then we create the class same as in C#. 

A.B.Test = function () {
};

This looks similar to a function. Well it is a function. So in order to instantiate the object of this class you call the function.

var t = A.B.Test();

Now that we are able to create the class, lets create public and private properties and methods.

A.B.Test = function () {
    // ctor
    alert('constructor');

    var _private_var = 'private var';

    private_method = function () {
        alert('private method');
    }

    alert('or can even write ctor anywhere');

    return {
        public_property: "public_property",

        public_method: function () {
            alert("public_method");
        }
    };
};
A.B.Test.public_static_property = 'public static property';
A.B.Test.public_static_method = function () {
    alert('public static method');
};

And here’s are the tests. 

var t = A.B.Test();
alert(t.public_property);
t.public_method();
if (typeof (t._private_var) != 'undefined')
    alert('can access private var, test failed');
else
    alert('cannot access private var, test passed');
try {
    t.private_method();
    alert('can access private method, test failed');
} catch (e) {
    alert('cannot access private method, test passed');
}
alert(A.B.Test.public_static_property);
A.B.Test.public_static_method();

So next time you write Javascript, try implementing these OOP concepts. It will really help you out in organizing your codes.

jsoop.zip (727.00 bytes)

Recently I had been writing a lot of Javascript codes and was very unhappy about the code organization and the architect of my source code. Having lots of functions all jumbled up with UI logic and business logic was getting me no where. I decided to stop all my coding and search for a better way to organize my javascript codes.

I saw some solutions by using 3rd party javascript libraries such as YUI and Microsoft Ajax Client library to name a few. It did provide a great way to solve my problems, but what if I wanted to distribute my Javascript codes as an SDK for other devs to build upon (like the Facebook Javascript SDK). They would have to reference it, and even learn how to use YUI or MSAjax libraries. I wanted simpler solution less bulky solution.

Then after searching around, I found out a lot of ways to do it. I have broken up this tutorial into various parts which I will be posting soon. The first one is using the concepts of namespaces as you would do in C#.

Lets say I want to create a SDK called MySDK. I would want to have it under the company’s name like CompanyName.MySDK.

In C# you would do it as …

namespace Prabir.Shrestha
{
   public MyClass
   {
   }
}

 Equivalent code for Javascript would be as follows:

var Prabir = Prabir || {};
Prabir.Shrestha = Prabir.Shrestha || {};
Prabir.Shrestha.MyClass = function(){
};

Lets examine the first line in details. var Prabir tells us to create a Javascript variable called Prabir. The right hand side tells to assign Prabir (rhs) to Prabir (lhs) and if Prabir(rhs) is not defined create a new object and assign it to Prabir (lhs) – counfusing isn’t it. Well just remember it as a sort of C# null coalescing operator (??). The next line does the similar thing. It is very important to check if the object already exists as you might have another SDK under the same namespace, and if you create a new one it would override the old variable, so only the last referenced SDK would be available.

Note: Put var only in the root namespace lines and not in others.

So now you could create public functions using the following code.

var Prabir = Prabir || {};
Prabir.Shrestha = Prabir.Shrestha || {};
Prabir.Shrestha.MySDK = function(){
     return {
          public_method : function() {
               alert('I am a public method');
          }
     };
};

To call the public method you would need to create an instance of the object as you would do in C# and call the function.

var mySdk = new Prabir.Shrestha.MySDK();
mySdk.public_method();

Congrats. That’s the first way to organize your Javascript using namespaces as in C#.

To make it more easy, I actually landed up creating a new Javascript library to make managing namespace easier. You can find this library at http://github.com/prabirshrestha/js-namespace

/*!
 * js-namespace Javascript Library v1.0
 *
 * http://www.prabir.me
 * http://github.com/prabirshrestha/js-namespace
 *
 */
NS = {
	register: function(ns,container){
		var root = container || window;
		var nsParts = ns.split('.');
		var length = nsParts.length;
		for(var i = 0; i < length; ++i)
			root = root[nsParts[i]] = root[nsParts[i]] || {};
		return root;
	},
	exists: function(ns,container){
		var root = container || window;
		var nsParts = ns.split('.');
		var length = nsParts.length;
		for(var i = 0; i < length; ++i){
			if(!root[nsParts[i]])
				return false;
			root = root[nsParts[i]];
		}
		return true;
	}
};
// alias
NS.r = NS.register;
NS.e = NS.exists;

To create a namespace you would call the register method.

NS.register('Prabir.Shrestha');

and to check if the namespace exists call the exists function. Instead of using NS.register and NS.exists you could also use the shorthand NS.r and NS.e respectively.

The uncompressed file is 900 bytes and the minimized gziped file is around 368 bytes.

Next tutorial is about Object Oriented Programming in Javascript. So stay tuned.

js-namespace-samples.zip (1.92 kb)