X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, June 19, 2014

Linq and lambda expressions in c#

Introduction

LINQ or Language Integrated Query is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
LINQ simplifes and reduces the code with neat and effective way. It provides an easy way to write queries that can run with the in-memory objects.
Linq is always associated with Lambda Expressions. in .NET 2.0 we had the concept of Annonymous Methods that allows you to write function body inline without the need of writing a delegate function. So In .Net 3.5 Lambda Expressions are used for the same purpose.
Linq and lambda expressions in c#
Types of LINQ
There are basically 3 types they are -
1. LINQ (Linq to Objects)
2. DLINQ (Linq to SQL)
3. XLINQ (Linq to XML)
How to use
So you will be thinking now in which scenarios i can use it. Here i am going to explain few scenarios where LINQ simplifies the process.
Following are some of the scenarios where we can use LINQ or Lambda expressions -
1) DataTable to List of Objects
Add one method to get the data table for our testing purpose. Since i love to use MVC i will create an MVC application but you can create webform as well.
 private DataTable GetDataTable()
  {
      DataTable dt = new DataTable();
      dt.Columns.Add("ID", typeof(int));
      dt.Columns.Add("Name", typeof(string));
      dt.Columns.Add("Gender", typeof(string));

      DataRow dr1 = dt.NewRow();
      dr1["ID"] = 1;
      dr1["Name"] = "aa";
      dr1["Gender"] = "M";

      DataRow dr2 = dt.NewRow();
      dr2["ID"] = 2;
      dr2["Name"] = "bb";
      dr2["Gender"] = "M";

      DataRow dr3 = dt.NewRow();
      dr3["ID"] = 3;
      dr3["Name"] = "cc";
      dr3["Gender"] = "F";

      dt.Rows.Add(dr1);
      dt.Rows.Add(dr2);
      dt.Rows.Add(dr3);
      
      return dt;
  }



Now i will create one class which same properties as Datatable columns. I will call it as “Employee”.
public int ID { get; set; }

public string Name { get; set; }
        
public string Gender { get; set; }

I will add one more method which uses the DataTable and converts into List of Employees using Reflection -
private IList ConvertToList(DataTable dt)
 {

   var columns = dt.Columns.Cast()
                .Select(c => c.ColumnName)
                .ToList();
    
    var props = typeof(T).GetProperties();
       return dt.AsEnumerable().Select(row =>
       {
          var objT = Activator.CreateInstance();
          foreach (var pro in props)
          {
               if (columns.Contains(pro.Name))
               {
                    if (row[pro.Name] != DBNull.Value)
                    {
                        pro.SetValue(objT, row[pro.Name], null);
                    }
                    else
                    {
                        pro.SetValue(objT, null, null);
                    }
                }
           }
    
        return objT;
    }).ToList();
            
 }

So Call the method like this -
DataTable dt = GetDataTable();
List employees = ConvertToList(dt).ToList();

2) Get DISTINCT List of Objects
Now lets see how we can get distinct records of employees based on employee name using LINQ.

//Get Distinct Employees
List distinctItems = employees.GroupBy(a => a.Name).Select(b => b.First()).ToList();

3) Check value exists in List of Objects
Below is the query to check the value exists in List of Objects or not. If it exists then it will return "true" else "false".

//Check for Employee Name in List of Employees
bool isRes = employees.Any(w => w.Name.Contains("er"));

Hope this helps.

Thank You.



Sunday, June 15, 2014

MVC Route Debugger – GLIMPSE

As we all know MVC pattern purely relies on Routing. In ASP.NET MVC routing, you can define URL patterns that map to request-handler files, but that do not necessarily include the names of those files in the URL. In addition, you can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string. So here i am not elaborating much on MVC pattern and Routing mechanism. So this post is written mainly concentrating on the mvc routing debugger.
I know there are lot of people loving to code in MVC. But there are lot of people like me who struggled a lot in the MVC Routing, who are not able to find which method is being called on client request.
To overcome this there are lots of tools came in the market to ease the debugging the routing part. So here i am going to explain the debugger called “Glimpse”, which is used by majority of the people to debug their routing needs.
So what is Glimpse ?
Glimpse is like the FireBug client side debugger, except it’s implemented in JavaScript on the client side with hooks in to ASP.NET on the Server Side.
How i can use it in my Visual Studio Project ?
So here i am going to explain you the steps to use “Glimpse” in your project -
Open your Visual Studio -> Click on New Project -> Click on Web -> Select ASP.NET MVC4 Web Application

MVC Route Debugger – GLIMPSE















Click on Tools -> Nuget Package Manager -> Package Manager Console -> Install-Package Glimpse


MVC Route Debugger – GLIMPSE



and Install Glimpse for MVC4 using command -> Install-Package Glimpse.MVC4
You can observe the change in your web.config, it adds the few lines which are relevant to glimpse.

Now, I will run my app. I can turn Glimpse on like visiting http://localhost:portname//glimpse.axd and click on button “Turn Glimpse On”

You can see the below toolbar at the bottom of the screen -
MVC Route Debugger – GLIMPSE





In the above screenshot you can check the request details, method called in server, time taken to get the response etc. which i feel is boon to all developers to track the code and debug. 
This article is just for overview of it you can check more on - http://www.getglimpse.com


Sunday, June 8, 2014

DataContracts are not generated in Client side after adding Service Reference !!

Hi All,
Back to boring WCF but this time with a different issue :-):-)
This time my client wanted to have an smart client application using .NET technology. So here is my list of layers created for this project -
1) DataAccess Layer – Contains my Classes with DataContracts and library references which are used to connect to my SQL database.
2) Service Layer – which is used for calling the methods which are in DataAccess Layer. We have used WCF service with SOAP in this case.
3) Client Library – which takes the reference of the service and calls up the methods in service layer.
After giving an reference of the WCF service to my client library i was not getting the classes generated in the client side.
I made sure that i have added “DataContract” and “DataMember” attributes are added on my Class and Property level respectively.
1 full day i was scratching my head but of no use :-):-)
Next day some forum answers provoked me to find the root cause of it. I got following answers in forums -
1. Try remove the entire service reference and add again, instead of update.
2. Please check if project settings are same – like – platform, framework and other settings are same – any assembly keys you are using?
3. Also check if there are any predefined assembly references are missing on your destination project.
So finally i found the solution – That was because My Service Library was in Framework 4.5 and my Client Library was in Framework 3.5.
So after changing my Service Library to Framework 3.5 it solved the issue.
Note : In my case client wanted the client library to be in Framework 3.5 so i changed my Service Library to Framework 3.5. You can do it vice versa too. (Client and Service libraries to be in framework 4.5)
Other reason also i found by googling is “If DataContracts are not been used in any of your Service Methods
(Operation Contracts) then also you would not get that in Client side”.
In my case DataContract was of type class. Same thing is true for other types like structures, or enumerations too.
Hope this is helpful to others.

Change base address wcf

Wow !!! today i had first vision towards WCF technology its seems to be very interesting. I was scratching my head from last 2 hours and got the solution and by seeing the solution i myself got ashamed…..

The funny thing started from here -


Change base address wcf
















Here I am trying to create a new WCF project and here I have the options
1)      WcfServiceLibrary
2)      WcfService Application
3)      Wcf Workflow Service Application
4)      Syndication Service Library
I am choosing “WcfServiceLibrary” because I wanted a dll to be created and I am hosting WCF in self-hosting method.
Now look at the app.config which is been created by default,
Change base address wcf














This is the config file generated and the default base address generated is
 Which is using Http binding, Now suppose I want to change the base address to
I tried this but I was getting this error
“Please try changing the HTTP port to 8732 or running as Administrator.”
Then after googling this I got some links which could help me to resolve this issue and finally it got solved by running visual studio in Administrator mode.
Change base address wcf

Running as administrator will allow you to run the service on any port.
After doing this automatically everything  worked !!!!
Isn’t  that funny.. yes it is….


Hope it helps…..