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.