Just Released! – NuGet Package to List Attribute Based Routes

Hello People!

Just wanted to share some information on what I have been doing. Yesterday I released a NuGet package that could prove helpful if you have started using ASP.Net MVC 5′s attribute based routing. You can read about attribute based routing here. But on a high level, attribute based routing is a feature that enables you to decorate action method’s with the Route attribute that will specify the url pattern to be used for this action to be invoked.

The thing with this approach is that, once you have more than one or two controllers, it could prove really tedious for you to open every controller and see the routes used so far. This package helps you solve this. Once you install the package using NuGet with the UI or the package manager console, you get the ability to look at all the routes used in the project. Once this package is successfully added, you could visit http://localhost<port_no>/attribute-based-routes to look at a list of all available routes, as show below!

Sample screenshot

Here is a list of all the relevant links for more information!

Hope this package is helpful and do let me know your comments!

Share

Paging w/ Angular

Hello again!

I was looking for an implementation of paging using angular and encountered this. This post just shows how I extended this implementation to have some sort of filtering. Obviously, I am very much a beginner in angular, so do recommend if you think there is a better way of doing this! I am not going to do a whole lot of explaining here and more or less directly get in to code!

I have built upon this sample by changing it in to a user listing page and also by adding a search box. This is unlike the angular filter, since I just don’t want to filter just the items in the first page. For this I have used $watch on a new scope variable sText that is used for displaying the paged items, as shown below:

    $scope.$watch('sText', function () {
        if ($scope.sText.length == 0 || $scope.sText.length > 2) {
            $scope.makeUsers();
            $scope.updateResults();
        }
    });

In the above snippet, makeUsers is a function that just generates 1000 entries with random first & last names and the updateResults function deals with setting up the data only for a certain page along with the pager bar. sText is set as the model for a text box as shown below:

     <input ng-model="sText" class="form-control" style="width: 300px" placeholder="Search Term (atleast 3 chars)" />

Here is a plunker for the same! And, learning angular was the intention for this, so go easy on the performance stuff and w/ the correctness of the makeUsers function!

Happy coding!!!

Share

Express – Route requests from multiple files

If you have started using NodeJS/Express like myself, probably you have this question too! I have a whole lot of app.get, app.post in my app.js file and I don’t like this! Here is a section of my app.js file to give you some perspective!

var app = express();

app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/contact', routes.contact);

If you have a gazillion number of such entries, it’s better to seperate them out based on the purpose. To do this, you can do the following:

var express = require('express');
var router = express.Router();

router.get('/login', function(req, res) {
  res.render('login', { message: req.flash('message') });
});

From the above code listing, the Router function can be used to get a reference to the express router. Now just like app.get/app.post you can use the router variable to add more routes!

That’s not enough though! In order to wire them to the main application file (app.js), the following has to be done, assuming the above code listing is in a file called auth.js within the “routes” folder.

var routes = require('./routes/auth')(passport);
app.use('/', routes);

In case I am wrong somewhere, feel free to point it out! Happy coding!

Share

Getting started w/ Web Workers

Hello,

I am not even going to discuss as to how long it’s been since I blogged about anything, because, it’s been forever. But here I am with a new post! This is about html 5 web workers and I should agree that it’s quite exciting to use web workers! In this post I am going to show a pretty simple web worker that calculates how long a user was on a certain page. Let’s see how far I can get w/ this!

Initial requirements are simple: create a worker script file that displays how long (in seconds) you’ve spent in a page. To do this, I have a simple page as shown below (MVC 4 cshtml):

@{
    ViewBag.Title = "Web Workers";
}

<h2>Web Workers</h2>

<p>
    You've been in this page for <span id="result">0</span> seconds!!
</p>

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    var worker = new Worker('@Url.Content("~/Scripts/timer.js")');
    worker.onmessage = function(event) {
        $('#result').html(event.data);
    };
</script>

Line 13 in the above snippet initializes a new web worker asking it to run the timer.js file. Whenever the worker accomplishes something (spending 1 second in this case), it “posts” a message saying that it did! Here is the timer.js file in its entirety!

var secs = 0;
function timer() {
    setTimeout(function () {
        secs++;
        postMessage(secs);
        timer();
    }, 1000);
}

timer();

In the above script I setup a timer function which uses the setTimeout function to call itself after every second. Before calling itself, it “posts” a message to the parent which is listening for the onmessage event. As indicated in the first snipped, this data is retrieved and using jQuery the corresponding span is updated! Here is the output:

Okay! It works!! But let’s improvise now! The following changes to timer.js starts as seconds and then into minutes! To begin with lets update the html in line 8 to the following:

<p>
    You've been in this page for <span id="result">0 seconds</span>!!
</p>

Then the following update to timer.js takes care of minutes and seconds.

var secs = 0;
function timer() {
    setTimeout(function () {
        secs++;
        var msg = getTimeSpent(secs);
        postMessage(msg);
        timer();
    }, 1000);
}

function getTimeSpent(sec) {
    if (sec < 60) {
        return sec + " seconds";
    }

    var mins = Math.floor(sec / 60);
    var secs = sec % 60;
    return mins + " minutes " + secs + " seconds";
}

timer();

Here is how it would look now:

So, What's next? I could go on w/ hours, minutes & seconds and so on. But I am going to stop here for now! Hope you enjoyed this post!

Happy coding!

Share

Overriding the Private Method of a Ruby Class

It feels like forever since I ever posted anything, but, here I am with an interesting post on ruby! Consider the following class which has a private method called “say”.

class Client
   def print
      say
   end

   private
      def say
          "hello"
      end
end

c = Client.new
puts c.print

Let’s assume you are unit testing the Client class and you want to override the say. But, why would you want to override the said method? There are numerous reasons – for one, the say method could talk to a web service to get some data to be used by one of the public methods. For unit tests, it’s better to have some predictable data rather than have something that would change quite often, rendering the unit tests useless!

So, under the assumption that the data will always be available using a specific format we can override this private method as shown below:

class Client
    def self.print
       new.print
    end

    def print
       say
    end

    private
        def say
           "hello"
        end
end

c = Client.new
puts c.print

puts "=========="

k = Class.new(Client) do
    define_method(:say) do
        "hello from an overridden private method"
    end
end

puts k.print

puts "=========="

k_instance = k.new
puts k_instance.print

Since this is not an introduction to ruby classes :) , I am going to make this quick! Lines 21 to 25 are of prime interest. Ruby’s Class.new class method is used to create a new class by passing the class in question – Client. Then using the define_method method I pass in a method name :say and define what it’s supposed to do – in this case return a different string instead of the one defined in the Client class.

That’s it! You can also create an instance of the newly defined class as shown in line 31! Calling the print method would display the following:

hello
==========
hello from an overridden private method
==========
hello from an overridden private method

Line 1 displays what will be printed without any overrides. Line 3 displays what will be printed when the class method is called after the say method is overridden by Class.new returns a new class and line 5 displays the same as line 3, but this time with an instance created using the class returned, again by Class.new

Share

EditPlus: Search & Replace with RegEx

Hello people! It’s been so long since I posted anything here. So here you go! This is going to be a short and sweet post! One of my favorite text editor is EditPlus and this is a way by which you could do a search using a RegEx and also replace it by using RegEx! Here is the scenario. I have an XML file where there are some elements without the end tag. So I wanted to replace them at a single shot instead of doing it numerous times. Remember, this is a 50,000 line file, so you can imagine! Here is the text:

<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO">
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO">
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO">
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO">
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO">

The expected result is (self-closing):

<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO"/>
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO"/>
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO"/>
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO"/>
<SomeElement Code="C198440" StartDateTime="01-04-2014 08:02:00.000" EndDateTime="" Admin="PO"/>

You could use the following process in EditPlus to achieve this!

  • Open the “Replace” dialog by pressing Ctrl + H
  • Enter (<SomeElement)([a-zA-Z0-9 \"=\-\:\.]*)(>) in the “Find what” text box
  • Enter \1\2/> in the “Replace with” text box
  • Press the “Replace All” button! That’s it!!

Pretty cool, isn’t it! Made my life so much easier :) And of course, the regex in the find text box can be simplified, but for now it’s fine! Here is what’s happening… The text entered in “Find what” has 3 groups: first group finds a literal “<SomeElement”, second group matches anything that follows it and the third group matches a literal “>”! The text entered in “Replace with” means this: \1 represents the first matched group, used as it is. \2 is the second matched group, also used as it is. Finally a literal “/>” to get the desired XML! Hope you had fun learning something interesting about EditPlus!

Share

JsFiddle: Something that would be really useful!

To begin with, let me say I love jsfiddle! In case you are not aware of jsfiddle, its a site where you could quickly test out your javascript, instead of creating a page to do the same locally! I have hundreds of fiddles and my manager always asks me how much I cost them :) One feature I tend to use a number of times is the “External Resources” tab, where I add a number of other additional .js files from various CDN’s. cdnjs.com is my go to place for a number of scripts and I am not sure if such another place exists!

External Resources tab

Here is what I am thinking should be available:

If a jsfiddle user types in (say) cdnjs: underscorejs in the text box within “External Resources” and press the tab key, the cdn url for underscore.js will be automatically added to the list of external sources! How cool would that be?

I think if this is possible it would be really cool ( I know it is ;) )! What do you people think :) ?

Update: Found out about codepen.io, which kind of does this, hoping to see this in jsfiddle soon!

Happy coding!

Share

Ninject: Passing dynamic parameters to the constructor

Hello poeple!

Been a really long time since I posted anything. But, here you go! This is a very interesting snippet about passing dynamic arguments to constructor that will be injected to a controller (say), using ninject. When you register a dependency in ninject, you do the following:

kernel.Bind<IData>().To<Data>();

Whereas, if you also want to pass a parameter to the construction of Data, you would do the following:

kernel.Bind<IData>().To<Data>().WithConstructorArgument("collectionName", "SomeValue");

But what if the value for collectionName changes based on various conditions, like in my case? Obviously, there is a way! You can pass callbacks to the WithConstructorArgument method, as shown below:

    public static class NinjectWebCommon
    {
	    // -- Snip --

        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IData>().To<Data>().WithConstructorArgument("collectionName", GetConstructorArgFromSession);
        }

        private static object GetConstructorArgFromSession(IContext context)
        {
            var httpContext = context.Kernel.Get<HttpContextBase>();
            if (httpContext != null && httpContext.Session != null)
            {
                var arg = httpContext.Session["Collection_Prefix"];
                if (arg != null && !string.IsNullOrEmpty(arg.ToString()))
                {
                    return arg;
                }
            }
            return null;
        }
    }

In the above snippet, WithConstructorArgument method, apart from the parameter name to be passed to the constructor for Data also takes in a callback. This callback uses the instance of IContext provided to get an instance of the HttpContextBase using which you could get the Session property as shown above. After getting the http context, it is now straight forward to access the Session and get the value I am looking for. This is now passed to the constructor of the Data class, when an instance is created by ninject!

That’s all for this post and hope you learnt something new about ninject, just like me! If at all I have more findings regarding this, I will update the article!

Happy coding!

Share

Announcing Db-Status-Provider NuGet Package – My first!

Hello People,

This is not a blog post per se, but just an announcement! I released my first nuget package yesterday! I have named it DbStatusProvider and as the name implies this package can be used to keep track of the status of your application’s database. I got the idea for this project from my open source project sBlog.Net!

To install this package launch the nuget package manager and enter the following command:

PM> Install-Package DbStatusProvider

Here is the github project page for this package. This page contains complete instructions on how to use this package. This is the package’s information page in the nuget site!

Hope you like this package and do let me know your questions/comments in github or here! Have fun!

Share

Fun With Generics 2: Comparables, Comparers, Sorted Sets

Hello People!

Yet another post in the fun with generics series. I am just trying to refresh stuff I already know and stuff I may have forgotten, also in the process also getting to know new stuff! In this post I am experimenting with IComparer<T>, IComparable<T> and SortedSet<T>. Before I get to the fun part, let me briefly explain the 2 interfaces I am going to use:

IComparable<T> is an interface that an object can implement in order to compare itself against another instance of the same type and return whether one object is “smaller” (-1) than the other, or “equal” (0) or is “greater” (1) to the other. Whereas, IComparer<T> is an interface thats expects us to implement a method that can compare 2 instances and return the same result as before. Native types like int already provides a CompareTo method and I am going to leverage this for the examples in this post!

To begin with, here is a class called User that implements the IComparable<T> interface.

    public class User : IComparable<User>
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string EmailAddress { get; set; }

        public int CompareTo(User other)
        {
            if (other == null)
                throw new Exception("Cannot compare with a null object");

            return UserId.CompareTo(other.UserId);
        }
    }

Notice how the Compare method uses int.CompareTo to see whether an instance is “smaller”, “equal” or “greater”! Now let me show how I could utilize the IComparer<T> interface. In this case, I am creating a UserComparer that can be used to sort a List<User> instance.

    public class UserComparer : IComparer<User>
    {
        public int Compare(User x, User y)
        {
            if (x == null || y == null)
                throw new Exception("Cannot compare null instances");

            return x.UserId.CompareTo(y.UserId);
        }
    }

Now let me put this UserComparer to use. Consider the following:

        public static void Main(string[] args)
        {
            var users = GetUsers();
            users.ForEach(u => Console.WriteLine(u.UserId + " : " + u.UserName));

            Console.WriteLine("--------------");

            users.Sort(new UserComparer());
            users.ForEach(u => Console.WriteLine(u.UserId + " : " + u.UserName));

            // -- Snip --
        }

        static List<User> GetUsers()
        {
            return new List<User>
                       {
                           new User{ UserId = 11, UserName = "testuser1", EmailAddress = "testuser1@mail.com"},
                           new User{ UserId = 62, UserName = "testuser2", EmailAddress = "testuser2@mail.com"},
                           new User{ UserId = 13, UserName = "testuser3", EmailAddress = "testuser3@mail.com"},
                           new User{ UserId = 42, UserName = "testuser4", EmailAddress = "testuser4@mail.com"},
                           new User{ UserId = 55, UserName = "testuser5", EmailAddress = "testuser5@mail.com"}
                       };
        }

Here is the output for this run:

11 : testuser1
62 : testuser2
13 : testuser3
42 : testuser4
55 : testuser5
--------------
11 : testuser1
13 : testuser3
42 : testuser4
55 : testuser5
62 : testuser2

If you notice in line 8, I have passed an instance of UserComparer, so that the framework can use the UserComparer.Compare method to find if an instance is “smaller”, “equal” or “greater” to another instance and sort it based on that! Okay, but where the implementation of IComparable<User> in the User class come in to the picture? When I use a SortedSet<T>! In the case of a SortedSet<T>, I don’t have to call the Sort method with the UserComparer explicitly! Here is the listing for the same:

        public static void Main(string[] args)
        {
            var users = GetUsers();

	    // -- Snip --

            var sortedSet = new SortedSet<User>();
            users.ForEach(u => sortedSet.Add(u));
            sortedSet.ToList().ForEach(s => Console.WriteLine(s.UserId + " : " + s.UserName));
        }

If you notice in the above snippet, when User objects are added to the SortedList, they are already stored as per the sort order! So there is no need to make an explicit call to Sort! SortedSet<User> uses the User.CompareTo method to sort the instance and put them in the correct position as and when they are added! One of my pet peeve would be why they didn't name this class SortedList as opposed to SortedSet! Of course, there is another class called SortedList but for a different purpose altogether (msdn)!

You can download a sample file here!

Hope you had fun! That's all for now!!

Share