Tuesday, February 18, 2014

LINQ - Filter a List from a comma separated string

I've used a sample Product class shown below.  productList contains 3 static values.

public class Product
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

string productIds = "1,3";
List<Product> productList = new List<Product>();

productList.Add(new Product() { Name = "iPhone", Price = 60000, ProductId = 1 });
productList.Add(new Product() { Name = "Google Nexus 5", Price = 34000, ProductId = 2 });
productList.Add(new Product() { Name = "iPad", Price = 27000, ProductId = 3 });

ProductIds are split into an IEnumerable<int> array and LINQ WHERE clause is used with "Contains"

//split productIds and populate productIdArray
IEnumerable<int> productIdArray = productIds.Split(',').Select(x => int.Parse(x));

//filter productList and fetch only the records which contains values in "productIdArray"
IEnumerable<Product> productFilter = productList.Where(c => productIdArray.Contains(c.ProductId));

"Children could not be evaluated" issue after updating Entity Framework to version 6

I was recently working on an ASP.NET MVC 4 website using Entity Framework 5.0.  

I updated my entity framework using "update-package -EntityFramework" command in package manager console.  It updated Entity Framework pretty well, but stuck me with an issue.  I was no longer able to debug my values and it showed "Children could not be evaluted" as shown below.  This was working fine before I updated my entity framework.

The solution is really simple but tricky.  I just had to add .ToList() at the end of the query and it worked like a charm.

Wednesday, January 22, 2014

Monday, January 13, 2014

RequireJS and ASP.NET MVC

RequireJS is a javascript file and module loader.  It is used to load your javascript frameworks/plugins dynamically when needed and can optimize the time taken by your website to load your pages.

I'll demo a simple ASP.NET MVC 3.0 Application with RequireJS

Step 1: Download latest version of RequireJS from http://requirejs.org/docs/release/2.1.10/minified/require.js

Step 2: Create an ASP.NET MVC project and include the require.js file in your _Layout.cshtml page or Site.Master if you're using ASP.NET MVC 2.0.

<script src="@Url.Content("~/Scripts/require.js")" data-main="/scripts/main.js" type="text/javascript"></script>

data-main  attribute refers to main.js file which would act as a single point of interaction.  You can load all your javascript files dynamically through this js file.  This attribute would load the main.js file asynchronously after require.js file is loaded.

Step 3: Include jquery file in your scripts folder

Step 4: Add a div with the id="container" in a view

Step 5: Below is the code for Main.js file

require(['Scripts/jquery'], function () {
    $().ready(function () {
        $('#container').html("Hey! Require.js rocks!!");

The code above loads jquery file dynamically and initializes the document.ready event.  The code would simply insert a static html inside "container" div.

Note that "Scripts/jquery"  would be your path of jquery.js file excluding the ".js" extension.

For example, if you are refering to a file jquery-1.10.1.js located in scripts folder, you have to use require(['Scripts/jquery-1.10.1'],....)

Thursday, December 5, 2013

Get Compile-Time View Errors in ASP.NET MVC

ASP.NET MVC developers generally face an issue with compiling their views.  The errors are not reported when compiling views and they eventually turn out to be "Yellow Screen Of Death" issues from client.  Below are the steps to enable compilation errors in views:

  1. Right-click on your project file in Visual Studio’s Solution Explorer and choose Unload Project.
  2. Right-click the project file again and choose Edit YourProject.csproj.
  3. Look for a node called <MvcBuildViews> in the first <PropertyGroup> node (the one without any other attributes). If it’s not there, add it.
  4. Add or update the value inside the <MvcBuildViews> node to true. When you’re done it should look like this: 

  5. Save the project file changes.
  6. Right-click the project file in Solution Explorer one last time and select Reload Project.

How to get the substring of a string that contains HTML tags using C# .Net

public string HtmlSubstring(string html, int maxlength)
            //initialize regular expressions
            string htmltag = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>";

            //match all html start and end tags, otherwise get each character one by one..
            var expression = new Regex(string.Format("({0})|(.?)", htmltag));
            MatchCollection matches = expression.Matches(html);

            int i = 0;
            StringBuilder content = new StringBuilder();
            foreach (Match match in matches)
                if (match.Value.Length == 1 && i < maxlength)
                //the match contains a tag
                else if (match.Value.Length > 1 && i < maxlength)

            return Regex.Replace(content.ToString(), string.Empty, string.Empty);