Friday, 21 November 2014

Split Function in sqlserver



CREATE FUNCTION [dbo].[SPLIT] (@LIST VARCHAR(1000), @SPLIT_BY VARCHAR(1)=',')
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN

    SELECT ROW_NO=row_number()over(order by @@rowcount),ITEM = y.i.value('(./text())[1]', 'nvarchar(50)')
    FROM
    (
    SELECT x = CONVERT(XML, '<i>'
        + REPLACE(@List, @SPLIT_BY, '</i><i>')
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
);

Thursday, 14 August 2014

When to use which bindings in WCF

What is WCF Bindings?

WCF bindings decides how Windows Communication Foundation service endpoint should communicate with clients. Each WCF service endpoint requires binding to be specified, if not set explicitly it uses default basicHttpBinding. It gives communication details and define below things.

  1. Protocols: specifies what type of security can be used like reliable messaging or transaction context.
  2. Encoding: specifies type of message encoding like binary or text.
  3. Transport: specifies communication transport to be used like HTTP or TCP.

WCF Predefined Bindings

  1. basicHttpBinding

    basicHttpBinding is best when you have traditional ASMX(Active Server Methods) web services and needs to be replace with WCF. It supports text as well as MTOM encodings and it does not support WS-* standards like WS-Addressing, WS-Security and WS-ReliableMessaging. 
    basicHttpBinding uses HTTP or HTTPS protocols. You can configure SSL for Transport Layer security with basicHttpBinding.
  2. WsHttpBinding

    This is secure and interoperable bindings uses SOAP over HTTP. With WsHttpBinding messages are encrypted by default and achieve message level security. It supports reliability, transactions and security over internet. It supports HTTP or HTTPS protocols and text as well as MTOM encoding. 
    The difference between basicHttpBinding and WsHttpBinding is WsHttpBinding does support WS-* standards like WS-Addressing, WS-Security and WS-ReliableMessaging whereas basicHttpBinding does not.
  3. wsDualHttpBinding

    wsDualHttpBinding is best when you required bidirectional communication with client. In some scenario when client makes call to WCF service, after processing of long running request service has to call client application for example updating shipment details to client application. 
    It supports reliability, transactions and security over internet. It supports HTTP or HTTPS protocols and text as well as MTOM encoding. You can implement Duplex message exchange pattern with wsDualHttpBinding.
  4. webHttpBinding

    webHttpBinding is best when you wish to implement RESTful WCF service. This is secure and interoperable binding which sends information directly over HTTP or HTTPS without creating SOAP messages. It allows HTTP request to use plain old XML (POX) style messaging which reduces the message size on wire compare to SOAP messages.
  5. NetTcpBinding

    netTcpBinding is best when WCF service and its clients are in intranet infrastructure. As it supports only TCP protocol and not HTTP so service cannot be accessed over internet. 

    This is secure binding is used to send binary encoded SOAP messages with in intranet computers. It supports reliability, transaction and security. If your using netTcpBinding and host WCF service in IIS, you need to make some settings on system and IIS this article will help you for required settings.
  6. netNamedPipeBinding

    When your WCF service and its clients reside on same computer netNamedPipeBinding is the best choice and gives best performance over other bindings. This is secure bindings. Binary encoded SOAP messages are sent over named pipes. 
    See how to implement netNamedPipeBinding in WCF services.
  7. netPeerTcpBinding

    netPeerTcpBinding is best when you require more security for peer to peer communication as netTcpBinding does not provide it. It is secure binding and supports TCP protocols.
  8. WsFederationHttpBinding

    It is secure and interoperable binding supports federated security. It supports HTTP and HTTPS transport protocols as well as text and MTOM encodings.
  9. NetMsmqBinding

    netMsmqBinding is best when you have to execute service operations in queued manner. Service requests are placed in queue and executed one by one. With netMsmqBinding service operations will always be one way and does not return any response to client. 
    This is interoperable bindings and can be used on existing MSMQ applications that use COM or Application Programing Interface(API)

In real time applications you have to use multiple bindings for one service endpoints. For example internet applications should be able to access service through HTTP request at same time the back office application should be able to access service by netTcpBinding or netNamedPipeBinding to get performance benefits.


Tuesday, 8 July 2014

LINQ Querys and Lambda Expression Examples


Where

IEnumerable<Product> x = products.Where(p => p.UnitPrice >= 10);
IEnumerable<Product> x =
    from p in products
    where p.UnitPrice >= 10
    select p;

Select
IEnumerable<string> productNames = products.Select(p => p.Name);
IEnumerable<string> productNames = from p in products select p.Name;
var namesAndPrices =
    products.
    Where(p => p.UnitPrice >= 10).
    Select(p => new { p.Name, p.UnitPrice }).
    ToList();
IEnumerable<int> indices =
    products.
    Select((product, index) => new { product, index }).
    Where(x => x.product.UnitPrice >= 10).
    Select(x => x.index);

SelectMany

IEnumerable<Order> orders =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders);
var namesAndOrderIDs =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    Select(o => new { o.Customer.Name, o.OrderID });
var namesAndOrderIDs =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders, (c,o) => new { c, o }).
    Where(co => co.o.OrderDate.Year == 2005).
    Select(co => new { co.c.Name, co.o.OrderID });
var namesAndOrderIDs =
    from c in customers
    where c.Country == "Denmark"
    from o in c.Orders
    where o.OrderDate.Year == 2005
    select new { c.Name, o.OrderID };

Take

IEnumerable<Product> MostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Take(10);

Skip

IEnumerable<Product> AllButMostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Skip(10);

TakeWhile SkipWhile
s.TakeWhile(p) s.SkipWhile(p)
Join

var custOrders =
    customers.
    Join(orders, c => c.CustomerID, o => o.CustomerID,
        (c, o) => new { c.Name, o.OrderDate, o.Total }
    );
var custOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID
    select new { c.Name, o.OrderDate, o.Total };

GroupJoin

var custTotalOrders =
    customers.
    GroupJoin(orders, c => c.CustomerID, o => o.CustomerID,
        (c, co) => new { c.Name, TotalOrders = co.Sum(o => o.Total) }
    );
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID into co
    select new { c.Name, TotalOrders = co.Sum(o => o.Total) };
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID
    select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID into co
    from o in co
    select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =
    from c in customers
    join o in orders on c.CustomerID equals o.CustomerID into co
    from o in co.DefaultIfEmpty(emptyOrder)
    select new { c.Name, o.OrderDate, o.Total };
Concat

IEnumerable<string> locations =
    customers.Select(c => c.City).
    Concat(customers.Select(c => c.Region)).
    Concat(customers.Select(c => c.Country)).
    Distinct();
IEnumerable<string> locations =
    new[] {
        customers.Select(c => c.City),
        customers.Select(c => c.Region),
        customers.Select(c => c.Country),
    }.
    SelectMany(s => s).
    Distinct();

OrderBy / ThenBy

IEnumerable<Product> orderedProducts1 =
    products.
    OrderBy(p => p.Category).
    ThenByDescending(p => p.UnitPrice).
    ThenBy(p => p.Name);
IEnumerable<Product> orderedProducts1 =
    from p in products
    orderby p.Category, p.UnitPrice descending, p.Name
    select p;
IEnumerable<Product> orderedProducts2 =
    products.
    Where(p => p.Category == "Beverages").
    OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
IEnumerable<string> orderedProductNames =
    products.
    Where(p => p.Category == "Beverages").
    Select(p => p.Name).
    OrderBy(x => x);

GroupBy

IEnumerable<IGrouping<string, Product>> productsByCategory =
    products.GroupBy(p => p.Category);
IEnumerable<IGrouping<string, string>> productNamesByCategory =
    products.GroupBy(p => p.Category, p => p.Name);

Distinct

IEnumerable<string> productCategories =
    products.Select(p => p.Category).Distinct();

AsEnumerable

Table<Customer> custTable = GetCustomersTable();
var query = custTable.AsEnumerable().Where(c => IsGoodCustomer(c));

ToArray

string[] customerCountries =
    customers.Select(c => c.Country).Distinct().ToArray();

ToList

List<Customer> customersWithOrdersIn2005 =
    customers.
    Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
    ToList();

ToDictionary

Dictionary<int,Order> orders =
    customers.
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    ToDictionary(o => o.OrderID);
Dictionary<string,decimal> categoryMaxPrice =
    products.
    GroupBy(p => p.Category).
    ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));

ToLookup

Lookup<string,Product> productsByCategory =
    products.ToLookup(p => p.Category);
IEnumerable<Product> beverages = productsByCategory["Beverage"];

OfType

List<Person> persons = GetListOfPersons();
IEnumerable<Employee> employees = persons.OfType<Employee>();

Cast

      ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 =
    objects.
    Cast<Order>().
    Where(o => o.OrderDate.Year == 2005);
ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 =
    from Order o in objects
    where o.OrderDate.Year == 2005
    select o;

First

string phone = "206-555-1212";
Customer c = customers.First(c => c.Phone == phone);

Single

int id = 12345;
Customer c = customers.Single(c => c.CustomerID == id);

ElementAt

Product thirdMostExpensive =
    products.OrderByDescending(p => p.UnitPrice).ElementAt(2);

Range

int[] squares = Enumerable.Range(0, 100).Select(x => x * x).ToArray();
Repeat

long[] x = Enumerable.Repeat(-1L, 256).ToArray();

Empty

IEnumerable<Customer> noCustomers = Enumerable.Empty<Customer>();

Any

bool b = products.Any(p => p.UnitPrice >= 100 && p.UnitsInStock == 0);

All

IEnumerable<string> fullyStockedCategories =
    products.
    GroupBy(p => p.Category).
    Where(g => g.Group.All(p => p.UnitsInStock > 0)).
    Select(g => g.Key);

Count

int count = customers.Count(c => c.City == "London");

Sum

int year = 2005;
var namesAndTotals =
    customers.
    Select(c => new {
        c.Name,
        TotalOrders =
            c.Orders.
            Where(o => o.OrderDate.Year == year).
            Sum(o => o.Total)
    });

Min

var minPriceByCategory =
    products.
    GroupBy(p => p.Category).
    Select(g => new {
        Category = g.Key,
        MinPrice = g.Group.Min(p => p.UnitPrice)
    });

Max

decimal largestOrder =
    customers.
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    Max(o => o.Total);

Average

var averageOrderTotals =
    customers.
    Select(c => new {
        c.Name,
        AverageOrderTotal = c.Orders.Average(o => o.Total)
    });

Aggregate
var longestNamesByCategory =
    products.
    GroupBy(p => p.Category).
    Select(g => new {
        Category = g.Key,
        LongestName =
            g.Group.
            Select(p => p.Name).
            
Aggregate((s, t) => t.Length > s.Length ? t : s)
    });

Thursday, 26 June 2014

Learn Linq query in c#

Filtering
-----------------------------------------------------------------------------------------------------------------
var queryLondonCustomers = from cust in customers
                           where cust.City == "London" 
                           select cust;
 
queryLondonCustomers.Where(p=>p.Cust_code>50)
 
Ordering
------------------------------------------------------------------------------------------
var queryLondonCustomers3 = 
    from cust in customers
    where cust.City == "London" 
    orderby cust.Name ascending 
    select cust;
Grouping
-----------------------------------------------------------------------------------------
 var queryCustomersByCity =
      from cust in customers
      group cust by cust.City;

  // customerGroup is an IGrouping<string, Customer> 
  foreach (var customerGroup in queryCustomersByCity)
  {
      Console.WriteLine(customerGroup.Key);
      foreach (Customer customer in customerGroup)
      {
          Console.WriteLine("    {0}", customer.Name);
      }
  }
 
var custQuery =
    from cust in customers
    group cust by cust.City into custGroup
    where custGroup.Count() > 2
    orderby custGroup.Key
    select custGroup;
 
 Join
------------------------------------------------------------------------------------------
var innerJoinQuery =
    from cust in customers
    join dist in distributors on cust.City equals dist.City
    select new { CustomerName = cust.Name, DistributorName = dist.Name }; 

Monday, 24 February 2014

Restfull service in asp.net c#

 void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

config setting
----------------------------------------------------------------------------------------------
<system.serviceModel>
    <services>
      <service name="RestService" behaviorConfiguration="ServiceBehaviour">
        <endpoint address=""  binding="webHttpBinding" contract="IRestService" behaviorConfiguration="web" bindingConfiguration="crossDomain">
        </endpoint>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true"/>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true">
      <baseAddressPrefixFilters>
        <add prefix="http://www.example.com"/>
      </baseAddressPrefixFilters>
    </serviceHostingEnvironment>
    <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
  </system.serviceModel>
Sample Method
-----------------------------------------------------------------------------
[WebMethod]
    public string getdata(string user, string name)
    {
//Your code
return string
}

Sunday, 16 June 2013

Get Client IP using jQuery


  •  jsonip.com: is a free utility service that returns a client's IP address in a JSON object with support for JSONP, CORS, and direct requests. It serves millions of requests each day for websites, servers, mobile devices and more from all around the world.

All you need to do is to make a call to jsonip.com.

$(document).ready(function () {
    $.get('http://jsonip.com', function (res) {
        $('p').html('IP Address is: ' + res.ip);
    });
});

  • Smart-IP.net: Smart IP for today is one of the leading services providing to it's users all the required information about IP-addresses and everything related to them.

$(document).ready(function () {
    $.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
        $('p').html('My IP Address is: ' + data.host);
    });
});

Along with the IP address, this service also provide Geo location details as well like Country, latitude, longitude etc. Following are the properties which are returned as JSON response by this service.

data.host;
data.countryName;
data.countryCode;
data.city;
data.region;
data.latitude;
data.longitude;
data.timezone;

Thursday, 13 June 2013

How to find duplicate values in two columns in Excel?


1. In cell B1, input this formula: “=IF(ISERROR(MATCH(A1,$C$1:$C$13,0)),"",A1)”.
A1 is the column which you want to be compared.
$C$1:$C$13 is the range that you want to be compared with.
You can change the variables for what you are using.

2. Press the Enter key. Select cell B1, and then drag the fill handle over cell B15.

3. And all of the duplicate names will be displayed in column B. See screenshot:


doc-find-duplicates2