Code Coverage with Chutzpah

There was a question in stackoverflow on how to do code coverage in JS with Chutzpah. This is just a short blog on how I did it.

1. First download Chutzpah from codeplex.

Chutzpah

 

2. Now extract it and do the following.

– I extracted chutzpah in the below path.

ChutzpahLocation

– And the location of my js files is here.

UnitTestsLocation

– So, below is how I do code coverage using the chutzpah’s console.

doing_the_console

– And yes of course the result.

resultOfChutzpahCodeCoverage

Nice isn’t it!!!

I will be bloggin everyday from .net,java,python,LAMP,MEAN and all other important topics. This is my way of challenging my self and not become stagnant with just 1 programming/scripting language.

Please also check my site www.francorobles.com if you want to know more about me.

 

Advertisements

CRUD with KnockoutJS, ASP.NET MVC and NHibernate

A friend of mine asked me to teach him a simple CRUD with KnockoutJS using NHibernate because he is already used to EntityFramework. Well, I told him to buy me a grande coffee first at starbucks, and he did. So in order for him and for the others to get to see it in action here is how its done.

First of all, for those of you who doesn’t know what is NHibernate, it is an Or Mapper like EntityFramework. Here is a comparison just in case you might want to know the difference between the 2.

Best comparison so far.

http://www.devbridge.com/articles/entity-framework-6-vs-nhibernate-4/

Now let’s work.

1. First, let’s download the latest release of NHibernate from Nuget.

NHibernate

3. Now since we want xml less mapping, lets get Fluentnhibernate from nuget. During this post, the latest stable version is 1.4.0.

– From your Package Manager Console. type the following “Install-Package FluentNHibernate -Version 1.4.0”

4. After successfully installing FluentNHibernate, your datastore library should now look like below.

FluentNhibernate

5. Now let’s set up a helper for NHibernate which will allow us to connect to the database.
– Okay, basically what the below does is create a SessionFactory.
– Connect to a local data soure from my App_Data directory.

public class CustomerContext
    {
        private static ISessionFactory sessionFactory;
        private static ISession session;
        private static ISessionFactory SessionFactory {
            get {
                if (sessionFactory == null)
                    SetSessionFactory();

                return sessionFactory;
            }
        }
        private static void SetSessionFactory() {
            sessionFactory = Fluently.Configure().Database(MsSqlConfiguration.MsSql2012.ConnectionString(@"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|Customers.mdf;integrated security=true;"))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf()<Customer>())
                .ExposeConfiguration(c => new SchemaExport(c))
                .BuildSessionFactory();
        }

        public static ISession OpenSession() {
            return SessionFactory.OpenSession();
        }
    }

6. Let’s create a mapping to our Customers table in the database to our Customer entity.

public class CustomerMap : ClassMap<Customer>
    {
        public CustomerMap()
        {
            Id(c => c.Id);
            Map(c => c.FirstName);
            Map(c => c.LastName);
            Map(c => c.Address);
            Map(c => c.Phone);
            Map(c => c.CreditLimit);
            Map(c => c.CustomerSince);
            Table("dbo.Customers");
        }
    }

7.  Now, below is self explanatory, I created the CRUD methods which inherited from an Interface.

public class CustomerViewModel : ICustomerProvider
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public decimal CreditLimit { get; set; }
        public DateTime CustomerSince { get; set; }

        #region NHibernate
        public List<CustomerViewModel> GetCustomers()
        {
            using (var context = CustomerContext.OpenSession())
            {
                return context.Query<Customer>().Select(c => new CustomerViewModel()
                {
                    Id = c.Id,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    Address = c.Address,
                    Phone = c.Phone,
                    CreditLimit = c.CreditLimit,
                    CustomerSince = c.CustomerSince
                }).ToList();
            }
        }

        public bool AddCustomer(CustomerViewModel customer)
        {
            bool saved = false;
            try
            {
                using (var context = CustomerContext.OpenSession())
                {
                    using (var transaction = context.BeginTransaction())
                    {
                        context.Save(new Customer()
                        {
                            FirstName = customer.FirstName,
                            LastName = customer.LastName,
                            Address = customer.Address,
                            Phone = customer.Phone,
                            CreditLimit = customer.CreditLimit,
                            CustomerSince = customer.CustomerSince
                        });
                        transaction.Commit();
                    }
                }
                saved = true;
            }
            catch (Exception ex)
            {
                //Log here
                throw ex;   
            }
            return saved;
        }
        public CustomerViewModel GetCustomer(int customerId)
        {
            using (var context = CustomerContext.OpenSession())
            {
                return context.Query<Customer>().Where(c => c.Id == customerId).Select(c => new CustomerViewModel()
                {
                    Id = c.Id,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    Address = c.Address,
                    Phone = c.Phone,
                    CreditLimit = c.CreditLimit,
                    CustomerSince = c.CustomerSince
                }).FirstOrDefault();
            }
        }

        public bool UpdateCustomer(CustomerViewModel customer)
        {
            bool saved = false;
            try
            {
                using (var context = CustomerContext.OpenSession())
                {
                    using (var transaction = context.BeginTransaction())
                    {
                        var existingCustomer = context.Query<Customer>().Where(c => c.Id == customer.Id).FirstOrDefault();
                        existingCustomer.FirstName = customer.FirstName;
                        existingCustomer.LastName = customer.LastName;
                        existingCustomer.Address = customer.Address;
                        existingCustomer.Phone = customer.Phone;
                        existingCustomer.CreditLimit = customer.CreditLimit;
                        existingCustomer.CustomerSince = customer.CustomerSince;
                        context.SaveOrUpdate(existingCustomer);
                        transaction.Commit();
                    }
                }
                saved = true;
            }
            catch (Exception ex)
            {
                //Log here
                throw ex;
            }
            return saved;
        }

        public void DeleteCustomer(int customerId)
        {
            using (var context = CustomerContext.OpenSession())
            {
                using (var transaction = context.BeginTransaction())
                {
                    var existingCustomer = context.Query<Customer>().Where(c => c.Id == customerId).FirstOrDefault();
                    context.Delete(existingCustomer);
                    transaction.Commit();
                }
            }
        }
        #endregion

    }

8. And in our controller. Below are the controller functions.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DeleteCustomer(int customerId) {
            ICustomerProvider provider = new CustomerViewModel();
            provider.DeleteCustomer(customerId);
            return PartialView("CustomerList", provider.GetCustomers());
        }

        public ActionResult CustomerList() {
            ICustomerProvider provider = new CustomerViewModel();
            return PartialView(provider.GetCustomers());
        }

        public ActionResult SaveCustomer([Bind(Exclude="Id")]CustomerViewModel customer) {
            ICustomerProvider provider = new CustomerViewModel();
            bool saved = provider.AddCustomer(customer);
            return Json(new { saved = saved }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult UpdateCustomer([Bind]CustomerViewModel customer)
        {
            ICustomerProvider provider = new CustomerViewModel();
            bool saved = provider.UpdateCustomer(customer);
            return Json(new { saved = saved }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetCustomer(int customerId)
        {
            ICustomerProvider provider = new CustomerViewModel();
            return Json(new { customer = provider.GetCustomer(customerId) }, JsonRequestBehavior.AllowGet);
        }
}

 

9. As you can see below, I have a very simple form. Don’t worry the source code is in github for you to look the entire running source.

– What I would like to highlight here is the data-bind attribute. The values and click events are bound to our js viewmodel.

@{
    Layout = "/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Customers";
}
<div class="row container">
    <h2>Customer List</h2>
    <br />
</div>

<div data-bind="visible: formVisible" class="container col-md-12">
    <div class="row margin-bottom-10">
        @ViewBag.Message
    </div>
    <div class="row">
        <div class="column">
            First Name
        </div>
        <div class="column">
            <input type="text" id="firstName" name="firstName" class="form-control" data-bind="value: firstName" />
        </div>
    </div>
    <div class="row">
        <div class="column">
            Last Name
        </div>
        <div class="column">
            <input type="text" id="lastName" name="lastName" class="form-control" data-bind="value: lastName" />
        </div>
    </div>
    <div class="row">
        <div class="column">
            Address
        </div>
        <div class="column">
            <input type="text" id="address" name="address" class="form-control" data-bind="value: address" />
        </div>
    </div>
    <div class="row">
        <div class="column">
            Phone
        </div>
        <div class="column">
            <input type="text" id="phone" name="phone" class="form-control" data-bind="value: phone" />
        </div>
    </div>
    <div class="row">
        <div class="column">
            Credit Limit
        </div>
        <div class="column">
            <input type="text" id="creditLimit" name="creditLimit" class="form-control" data-bind="value: creditLimit" />
        </div>
    </div>
    <div class="row">
        <div class="column">
            Customer Since
        </div>
        <div class="column">
            <input type="text" id="customerSince" name="customerSince" class="form-control" data-bind="value: customerSince" placeholder="yyyy-MM-dd" />
        </div>
    </div>
    <div class="row">
        <div class="column">
            &nbsp;
        </div>
        <div class="column">
            <input type="button" class="btn-info" value="Submit" data-bind="click: function() { submitForm() }" />
            <input type="button" class="btn-danger" value="Cancel" data-bind="click: hideForm" />
        </div>
    </div>
</div>
<br />
<div class="container col-md-12 margin-bottom-10 align-content-right">
    <br />
    <input type="button" class="btn-info" value="Add New Customer" data-bind="click: $root.showForm" /><br /><br />
</div>
<div id="customerlist" class="container col-md-12">
    @Html.Action("CustomerList", "Home")
</div>
@section scripts {
    <script src="~/Scripts/PageScripts/customers.js"></script>
}

 

10. And finally, our knockout view model.

function AppViewModel() {
    var self = this;
    //Since i hide and show the form to prevent turnaround from the server I created an observable property which is bound to the visibility of the form element.
    self.formVisible = ko.observable(false);

    //Here I instantiated all the properties bound to the input elements.
    self.firstName = ko.observable('');
    self.lastName = ko.observable('');
    self.address = ko.observable('');
    self.phone = ko.observable('');
    self.creditLimit = ko.observable('');
    self.customerSince = ko.observable('');
    self.customerId = ko.observable('');

    //Another property to toggle between add new and edit functionality.
    self.isEdit = ko.observable(false);

    //A function for showing the form which is called from the UI.
    self.showForm = function () {
        self.formVisible(true);
        self.resetForm();
        self.isEdit(false);
    };

    //A function for hiding the form which is called from the UI.
    self.hideForm = function () {
        self.formVisible(false);
    };

    //A function for resetting the values of the form.
    self.resetForm = function () {
        self.firstName('');
        self.lastName('');
        self.address('');
        self.phone('');
        self.creditLimit('');
        self.customerSince('');
    };

    //A function for getting the correct date.
    self.getCorrectDate = function (rawDate) {
        var dateStringValue = rawDate;
        var value = new Date (parseInt(dateStringValue.replace(/(^.*\()|([+-].*$)/g, '')));
        var correctDate = value.getFullYear() + '-' + value.getMonth() + 1 + "-" + value.getDate();
        return correctDate;
    }

    //A function which updates a customer
    self.editCustomer = function (id) {
        $.ajax({
            url: '/Home/GetCustomer',
            data: {
                customerId: id
            },
            success: function (data) {
                self.formVisible(true);
                self.isEdit(true);
                self.firstName(data.customer.FirstName);
                self.lastName(data.customer.LastName);
                self.address(data.customer.Address);
                self.phone(data.customer.Phone);
                self.creditLimit(data.customer.CreditLimit);
                self.customerSince(self.getCorrectDate(data.customer.CustomerSince));
                self.customerId(data.customer.Id);
            }
        });
    };

    //A function for deleting a customer
    self.deleteCustomer = function (id) {
        $.ajax({
            url: '/Home/DeleteCustomer',
            data: {
                customerId : id
            },
            success: function (data) {
                $("#customerlist").html(data);
            }
        });
    }

    //A function for loading the customer view via ajax.
    self.loadCustomers = function () {
        $.ajax({
            url: '/Home/CustomerList',
            success: function (data) {
                $("#customerlist").html(data);
            }
        });
    };

    //The function for updating and adding a customer.
    self.submitForm = function () {
        var url = '/Home/SaveCustomer';
        if (self.isEdit()) {
            url = '/Home/UpdateCustomer';
        } 
        $.ajax({
            url: url,
            data: {
                firstName: self.firstName(),
                lastName: self.lastName(),
                address: self.address(),
                phone: self.phone(),
                creditLimit: self.creditLimit(),
                customerSince: self.customerSince(),
                id: self.customerId()
            },
            success: function (data) {
                if (String(data.saved) == 'true') {
                    self.formVisible(false);
                    self.loadCustomers();
                }
            }
        });
    };
}

//Now here is the important part. Tell knockout to apply the necessary bindings between our dom elements and the above model.
ko.applyBindings(new AppViewModel());

 

And we are done. You now have a simple CRUD using NHibernate, FluentNHibernate, Knockout, and Bootstrap. The entire source is in github.

Get the entire source here https://github.com/francorobles/Blog/tree/master/CustomerSite.

Unit Testing JS with Jasmine and Chutzpah

Gone are the days where we will manually test our web sites specially if its using Javascript. Since the arrival of QUnit, Jasmine, and Mocha  the way we test the client side of our sites has changed. Now for this post I will be using Jasmine. Why Jasmine? Because, it support’s Ajax testing. I am not saying that you cannot test ajax results from the other 2 frameworks but Jasmine is just my favorite.

And if you want to integrate it with visual studio with a test runner, let’s use another open source tool

1. Okay first let’s add our test runner to visual studio.

– Go to Tools > Extensions and updates and search for Chutzpah

– Now you should see 2 results. The first one is the Test Adapter and the second is an addition to the context menu. Download them both.

Chutzpah

2. Lets get Jasmine using from Github.

– Go to your github command line and clone it from https://github.com/pivotal/jasmine.git. And add a reference to Jasmine into your solution.

gitclone

 

– Now that I have Jasmine, and with the help of Chutzpah. I can now create a simple test run in test explorer.

Testexplorer

 

Now, how about that? Easy isn’t it? As I said before, you can even test your ajax requests with Jasmine. The beautiful part is with the help of Chutzpah, I was able to load all these javascript test items into the test explorer. If you like my post, please go to my site as well www.francorobles.com.

 

IEnumerable VS IQueryable

Lately I have been doing some performance improvements in one of the modules of our web application in the office. I am writing this to share my observation between the 2 important subjects.

1. IEnumerable

– Exposes an enumerator, which supports a simple iteration over a non-generic collection.

2. IQueryable

– Provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified.

Okay let’s go to the real stuff. Lets say we have a collection from our EDMX. And we want to pick the top 100 last inserted records. So how do we do that?

1. IEnumerable

using (var context = new MyContext()) 
{
    IEnumerable<Employee> employees = context.Employees.OrderByDescending(e => e.EmployeeId);
    var latestEmployees = employees.Take(100);
}

1. IQueryable

using (var context = new MyContext()) 
{
    IQueryable<Employee> employees = context.Employees.OrderByDescending(e => e.EmployeeId);
    var latestEmployees = employees.Take(100);
}

Okay that was easy. Now let’s see how it is being interpreted by SQL Server.

1. Using IEnumerable – As you can see below it gets all the records without applying the top 100 filter which is really a bad idea if you have thousands of rows.

IEnumerable

 

2. Using IQueryable – Now with IQueryable, the query result is now different which is what we want. Apply the top 100 first before we execute the query.

IQueryable
As you can see from the above comparison, there is a very huge difference between the 2 when they are executed. I would suggest IEnumerable if you are dealing with in memory collections. If you want to deal with database collections I would suggest IQueryable.

 

I hope I had shared some helpful information to you regarding these topics which we use everyday and hopefully if you like my blog please also visit my site http://www.francorobles.com to know more about me.

How to avoid “Potential Dangerous Request.QueryString” in asp.net mvc

In some instances we might wan’t to allow html tags in our web application. But sad to say ASP.NET MVC blocks us from doing this. Chek out the below scenario. I want to add a comment and I want it italicized.

– Below is our form. When we submit this form it will result to?

ErrorOnPost

– Yes you are right, to an error. After submitting the form this is the result. By default MVC blocks potentially malicious scripts.

ErrorOnPost2

 

– But what if we want to allow valid htm tags such as the italics tag? What do we do then? One of the best ways I found is to block inputs containing <script> tags and allow those that are non script tags . So how do we do that?

Let’s modify our ActionResult a little bit by adding [ValidateInput(false)] attribute in our action.

[ValidateInput(false)]
public ActionResult AddComment(string comment)
{
     if (System.Text.RegularExpressions.Regex.IsMatch(comment, “<script>.*?</script>”)) {
          throw new HttpException(500, “Potantially malicious Request.QueryString detected.”);
     }
     else {
          ViewBag.Message = comment;
     }
     return View(“Index”);
}

As you notice from the above snippet I am checking if the input contains tags. If it does, I displayed the message that the input is not valid, otherwise, I displayed what they have typed in the message box.

– Once we run our app again and tried to input html tags appart from <script> tags, it run’s smoothly as shown below. Else we throw our own exception. disallowing script tags that might cause serious problems in our app.

PassedTag

And that is it. You are now allowing safe html tags in your web app.

Happy coding.

By the way the entire source is in github. https://github.com/francorobles/Blog/tree/master/HtmlInputsInMvc

Custom EntityFramework DbContext with VB.NET – Code first approach

First of all, let me say that I have used EntityFramework many times already but I want to know its inner workings and decided to do it for the starters. That is why I created this blog to share my experience when I did it in vb.net.For the remainder of this blog EF is EntityFramework.

So, now let’s get EF from nuget using package manager console in visual studio. At the time of this writing I am using Visual Studio 2013.

1. Go to package manager console.
PackageManagerConsole

2. Install the latest EF package which currently is 6.1.1.

PackageManagerConsoleConsole

3. Time to create our DbContext. What Im doing here is that I am inheriting from System.Data.Entity.DbContext,

Imports System.Data.Entity
Public Class EFContext
     Inherits DbContext
End Class

4. Lets Assign our connection string to our context.

Public Sub New()
     MyBase.New(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
End Sub

5. Lets create our entity

Public Class Users
     Property UserId As Integer
     Property Username As Integer
     Property FirstName As String
     Property LastName As String
End Class

6. Add our entity to our context

Private _systemUsers As DbSet(Of Users)
Public Property SystemUsers() As DbSet(Of Users)
     Get
          Return _systemUsers
     End Get
     Set(value As DbSet(Of Users))
          _systemUsers = value
     End Set
End Property

7. And finally lets override OnModelCreating method of our base class DbContext. Why I am doing this? Because I am telling our custom DbContext that I have an existing database and I don’t what you to touch it.

Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
     MyBase.OnModelCreating(modelBuilder)
     Database.SetInitializer(Of EFContext)(Nothing)
End Sub

And that is pretty much about it. You now have your custom DbContext using the code first approach.

The complete source is available in github. https://github.com/francorobles/Blog/tree/master/EntityFrameworkVB

Adding AntiForgeryToken to MVC with jQuery

I’ve seen many posts on how to include MVC’s AntiForgeryToken on a view that is using a javascript framework for its UI. Well, below is a simple solution on how you can implement it. By the way, I am using MVC 3 and jQuery while writing this post.

First.
Include @Html.AntiForgeryToken() on your view. Below is an example view.

Second
On your controller, add the [ValidateAntiForgeryToken] attribute.

Finally
To complete the puzzle, lets post our data together with the antiforgery token to our controller action. You need to encode the value of __RequestVerificationToken before posting it, otherwise it will be useless.

And that’s it, as simple as the above.