Friday, November 17, 2017

Creating WCF Service without .SVC File

This blog demonstrates how to create a WCF service without having physical .SVC File and after .net 4.0 release, we can create a WCF service without having svc file.

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application


In general, WCF Service have .SVC File and Service Code File as shown below







This SVC file is a simply text file and which contains the below information, which allows to host WCF Service and respond to incoming request/message.

·         Language: (C# / VB)
·         Service (Name of the service) : MoneyTransfer
·         CodeBehind (The location of service code ) : MoneyTransfer.svc.cs

Here is an example of SVC file:

<%@ ServiceHost Language="C#" Debug="true" Service="MoneyTransfer" CodeBehind="Money.MoneyTransfer.svc.cs" %>

A .SVC file contains a WCF-specific processing directive (@ServiceHost) that allows the WCF hosting infrastructure to activate hosted services in response to incoming messages. This file contains the details required for WCF service to run it successfully.


CodeBehind File : MoneyTransfer.svc.cs


namespace Money

{
    [ServiceContract]
    public interface IMoneyTransfer
    {
        [OperationContract]
        bool Post(decimal money, int accountNumber);

        [OperationContract]
        bool Withdrawal(decimal money, int accountNumber);
    }

    public class MoneyTransfer : IMoneyTransfer
    {
        public bool Post(decimal money, int accountNumber)
        {
            throw new NotImplementedException();
        }

        public bool Withdrawal(decimal money, int accountNumber)
        {
            throw new NotImplementedException();
        }
    }
}


WCF HOSTING


after .net 4.0 release, it allows to create a WCF service  without SVC file and all required setting for WCF hosting we can defined in web.config file.

The service activation is configuration element that allows you to define virtual service activation settings that map to your Windows Communication Foundation (WCF) service types. This makes it possible to activate services hosted in WAS/IIS without a .svc file.

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" >
      <serviceActivations>        <add relativeAddress ="MoneyTransfer.svc" service ="Money.MoneyTransfer"/>
      </serviceActivations>
    </serviceHostingEnvironment>

Breakdown the serviceActivations configuration element

·         RelativeAddress : the relative address within the current IIS application and it contain .SVC file address, which does not physically exist

·         Service: the service type that implements the service.




Monday, November 6, 2017

Entity Framework : Eager Loading of Multiple Levels of Entities by Using Include

This blog will demonstrates how to do multiple levels of entities loading by using include() method in entity framework and there are two ways to load the related entities data
  1.       Eagerly Loading
  2.       Lazy Loading


Eagerly Loading : 
In eager loading process, the query related to other related entities is part of the main query and it will be achieved by using INCLUDE method.

Example :

List<Customer> customers = _db.Customers.Include("Addresses").ToList();

OR

List<CustomerData> customers = _db.Customers.Include(c => c.Addresses).ToList();

as you can see in above ef query, Customer entities will be loaded along with included thier assciated Addresses entity data

in below exmaple you can see the multiple level of entities is being loaded. Customer enetity is being loaded with included entities Addresses, Order and it's releated Review entities.

Example :

List<Customer> customers = _db.Customers. Include("Addresses").Include("Orders.Reviews").ToList();

Lazy Loading:
In lazy loading process, the related entities is automatically loaded from the database the first time that property is being referenced or used



Thanks for visiting!!

Thursday, November 2, 2017

C# LINQ : SingleOrDefault() Vs. FirstOrDefault()

LINQ provides the operators like Single (), SingleOrDefault(), First() and FirstOrDefault(), they select a specific record from collection.SingleOrDefault() and FirstDefault() returns NULL or Default Value if there is no matching record found.


here is a list of customers :
 List<Customer>Customers = new List<Customer>
            {
                 new Customer { CustomerID = 1, Name= “Herry” },
                 new Customer { CustomerID = 2, Name=”Tom” }
            };

Select record by using FirstOrDefault() method
  Customer customer = Customers.FirstOrDefault(x => x.CustomerID = 1)

Select record by using SingleOrDefault() method
                Customer customer = Customers.SingleOrDefault(x => x.CustomerID = 2);

SingleOrDefault() vs FirstOrDefault()
  • SingleOrDefault() throw exception if we have more than one matching records, and FirstOrDefault() returns the first matching record in sequence.
  • Both SingleOrDefault() and  FirstOrDefault() return default value or NULL, If no matching record found.
  • FirstOrDefault() generates the TSQL statement "SELECT TOP 1..." and SelectOrDefault() generates regular TSQL statement "SELECT ..”
  • In Performance, FirstOrDefault() is usually faster than SingleOrDefault(). The FirstOrDefault() doesn’t care about record uniqueness and amount of record

Recommendations: if you sure, the query should result in at most a single result, you should use SingleOrDefault(), and on other side if query return any number of results, you should use FirstOrDefault() method.

Thanks for visiting!!

Friday, October 20, 2017

LINQ To EF : Error "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities in entity framework"

In LINQ -to-EF query, First EF query is translated into SQL and when we are trying to translate some code into SQL and something is not supported in SQL and then this exception occurred.




"The LINQ expression node type 'Invoke' is not supported in LINQ to Entities in entity framework"

    public List<PersonData> GetAll()

        {

             return _db.Persons.Select(x => MapToPersonData(x)).ToList();

        }

internal static Func<Person, PersonData> MapToPersonData = m =>
    {
        if (m == null)
        {
            return null;
        }
        else
        {
            return new PersonData()
            {
              PersonID = m.PersonID,
              Name = m.Name,
              Location = m.Location.City +""+ m.Location.Street
            };
        }
    };


In above EF Query, the function MapToPersonData()  is being used to map the person entity into person data object and in this function, we are concatenating  of the city and Street string and the concatenating of string will not be supported in LINQ to entties, so the above error is occured.

What solution I found, we have to fetch data from database table in your local memory by calling .ToList()/.ToEnumerable() function and then we can apply logic on top of that similar like LINQ-To-Object 


       public List<PersonData> GetAll()

        {

           return _db.Persons.AsEnumerable().Select(x => MapToNameData(x)).ToList();

        }

  
Other entity framework related links

Friday, September 29, 2017

C# IEnumerable vs IQueryable

The primary difference is that IEnumerable is great for working with in-memory collections, and IQueryable for a remote data source, like a database or web service.

IEnumerable : 
IEnumerable represent a forward collection of T and It has one GetEnumerater() method, from which you can iterate through collection.
  • It does not support adding, removing objects on collection.
  • It loads all object collection into local memory by using LINQ or entity framework before running query.
  • It is best option for in-memory data source like object collections, if your IEnumerable query is being executed against external database, it would be network overhead and first loads whole entity data in local memory and then apply filter.
 public interface IEnumerable<out T> : IEnumerable
    {      
        IEnumerator<T> GetEnumerator();

    }


IQueryable
 IQueryable is similar like LINQ and it parse the expression tree and generates SQL querya nd execute the script against the external data source.
  • It inherits the IEnumerable interface so it allows you to iterate over collection using ForEach statement.
  • It is best option for out-memory data source like database and it send only the filtered data to client and reduce network overhead due to reducing record count.

public interface IQueryable<out T> : IEnumerable<T>
{

}

Tuesday, September 5, 2017

Difference between Select and SelectMany in LINQ

Select and SelectMany are projection operator and Select method is used to select a
value from collection and SelectMany method is used to select value from multiple
collection. 

In below example, we will see that Select will returns the collection of Player object and to read Player Name, we need one more For Each loop to read the Player object and
SelectMany will flatten the list into a single list of Players, so we need only one for-each
loop to get player name.

Select Vs Select Many


C# Example : 


List<Team> teams = new List<Team>();


Team team1 = new Team {
             Name = "USA",
             Players = new List<Player> {
                                     new Player {  PlayerName = "John" },
                                     new Player { PlayerName = "Peter" },
                                     new Player { PlayerName = "Steve" }
             } };


Team team2 = new Team
         {
             Name = "AUS",
             Players = new List<Player> {
                    new Player {  PlayerName = "Ricky" },
                    new Player { PlayerName = "McGraw" },
                    new Player { PlayerName = "Donald" }
             }
         };


teams.Add(team1);
teams.Add(team2);


Select : 
by using Select query. We need two for-each loop to retrieve the player name from a
team collection of arrays, because Select returns a collection of arrays.


C# Example : 


var resultSelect = teams.Select(e => e.Players);


foreach (var playerList in resultSelect)
         {
                foreach (var player in playerList)
             {                      Console.WriteLine(player.PlayerName);
             }
                Console.WriteLine();
         }


Output:


John
Peter
Steve


Ricky
McGraw
Donald


SelectMany: 
By using SelectMany query, we only need one for each loop to retrieve the player name
from team collection of array and SelectMany returns a one dimensional collection.

C# Example : 
     
      var resultSelectMany = teams.SelectMany(emp => emp.Players);


      foreach (var player in resultSelectMany)
         {
                Console.WriteLine(player.PlayerName);
         }


            Console.ReadKey();
     }


Output:
John
Peter
Steve
Ricky
McGraw
Donald


Thanks for visiting !!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...