WCF Proxy & ClientBase

What happens if we add a service reference of WCF service using VS :

It creates a class that inherits from ClientBase<Type of Service Interface>, Service Interface.

Since it has to implement the Service interface methods, it has implementation as

this.Channel.ThatParticularMethod. here Channel is of type – Service interface. (protected TChannel Channel { get; })

Instead of using adding service reference, we can cosume WCF service using a generic class that connects to any method of it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.Configuration;

public class ServiceClient<T> : ClientBase<T> where T : class
{
    private bool _disposed = false;
    public ServiceClient()
        : base(typeof(T).FullName)
    {
    }
    public ServiceClient(string endpointConfigurationName)
        : base(endpointConfigurationName)
    {
    }
    public T Proxy
    {
        get { return this.Channel; }
    }
    protected virtual void Dispose(bool disposing)
    {
        if (!this._disposed)
        {
            if (disposing)
            {
                if (this.State == CommunicationState.Faulted)
                {
                    base.Abort();
                }
                else
                {
                    try
                    {
                        base.Close();
                    }
                    catch
                    {
                        base.Abort();
                    }
                }
                _disposed = true;
            }
        }
    }
}

& can make use of it as

protected void Page_Load(object sender, EventArgs e)
{
    using (ServiceClient<IService1> ServiceClient = 
           new ServiceClient<IService1>("BasicHttpBinding_IService1"))
    {
        this.Label1.Text = ServiceClient.Proxy.GetMessage();
        //once you have done the build inteli sense 
            //will automatically gets the new function
        this.Label2.Text = ServiceClient.Proxy.GetAddress();
    }
}

—————————————————————-

Can WCF be made Resfull

If so, why we need to make it? How we gonna make it?

How we gonna consume WCF REsful from angular js for instance.

Different bindings in WCF.

Difference between WCF & Web Api

Advertisements

SOAP, REST Services & HTTP

HTTP Vs SOAP

SOAP : Simple Object Access Protocol is a message protocol(format of the message) to describe how we can transport messages over network(a data exchange used protocol putting soap message inside the http body). More about a format. This is an xml format that looks little complex than that of HTTP message.SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages. It is a protocol for accessing web services which supports web service security features such as Reliable messaging, assertion and so on which http won’t. SOAP typically sent over HTTP, but could be sent over SMTP or even FTP(transoport protocol)

Http (HyperText Transfer Protocol) is a transfer used protocol, which called a stateless protocol. It is majorly a transport protocol that describes the way of tranporting the messages over network. It may use HTTP message format or SOAP message format or JSON or anyother.

———————————————————————-
SOAP Services & Rest services : 

Services :
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must “speak” the same “language”.

That’s where SOAP and REST come in. They are standard ways you’d pick communicate with the web-service. In One word to describe the difference, we can put it as Operation based Soap Service vs Resource based Rest service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
whereas REST just uses XML or JSON to send and receive data. WSDL Defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It’s highly dynamic unlike WSDL.

Problems with SOAP 

The SOAP offered an excellent way of transferring the data between the applications. but the problem with SOAP was that along with data a lot of other meta data also needs to get transferred with each request and response. This extra information is needed to find out the capabilities of the service and other meta data related to the data that is being transferred coming from the server. This makes the payload heavy even for small data. Also, Web services needed the clients to create the proxy on their end. These proxies will do the marshaling and un-marshaling of SOAP WSDL and make the communication between the application and the web service possible. The problem with this proxy is that if the service is updated and the proxy on the
client is not then the application might behave incorrectly.

REST:

REST is a design concept. REST doesn’t add any specific functionality to HTTP but is an architectural style that was developed alongside HTTP and most commonly uses HTTP for its application layer protocol.The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn’t as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:

  • GET: This maps to the R(Retrieve) part of the CRUD operation. This will be used to retrieve the required data (representation of data) from the remote resource.
  • PUT: This maps to the U(Update) part of the CRUD operation. This protocol will update the current representation of the data on the remote server.
  • POST: This maps to the C(Create) part of the CRUD operation. This will create a new entry for the current data that is being sent to the server.
  • DELETE: This maps to the D(Delete) part of the CRUD operation. This will delete the specified data from the remote server.

Flickr’s REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and either could be chosen. XML is thought of as being too verbose, and harder to parse, so many-a-times, data is more adequately represented using JSON. (E.g. serialization)

If you are looking for the most significant constraints of REST that distinguish a RESTful application from just any HTTP application, I would say the “self-description” constraint and the hypermedia constraint (aka Hypermedia as the Engine of Application State (HATEOAS)) are the most important.
The self-description constraint requires a RESTful request to be completely self descriptive in the users intent. This allows intermediaries (proxies and caches) to act on the message safely.
The HATEOAS constraint is about turning your application into a web of links where the client’s current state is based on its place in that web. It is a tricky concept and requires more time to explain than I have right now.

Finally

No. SOAP REST
1) SOAP is a protocol. REST is an architectural style.
2) SOAP stands for Simple Object Access Protocol. REST stands for REpresentational State Transfer.
3) SOAP can’t use REST because it is a protocol. REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.
4) SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
5) SOAP defines standards to be strictly followed. REST does not define too much standards like SOAP.
6) SOAP requires more bandwidth and resource than REST. REST requires less bandwidth and resource than SOAP.
7) SOAP defines its own security. RESTful web services inherits security measures from the underlying transport.
8) SOAP permits XML data format only. REST permits different data format such as Plain text, HTML, XML, JSON etc.
9) SOAP is less preferred than REST. REST more preferred than SOAP.

Linq Single vs SingleOrDefault vs First vs FirstOrDefault :

Single() SingleOrDefault() First() FirstOrDefault()
Description Returns a single, specific element of a sequence Returns a single, specific element of a sequence, or a default value if that element is not found Returns the first element of a sequence Returns the first element of a sequence, or a default value if no element is found
Exception thrown when There are 0 or more than 1 elements in the result There is more than one element in the result There are no elements in the result Only if the source is null (they all do this)
When to use If exactly 1 element is expected; not 0 or more than 1 When 0 or 1 elements are expected When more than 1 element is expected and you want only the first When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

Some ‘Difference’ concepts in sql server

Primary Key Vs Unique Key

PRIMARY KEY UNIQUE KEY
NULL It doesn’t allow Null values.
Because of this we refer
PRIMARY KEY = UNIQUE KEY + Not Null CONSTRAINT
Allows Null value. But only one Null value.
INDEX By default it adds a clustered index By default it adds a UNIQUE non-clustered index
LIMIT A table can have only one PRIMARY KEY Column[s] A table can have more than one UNIQUE Key Column[s]

 

Yet TO :

Varchar Vs NVarchar
Varchar Vs Varchar(MAX)
Char Vs Varchar
Union Vs Union All
DateTime Vs DateTime2
SET QUOTED_IDENTIFIER ON Vs OFF
Stored Procedure Vs User Defined Function
RAISERROR Vs THROW
Temporary Table Vs Table Variable
LEN() Vs DATALENGTH()
Sequence Vs Identity

Angular JS – Part2 : View, Controller & Scope

AngularJSImage.png

Angular JS is a javascript framework that allows to write client side code in MVC way.

View : It is pure UI cshtml pages with HTML/HTML5 markups, angular directives, filters & databindings & some CSS(3) & bootstrap classes bound. Preferably with no logic.

Controller : Its a container which has javascript code & which drives the logic of views. It ideally suppose to be independent of view & sameway view suppose to be independent of Controller when thinking from perspective of loose coupling & SOC principles. But View may refer to controller using including ng-controller directive inside div/body etc. Instead of giving the explicit mapping of controller in View, we can assign it during the routing. like -> $routeProvider.when(‘/CustomerDetails’, {templateUrl: ViewName, controller : ‘JsControllerName’}); Instead of giving the direct ViewName, if we are using MVC combo, we can use MVC routing too to controller/ActionMethod that returns the view. It looks like $routeProvider.when(‘/CustomerDetails’, {templateUrl : $location.pathname + “Controller/ActionMethod”, controller : ‘JsControllerName’});

Ambiguity regarding Controller : Since it has mostly binding logic of View usinf $scope, some call it ViewModel, since it deals with presentation logic, some call it a presenter. So we may call it as whatever. MVW -> ModelViewWhatever.

———————————————————————

Scope : Its a glue between view & controller. This is something similar to ViewModel which we fing in MVVM architectures. Scope is a javascript object that contains the properties & functions related to particular View. It is an input to the Controller.

“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered or when controller is mapped to certain view. Its scope & memory is with in controller.

MyApp.controller (‘MyController’, function($scope) {

$scope.input1= 1;

$scope.input2=3;
$scope.output ;
$scope.Calc = function()
{
$scope.output = $scope.input1 + $scope.input2;
}
});

Wotver tagged to ng-model in View, all those fields are inherently available in controller via scope.

———————————————————————

$rootScope :

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.

  • Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
  • Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
  • Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
  • Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

——————————————————————–

Data Binding in Angular :

Its two way binding. So whenever you make changes in one entity the other entity also gets updated. we use ng-model, ng-bind for databinding.

———————————————————————

Compile & Link Phases :

At the heart Angular framework is a parser. A parser which parses the Angular directives and render’s HTML output.

Angular parser works in 3 steps:-

Step 1:- HTML browser parses the HTML and creates a DOM (Document Object Model).

Step 2:- Angular framework runs over this DOM looks at the Angular directives and manipulates the DOM accordingly.

Step 3:- This manipulated is then rendered as HTML in the browser.

Now the above angular parsing is not so simple as it looks to be. It occurs in two phases “Compile” and “Link”. Firs the compile phase occurs then the link phase.

In compile phase the angular parser starts parsing the DOM and whenever the parser encounters a directive it create a function. These functions are termed as template or compiled functions. In this phase we do not have access to the $scope data.

In the link phase the data i.e. ($scope) is attached to the template function and executed to get the final HTML output.

Angular JS Part1

1) What & Features
Angular JS is an javascript application framework to build large responsive web applications.
*It aids for building SPA’s & helps in its easy maintenance.
*Supports Client side code in MVC pattern, so SOC (seperation of concerns)
*Twoway data binding so Rich UI :AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.
*Cross browser complaint
*Dependency Injection in built
*Code reuse via Services & Factories
*Dom dynamic manupulation using JQLITE

2) Advantages & Cons
Advantages :
————-
*Easy to build & develop applications
*MVC, so SOC & testable
*Rich UI as two way data binding
CONS
—-
*No security inbuilt. Have to seek server side code support.
*If javasccript disabled, whole application doesn’t work anymore.

3) SPA
———-
Its, instead of page redirects & posting for server for loading each pages, it is in shell, we tend to load partial views with out flickering effect. Which benefits the mobile & tablet views.

4) Directives : It is a way to teach HTML new tricks. They can be attributes, tags, markers.
Example : ng-app : to mark an application as angular & start of it.
ng-model : this adds a property in scope which has enabled two way binding.
ng-Controller : to specify the controller
ng-init : to initialise the objects
ng-repeat : foreach loop to repeat the elements
ng-bind : to bind the data

5) Filters : These are the way we manupulate the data that is bound to the control. |Uppercase, |lowercase, |currency, |number : 2, |filter :, | orderBy :

6) Expressions : The double braced {{}} statements to help displaying the outputs sometimes. No Conditional statements allowed. {{firstName + lastName}}