Tuesday, 29 July 2014

LINQ:: Left Join in C#

In this post, we will see an example of how to do a Left Outer Join in LINQ and C#.

In a previous post, we saw how to do an Inner join in C# and LINQ where each element of the first collection appears one time for every matching element in the second collection. If an element in the first collection has no matching elements, it does not appear in the join result set. However in a Left Outer Join, each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection.

Let us see this with an example.

public class Book
public int BookID { get; set; }
public string BookNm { get; set; }
public class Order{
public int OrderID { get; set; }
public int BookID { get; set; }
public string PaymentMode { get; set; }}

class Program
static void Main(string[] args)
#region bind Data
List<Book> bookList = new List<Book>
new Book{BookID=1, BookNm="DevCurry.com Developer Tips"},
new Book{BookID=2, BookNm=".NET and COM for Newbies"},
new Book{BookID=3, BookNm="51 jQuery ASP.NET Recipes"},
new Book{BookID=4, BookNm="Motivational Gurus"},
new Book{BookID=5, BookNm="Spiritual Gurus"}

List<Order> bookOrders = new List<Order>{
new Order{OrderID=1, BookID=1, PaymentMode="Cheque"},
new Order{OrderID=2, BookID=5, PaymentMode="Credit"},
new Order{OrderID=3, BookID=1, PaymentMode="Cash"},
new Order{OrderID=4, BookID=3, PaymentMode="Cheque"},
new Order{OrderID=5, BookID=5, PaymentMode="Cheque"},
new Order{OrderID=6, BookID=4, PaymentMode="Cash"}

var orderForBooks = from bk in bookList
join ordr in bookOrders
on bk.BookID equals ordr.BookID
into a
from b in a.DefaultIfEmpty(new Order())
select new
Name = bk.BookNm,

foreach (var item in orderForBooks)


In the code shown above, the query uses the join clause to match Book objects with Order objects testing it for equality using the equals operator. Up till here, the query is the same as in our previous article.

Additionally in order to include each element of the Book collection in the result set even if that element has no matches in the Order collection, we are using DefaultIfEmpty() and passing in an empty instance of the Order class, when there is no Order for that Book.

The select clause defines how the result will appear using anonymous types that consist of the BookID, Book Name and Order Payment Mode.

Observe that BookID =2 was included in the list even though it did not have an entry in the Order table. 

Continue Reading →

Monday, 21 July 2014

Enable jQuery Intellisense support to MVC3 Razor

Jquery intellisense support helps a lot while programming with jQuery. By default Visual Studio doesn't provide us the jQuery intellisense support. We can enable the jQuery intellisense support in Visual Studio with MVC Razor by adding vsdoc.js file to your view like as :

@if (false)
<script src="~/Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>

The above if-statement prevents the rendering of script tag into the html source code and it used only by the Visual Studio for jQuery intellisense support. To check jQuery intellisense type the $ or $( between your $(document).ready(function() function and you can see the intellisense as shown in fig.

Note:  In MVC Razor, there is no central place to add the reference to the vsdoc.js file. We need to add this code line to each every view separately to enable the IntelliSense support for jQuery.

Continue Reading →

Difference between Asp.Net WebForm and Asp.Net MVC

Asp.net framework is a part of .net platform for building, deploying and running web applications. Now, we can develop a web application by using Asp.Net Web Form and Asp.Net MVC. In this article, I am going to expose the main difference between Asp.Net Web Form and Asp.Net MVC.
Difference between Asp.Net MVC and Web Forms
{click on the image to zoom:}
Asp.net framework is a part of .net platform for building, deploying and running web applications. Now, we can develop a web application by using Asp.Net Web Form and Asp.Net MVC. In this article, I am going to expose the main difference between Asp.Net Web Form and Asp.Net MVC.
Continue Reading →

Thursday, 10 July 2014

MVC using Web API and JQuery to GET or POST Data


In this tip, you can learn about how to use WebApi with MVC and jquery. I have defined getpostput and deletemethods using model class to use it in jquery at client side and MVC controller.

About WebApi

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

We already know about WCF services and web services that both are soap based services and they use HTTP as the transport level protocol. That means they use HTTP protocol just to tunnel the soap messages across the internet. But all clients are not handled to suitable the soap messages. SOAP messages are internally XML and handling XML which might be complicated for some clients. And the best example non soap based client is JQUERY. Now to overcome this problem we introduced WCF rest services. If you are conversant with REST, please go through WCF REST services site and first learn it there. REST is an architectural style which says to use the existing features of the web in a more efficient and simpler way. If you want to know about the features and to learn them, those are HTTP verbs like GET,POSTPUT and DELETE. In REST, every stuff is unique to identify, not always in XML for communication you can pass XML, JSON so on. Use this feature for this we are calling HTTP rest service.

For use of WCF rest service, it requires lots of configuration settings which is a bit complicated. The main intention behind services is building service oriented architecture not to support REST. Now Microsoft simplified this and finally it came with the solution, created part of ASP.NET called ASP.NET Web API. It is part of ASP.NET technology for creating REST services.

MVC with API

With MVC 4 application with selection of Web API Template, this includes a sample web API call ValuesController. Here you will find lots of features which are the same as MVC. It means not exactly the same but its code patterns are similar. If you are not an MVC developer, these things may be difficult for you, otherwise it's very easy to understand.

Let's discuss something about this. In MVC, there is an added MVC Controller whereas in web API, there is an added API controller. In API controller, action methods are HTTP verbs like GetPostPut and Delete even we can overload this methods.

Let's discuss about another feature - that's RouteConfig.cs file:

   public class RouteConfig
        public static void RegisterRoutes(RouteCollection routes)

                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new
                    controller = "Person",
                    action = "Index",
                    id = UrlParameter.Optional

Let's discuss about MVC Routes how MVC is implemented with Web API. You will get App_Start folder and open it. When request comes to MVC, it takes the URL and passes through its three segments. The first name is controller, it finds controller by its name. Next is action then it finds the methods with this name. And also, we have default id with option UrlParameter. Just like this, we have WebApiConfig.cs file:

name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }

Just like this in WebApi default name is DefaultApi. Just to keep separate with MVC routes web API routes template defined first is API. We can change it to customerapifacebookapi so on as per our requirement. Next is controller and id option RouteParameter. The main thing is that it doesn't have action here, we only have HTTP methods depending on client requirements. If it is a get request, the get method will call and post request, thenpost method will call and so on.


Let's create a Person class inside model folder.

    public class Person
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public DateTime DOB { get; set; }
    public class PersonEntities : DbContext
        public DbSet<Person> Persons { get; set; }

 As per the API, my API controller name is Values on top of the picture. I have changed instead of returning stringchanged to person list.

    public class ValuesController : ApiController
        PersonEntities db = new PersonEntities();
        // GET api/values
        public IEnumerable<person> Get()
            return db.Persons.ToList();
            //return new string[] { "value1", "value2" };

I have commented the default return values. I have also dded PersonalEntities where I have defined it in modelclass. When you will run the application, browse through the ../api/Values/ you will get data with XML in chrome browser. You can get JSON representation of data from request of get method. For this, I have designed it inIndex2 VIEW page. This is just as content negotiation. Depending on the client request, it returns the data. When client says XML, it returns XML and JSON even say we return our own custom format like visiting card, class or anything.

    $(document).ready(function () {
            url: "http://localhost:49493/api/Values",
            type: "Get",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {

" + data[i].Name + "</td>
                    " + data[i].Address + "</td>
                    " + data[i].DOB + "</td></tr>").appendTo("#tbPerson");                  
            error: function (msg) { alert(msg); }

In this above code, I have collected JSON data by the code of JSON format and designed it to our HTML page. One of the things we can show as MVC format by the call of Web API get method where you will get complete information to view the downloaded project. if you will run http://localhost:49493/api/Values in chrome browser then get to see like below image. It will return HTTP XML values.

Call the Post Method of Web API

Now, we will write a code which will consume the web API by the way of JQuery and MVC. Now I am writing a post method in Web API to insert data.

// POST api/values
        public void Post(List<string> val)//(Person obj )
                Person obj = new Person();
                obj.Name = val[0];
                obj.Address = val[1];
                obj.DOB = Convert.ToDateTime(val[2]);
            catch (Exception) { }

Now our main purpose to use Web API in client side using MVC. For this, I have added a script in MVC using jquery link. You will get to see to post data using JQuery with MVC. For this, I have coded it into create.cshtml. You will get to see below:

 $(document).ready(function () {
    $("#submit").click(function () {
        var name = $("#Name").val();
        var address = $("#Address").val();
        var dob = $("#DOB").val();
            url: "http://localhost:49493/api/Values",
            type: "Post",
            data: JSON.stringify([name, address, dob]), //{ Name: name,
                                              // Address: address, DOB: dob },
            contentType: 'application/json; charset=utf-8',
            success: function (data) { },
            error: function () { alert('error'); }

Download SourceCode Click @ me
Continue Reading →


ADFS (1) ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Authentication (1) Azure (1) Breeze.js (1) C# (50) CD (1) CI (2) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DevOps (4) DI (4) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSO (1) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)