Saturday, 6 February 2016

OOPS Concept with Real-world example

Introduction




OOP is Nothing but Object Oriented Programming.According to Wikipedia,  Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs.

OOPs have following features

1. Object   - Instance of class
2. Class    - Blue print of Object
3. encapsulation  - Protecting our data
4. polymorphism   - Different behaviors at diff. instances
5. abstraction    - Hidding our irrelavance data
6. inheritence    - one property of object is aquring to another property of object

1. Object
Basically an object is anything that is identifiable as an single material item. You can see around and find many objects like Camera, Monitor, Laptop etc. In OOP perspective, an object is nothing but an instance of a class that contains real values instead of variables

2. Class

A class is a template definition of the methods and variables for a particular kind of object. In other words, class is the blue print from which an individual objects are created.

every human has eye ,so eyecolor can be considered as the property of human being which can be encapsulted as a data in our class Human

class Human

{

    private:

    EyeColor IColor;

    NAME personname;

};


Consider object of class of
                Human myhuman;

we want set myhuman's name as "linto" and IColor as "black", For that we want methods to do that task.

So need methods for class to do a particular task on the data

class Human

{
    private:

    EyeColor IColor;

    NAME personname;

    public:

    void SetName(NAME anyName);

    void SetIColor(EyeColor eyecolor);

};


3. Abstraction

Abstraction is a process of identifying the relevant qualities and behvaiors an object should possess. Lets take an example to understand abstraction. A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antena, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antena, speakers works.  You just need to know how to operate the laptop by switching it on. The intrinsic details are invisitble. Think about if you would have to call to the engineer  who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone. So here the Laptop is an object that is designed to hide its complexity.

Think If you need to write a piece of software to track the students details of a school, you may probably need to create Students objects. People comes in all different backgrounds, educational qualifications, locations, hobbies, ages and have multiple religion, language but in terms of application, an student is just a name, age, class and roll number, while the other qualities are not relevant to the application. Determining what other qualities (background, qualifications, location, hobbiels etc) are in terms of this application is abstraction.

In object-oriented software, complexity is managed by using abstraction. Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex detilals. A well thought-out abstraction is usually simple, and easy to use in the perspective of the user, the person who is using your object.

4. Encapsulation

Encapsulation is a method for protecting data from unwanted access or alteration by packaging it in an object where it is only accessible through the object's interface. Encapsulation are often referred to as information hiding. But both are different. Infact information hiding is actually the result of Encapsulation. Encapsulation makes it possible to separate an object's implementation from its orgiinal behavior - to restrict access of its internal data. This restriction facilitate certains detiails of an object;s behavior to be hidden. This allows to protect an object's interal state from corruption by its user.

It is the mechanism by which Abstraction is implemented. In other words you can say that it is the result of the Encapsulation. For example,  the Laptop is an object that encapsulates many technologies/hardwares that might not be understood clearly by most people who use it.
Inheritance

5. Inheritance

Inheritance is the ability to define a new class or object that inherits the behaviour and its functionality of an existing class. The new class or object is called a child or subclass or derived class while the original class is called parent or base class. For example, in a software company Software Engineers, Sr. Software Engineers, Module Lead, Technical Lead, Project Lead, Project Manager, Program Manager, Directors all are the employees of the company but their work, perks, roles, responsibilities differs. So in OOP, the Employee base class would provide the common behaviours of all types/level of employee and also some behaviours properties that all employee must have for that company. The particular sub class or child class of the employee would implement behaviours specific to that level of the employee. So by above example you can notice that the main concept behind inheritance are extensibility and code reuse (in this case you are extending the Employee class and using its code into sub class or derived class).

6. Polymorphism

As name suggests, Polymorphism means an ability to assume different forms at different places. In OOP, it is a language's ability to handle objects differently based on their runtime type and use. Polymorphism is briefly described as "one interface, many implementations".Ppolymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

There are two types of polymorphism.

  •     Compile time polymorphism - It is achieved by overloading functions and operators

  •     Run time polymorphism - It is achieved by overriding virtual functions

Lets say you have a class that have many Load methods having different parameters, this is called Compile time polymorphism. Lets take another example where you have a virtual method in the base class called Load with one parameter and you have redefined its functioanlity in your sub class by overriding base class Load method,  this is called Run time polymorphism.


Thursday, 4 February 2016

How to create Custom Filters in AngularJS

Have you ever used filters with the ng-repeat directive as shown in the listing below?













{{a.name}}{{a.price}}






If so, then you’ve used a filter in an AngularJS application. AngularJS provides us many in-built directives like search. If required, AngularJS also allows us to create custom filters, which we’ll explore in this post.

AngularJS gives us a simple API to create a custom filter. You’ll remember that we use app.controller() to create controllers and app.module() to create modules. In exactly the same way, AngularJS has given us the angular.filter API to create a custom filter in AngularJS.

A custom filter can be created using the following syntax:





To create a custom filter, you need to do the following steps:

  • Create a filter using the app.filter by passing a custom filter name and a function as input parameters to the app.filter()

  • App.filter() will return a function

  • The retuned function can take various optional input parameters

  • The returned function will have custom filter code and it will return the output.



Let us start with creating a very simple custom filter. We can apply this custom filter on a string and it will return the string with each character in capital case.

MyApp.filter('toUpperCase', function () {



return function (input)

{

var output = "";

output = input.toUpperCase();

return output;

}

})



We can use the toUpperCase custom filter in the view as shown the listing below:













{{a.name|toUpperCase}}{{a.price}}






We need to keep in mind that the name of the custom filter is case sensitive. The above created view is reading data from the controller as shown the listing below:

MyApp.controller("ProductController", function ($scope) {



$scope.products = [

{ 'name': 'pen', 'price': '200' },

{ 'name': 'pencil', 'price': '400' },

{ 'name': 'book', 'price': '2400' },

{ 'name': 'ball', 'price': '400' },

{ 'name': 'eraser', 'price': '1200' },

];



})



Now we’ll get the product name rendered in capital case on the view as shown in the image below:

The filter we created above does not take any input parameter, but let us say we want one there. This can be done very easily.  In the above filter we are returning each character of the string in upper case. In the next filter we will pass the position and only the character at that position will be converted to capital. So the filter which takes input parameter can be created as shown in the listing below:

MyApp.filter('toPositionUpperCase', function () {



return function (input,position)

{

var output = [];

var capLetter = input.charAt(position).toUpperCase();

for (var i = 0; i < input.length; i++) {



if (i == position) {

output.push(capLetter);

} else {

output.push(input[i]);

}



}

output = output.join('');

return output;

}

})



We can use toPositionUpperCase custom filter in the view as shown the listing below. As you will notice that we are passing the input parameter to the custom filter using the colon.













{{a.name|toPositionUpperCase:1}}{{a.price}}




We will get the second letter of product name rendered in the capital case on the view as shown in the image below:



Before we conclude this article, let us create a custom filter which will be applied on the collection of items. Let us say from the list of products, we want to filter all the products greater than a given price. We can write this custom filter as shown in the listing below:

MyApp.filter('priceGreaterThan', function () {



return function (input, price) {

var output = [];

if (isNaN(price)) {



output = input;

}

else {

angular.forEach(input, function (item) {



if (item.price > price) {

output.push(item)

}

});

}

return output;

}

})



We can use the custom filter on the view as shown in the listing below. We are passing the price parameter from the input type text box.

<h1>With Custom Filter</h1>



















{{b.name}}{{b.price}}






With this we will get a filtered array on the view as shown in the image below:

So there you have it – that’s how to create a custom filter! It’s easy – they’re nothing but functions that take one input and optional parameters to return a function. I hope you enjoyed reading!

Difference between Abstract class and Interface in Asp.Net

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.



What is an Interface

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.



























































Feature


Interface


Abstract class


Multiple inheritance


A class may inherit several interfaces.


A class may inherit only one abstract class.


Default implementation


An interface cannot provide any code, just the signature.


An abstract class can provide complete, default code and/or just the details that have to be overridden.


Access Modfiers


An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public


An abstract class can contain access modifiers for the subs, functions, properties


Core VS Peripheral


Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.


An abstract class defines the core identity of a class and there it is used for objects of the same type.


Homogeneity


If various implementations only share method signatures then it is better to use Interfaces.


If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.


Speed


Requires more time to find the actual method in the corresponding classes.


Fast


Adding functionality (Versioning)


If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.


If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.


Fields and Constants


No fields can be defined in interfaces


An abstract class can have fields and constrants defined



 I have explained the differences between an abstract class and an interface.

I think it helps you  

Sunday, 24 January 2016

Read XML Nodes in C#

Select XML Nodes by Name [C#]


To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodesreturns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode findsthe first node that matches the XPath string.

Suppose we have this XML file.

[XML]
<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply indexXmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

Resignation letter without notice period

Dear Sir/Mam,

This email is to notify you that I am resigning my position with [Comapany name] due to suffering from jaundice which will require extended treatment and recovery, and I am unsure that my ability to perform the duties of my present position will return.

I apologize for the inconvenience that I may be causing to [Comapany name], but I think it is the right thing to do at this moment of time. I want to thank you for all the support and encouragement you have always given me.

Again, it has been a pleasure working with you and I want to wish everyone at [Comapany name] the best of luck for the future.

Your's sincerely
[Your name]

Mail after an interview

Dear Sir,Mam,

I am writing to thank you for taking the time to interview me on [DATE] and to confirm my interest in the [NAME OF POSITION] job.

I was really impressed with the company and the job and, as I explained in the interview, I think I’d be well suited to the role.

[At this stage you could do a few bullet points to show the key skills you have that fit the job]
I look forward to hearing from you once you reach a decision. In the meantime, if you have any questions for me at all please do not hesitate to call me on [YOUR NUMBER].
Kind regards,
[YOUR NAME]

Monday, 18 January 2016

XML parser in C#

Select XML Nodes by Name [C#]


To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodesreturns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode findsthe first node that matches the XPath string.

Suppose we have this XML file.

[XML]
<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply indexXmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

Sunday, 17 January 2016

Understanding the Basics of Web Service in ASP.NET

This article aims at understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Background


Connectivity between applications is very important. Connectivity in any case is very important for that matter but it specially is very important between applications. Connecting web application used to be a big challenge before the advent of technologies like SOAP (Simple Object Access Protocol). The reason it was so difficult was, there were so many technologies people were working in. The applications were hosted on different types of servers, etc. But these things should not be a barrier to facilitate the communication between applications. The only requirement was to have some standards to follow and standard ways of doing things so that the applications become capable of communicating with other applications irrespective of the technologies used.

SOAP and Web Services


SOAP and XML created the solution for the problem that developers were facing before. SOAP is a standard XML based protocol that communicated over HTTP. We can think of SOAP as message format for sending messaged between applications using XML. It is independent of technology, platform and is extensible too.

We have SOAP and XML to give us connectivity between applications. Does it mean that I have to write XML and SOAP specific things myself to facilitate this communications? I could do that but that will be very time consuming and sometimes error prone too.

Where does Web Services come in picture? Well, Web services is the mechanism that ASP.NET framework provides to make it easy for us to write code to facilitate connectivity between applications. As ASP.NET developer, If I need an application that will be used by many other applications then I can simply decide to write a web service for it and ASP.NET framework will take care of doing the low level SOAP and XML work for us.

The other side of the coin is, if our ASP.NET application wants to use a web service, i.e., an application that is providing me SOAP based interface for communication. So what we are going to do now is write a small Web service to see how we can have our application communication-ready for other applications and secondly, we will try to consume a webservice to understand how we can use other applications from our application.

soap

 

Creating a Web Service


Let us write a simple module that will provide basic arithmetic operations to other applications. The user of our application will have to provide us 2 numbers and we will perform the requested operation like Addition, Subtraction and Multiplication.

So, the first thing we need to do is to create our web service. We can do this by creating a website of type ASP.NET Web service. This will give us a skeleton to write our web service code in.

The attribute WebServicetells that this class contains the code for web service. The namespace is what is used to identify the web service. The WebMethodattribute specifies the methods which our web service is providing.

Let us now go ahead and write code to have our functions in this webservice.

We have a very basic web service implemented which can let the user have some basic arithmetic operations. Now to create the WebServicebinary, we will have to use the following command on Visual Studio Command Prompt.

This will create a DLL file for our web service. This DLL file can be used by any client by using the SOAP protocol. If we need to test our web service for how it works over the SOAP protocol, we can view the service.asmx file in the browser and see what functions our web service is exposing.

asmx

 

We can even test these methods here and see the XML file that contains the service description.

Consuming a WebService


There are three ways we can consume a WebService:

  1. Using HTTP-POST method.

  2. Using XMLHttpthat will use SOAP to call our the service

  3. Using WSDL generated proxy class


The HTTP-Post method can be used by calling .asmx file directly from client. We can directly use the method name and the parameter names will be taken from our input fields on form.

When this form get submitted, the web service’s method will be called. The second method where we can use the XMLHttpover SOAP to access the webservice is used when we want to use the web service using full capability of SOAP.

The third way of using the web service is by generating a Proxyclass for the web service and then using that proxy class. This method is, to me, more type safe and less error prone as once we have the proxy class generated, it can take care of SOAP messages, serialization and ensure that all the problems can be handled at compile time instead of runtime.

To use this service, we need to do “Add Web reference” and add the webservice reference. Alternatively I can also use WSDL.exe, a command line tool, to generate the proxy classes and use them. “Add web Reference” is also using the same WSDL.exe to generate the proxy classes.

 

addref

Now let us write some code to use the proxy class to perform the operations, the proxy class will then communicate to the web service using SOAP and get back the results to us.

Let us run the website to see the results

running

 

Points of Interest


We saw how to create a web service in ASP.NET and how we can consume a web service in ASP.NET. One interesting area that we did not see here is how we can use web service from AJAX. ASP.NET also provides a mechanism using scriptManagerthat will generate the JavaScript proxy for a webservice and we can use it to call the webservice methods. Also, if we want to customize the security of our web service, we can do that too using custom SOAP headers.

Saturday, 16 January 2016

What is Unit Testing and Why to use it?

Unit testing is a way to test each piece of your code which is called as unit. The idea behind the unit testing is to ensure the quality of each smaller unit. It verify the functional behavior of each unit in response to correct and incorrect cases of input data and verify any assumptions made by the code. Unit test cases are usually written by the developer who has written that code unit.


Developers can also use test frameworks as per their programming languages or frameworks of code, to make writing and running unit tests easier.

For example, .NET developers use NUnit, XUnit and third-party mock-object libraries such as Rhino mocks, Type mocks or NMock to write and running unit tests.

Visual Studio Test Explorer


Visual Studio Test Explorer is designed for developers to run your unit tests and view their results in Visual Studio. It can be used to run tests written in .NET languages (C#, VB.NET) and other programming languages like javascript or JS framework like AngularJS with the help of Visual Studio Extension.

You can download these third party testing extensions from Visual Studio gallery.

Test Explorer views display all of your tests - passed, failed, not run yet, or skipped. You can also do filter or search for a specific test in Test Explorer view at the global level or by selecting one of the pre-defined filters.

Why Unit Testing?


Unit tests reduce number of bugs, provide accurate documentation, and improve design. There are following reasons to choose unit testing.

  1. Allow you to make big changes into code quickly since you know it's tests are working as expected and when you make the changes you need to write and run tests again to get it work.

  2. Reduce the number of bugs in production code.

  3. Help you to understand the design of the code since to write tests you need to outline all the conditions with respect to your code and what outputs you are expecting from the code.

  4. Allow refactoring of code at any time without fear of breaking existing code. In this way it make the coding process more agile.

  5. Ensure functional behavior of your code since all the tests have been passed.


What do you think?

I hope you will enjoy Unit Testing for writing a better code. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Calling Cross Domain WCF Service using Jquery

From last couple of days, I was trying to call a wcf service using jquery that is hosted in different domain. But every time I was failed to call wcf service from different domain. After spending much time on R&D, I found the solution and the reason why I was unable to call cross domain wcf service.

Whenever you try to call a cross domain WCF Service by javascript or jquery, it behaves differently with different browsers. When you want to perform "POST" or "GET" request on cross domain wcf service or normal service using jquery/javascript or ajax, the browser actually sends an "OPTIONS" verb call to your wcf service that is not mention in your wcf method attribute. We mention there "POST" or "GET" to call a wcf service method. Hence we get error to call cross domain wcf service. We find the following request and response headers in firefox when we try to call wcf service.

Request Headers



  1. OPTIONS http://myserver/MyService.svc/GetStates HTTP/1.1

  2. Host: 192.168.4.156 User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0

  3. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

  4. Accept-Language: en-us,en;q=0.5

  5. Accept-Encoding: gzip, deflate

  6. Proxy-Connection: keep-alive

  7. Origin: http://192.168.4.156:90

  8. Access-Control-Request-Method: OPTION

  9. Access-Control-Request-Headers: content-type

  10. Pragma: no-cache

  11. Cache-Control: no-cache

Response Headers



  1. HTTP/1.0 405 Method Not Allowed

  2. Cache-Control: private

  3. Allow: POST

  4. Content-Length: 1565

  5. Content-Type: text/html; charset=UTF-8

  6. Server: Microsoft-IIS/7.0

  7. X-AspNet-Version: 4.0.30319

  8. X-Powered-By: ASP.NET

  9. Access-Control-Allow-Origin: *

  10. Access-Control-Allow-Headers: Content-Type

  11. Date: Fri, 04 May 2012 12:05:17 GMT

  12. X-Cache: MISS from c1india.noida.in

  13. X-Cache-Lookup: MISS from c1india.noida.in:3128

  14. Via: 1.0 c1india.noida.in:3128 (squid/2.6.STABLE21)

  15. Proxy-Connection: close

In above request headers the method is "OPTION" not "POST" and the response headers has content-type "text/html; charset=UTF-8" instead of "json;charset=UTF-8". To change these options we need to do some changes in web.config of hosted wcf service.

Configure WCF Cross Domain service



  1. namespace CrossDomainWcfService

  2. {

  3. [DataContract]

  4. public class Supplier

  5. {

  6. [DataMember] public string Name;

  7. [DataMember] public string Email;

  8. }

  9. [ServiceContract(Namespace = "")]

  10. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

  11. public class MyService

  12. {

  13. [OperationContract]

  14. [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

  15. List GetSuppliers (int OrgID)

  16. {

  17. // Fetch data from database var q= (from tbl in mobjentity.Customer

  18. where tbl.OrgID=OrgID).ToList();

  19. Listlst= new List();

  20. foreach(var supp in q)

  21. {

  22. Supplier msupp=new Supplier();

  23. msupp.Name=supp.Name;

  24. msupp.Email=supp.Email

  25. //Make Supplier List to retun

  26. lst.Add(msupp);

  27. }

  28. return lst;

  29. }

  30. }

  31. }

WCF Service Web.config



  1. <system.webServer>

  2. <modules runAllManagedModulesForAllRequests="true" />

  3. <httpProtocol>

  4. <customHeaders>

  5. <add name="Access-Control-Allow-Origin" value="*" />

  6. <add name="Access-Control-Allow-Headers" value="Content-Type" />

  7. </customHeaders>

  8. </httpProtocol>

  9. </system.webServer>

  10. <system.serviceModel>

  11. <behaviors>

  12. .

  13. .

  14. .

  15. </behaviors>

  16. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

  17. <standardEndpoints>

  18. <webScriptEndpoint>

  19. <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />

  20. </webScriptEndpoint>

  21. </standardEndpoints>

  22. <services>

  23. .

  24. .

  25. </service>

  26. </services>

  27. <bindings>

  28. .

  29. .

  30. </bindings>

  31. <client>

  32. .

  33. .

  34. </client>

  35. </system.serviceModel>

Global.asax Code


You can also define your hosted service web.config setting in Global.asax file. If you have defined setting in web.config then there is no need to do here.

  1. protected void Application_BeginRequest(object sender, EventArgs e)

  2. {

  3. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , ”*”);

  4. if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )

  5. {

  6. //These headers are handling the "pre-flight" OPTIONS call sent by the browser

  7. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );

  8. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );

  9. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" );

  10. HttpContext.Current.Response.End();

  11. }

  12. }

Wcf calling using Jquery



  1. $.ajax({

  2. type: "Post"

  3. url: "http://www.yourdomain.com/MyService.svc/GetSuppliers", // Location of the service

  4. data: '{"OrgID"="1"}', //Data sent to server

  5. contentType: "application/json;charset-uf8", // content type sent to server

  6. dataType: "json", //Expected data format from server

  7. success: function (msg) {

  8. //Implement get data from service as you wish

  9. },

  10. error: function (err) {

  11. // When Service call fails

  12. }

  13. });

Note



  1. You can define cross domain setting either in web.config or in global.asax file of your wcf service.

  2. For running the code, make a virtual directory/web application on IIS and map the code folder to it.

Summary

In this article I try to explain cross domain wcf service calling with example. I hope after reading this article you will be able to call cross domain wcf service. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article. You can download demo project from below link.