Showing posts with label web services. Show all posts
Showing posts with label web services. Show all posts

Sunday, September 25, 2011

WCF Interview questions and answers (reference only, uuber level)

The intent to draft this list of questions is for learning purpose only and at very high level understanding of WCF services. This is not a dump :)

Question 1: What is the difference WCF and Web services?
Answer: -
Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
Question 2: What are different bindings supported by WCF?
Answer: -
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just incase you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.
BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.
WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.
NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.
NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.
NetNamedPipesBinding:-Ths binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.

Note: - An interprocess control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.

Question 3: What are the main components of WCF?
Answer: -
We need to define three main components in WCF:-
• Service class. • Hosting environment • End point

Question 4: What are the various ways of hosting a WCF service?
Answer: -
There are three major ways to host a WCF service:-
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.

Question 5: What is a service level message and transport level message?
Answer: -
You can log WCF message at two levels one is service level and the other is transport level. Service level:-In this the messages are logged as they enter the user code or leave the user code. Transport level: - In this the messages are logged as they are ready to be encoded / decoded. All transport level, infrastructure messages and also reliable messaging is logged. You specify the message levels in the diagnostics node as shown in the below code snippet.

Question 6: For which bindings are transport, message and mixed mode supported?
Answer: -
Below is a table which shows for which binding which mode is supported. We did not discuss the mixed mode. It’s nothing but combination of transport and mixed mode. For instance data encrypted and passed over WsHttp using HTTPS is a mixed mode of security. Encryption is nothing but message security and HTTPS is a transport mode. In a combination they form mixed mode.

Question 7: Which bindings in WCF support the message streaming?
Answer: -
Following bindings supports the streaming in WCF:
1. basicHttpBinding 2. netTcpBinding 3. netNamedPipeBinding

Question 8: What are the various ways of hosting a WCF Service?
Answer: - 1.IIS 2.Self Hosting 3.WAS (Windows Activation Service)

Question 9: What is the use of ServiceBehavior attribute in WCF ?
Answer: -
ServiceBehaviour attribute is used to specify the InstanceContextMode for the WCF Service class (This can be used to maintained a state of the service or a client too).

There are three instance Context Mode in the WFC PerSession : This is used to create a new instance for a service and the same instance is used for all method for a particular client. (eg: State can be maintained per session by declaring a variable) PerCall : This is used to create a new instance for every call from the client whether same client or different. (eg: No state can be maintained as every time a new instance of the service is created) Single : This is used to create only one instance of the service and the same instance is used for all the client request. (eg: Global state can be maintained but this will be applicable for all clients)

Question 10: How the concurrency mode is specified in WCF service?
Answer: - The concurrency mode is specified using the ServiceBehavior attribute on the class that implements the service. Ex. [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)] Public class ServiceClass : IServiceInterface{ //Implementation Code } There are 3 possible values of ConcurrencyMode enumeration Single Reentrant Multiple.

Question 11: hat the different transaction options ?
Answer:-

We can specify transaction in 3 ways in WCF:-
TransactionFlowOption.NotAllowed This is a default option. Using this option no transaction will be propagated across the binding. If any client attempts to call the WCF service in a transaction it will be ignored for this option. This option specifies that client can call this WCF service in a transaction. It’s not compulsory that the service needs to be called in a transaction. You can call without the transaction also. TransactionFlowOption.Mandatory This option specifies that client must call the WCF service in a transaction mode. If the WCF service is called without transaction, ‘FaultException’ will be raised.

Question 12: Wat are the advantages of hosting WCF Services in IIS as compared to self-hosting?
Answer: - There are two main advantages of using IIS over self-hosting:-


Automatic activation IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running.
Process recycling If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you loose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system. In case of self-hosting both the above features, you will need to code yourself.

Question 13: What is trace listener?

Answer - ‘Tracelistener’ are objects that get tracing information from the trace class and they output the data to some medium. For instance you can see from the figure ‘TraceListener’ how it listens to the trace object and outputs the same to UI, File or a windows event log. There are three different types of ‘tracelistener’ first is the ‘defaulttracelistener’ (this outputs the data to UI), second is ‘textwritertracelistener’ (this outputs to a file) and the final one is ‘Eventlogtracelistener’ which outputs the same to a windows event log.

Question 14: What is service host factory in WCF?
Answer-

1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.
2. This is useful when we need to implement the event handlers for opening and closing the service.
3. WCF provides ServiceFactory class for this purpose.

Question 15: What are the advantages of hosting WCF service in WAS?

Answer- WAS (Windows Activation Service) is a component of IIS 7.0. Following are few advantages : 1. We are not only limited to HTTP protocol. We can also use supported protocols like TCP, named pipes and MSMQ 2. No need to completely install IIS. We can only install WAS component and keep away the WebServer.

Question 16: In WCF which bindings supports the reliable session?

Answer- In WCF, following bindings supports the reliable session - 1. wsHttpBinding 2. wsDualHttpBinding 3. wsFederationHttpBinding 4. netTcpBinding

Reference - Prasham on dotnetfunda.com and Pro WCF: Practical Microsoft SOA Implementation -- Chris and Denis Mulder – Apress 2007.

- DJ

Friday, September 23, 2011

Asp.net migration to Sharepoint

ASP.NET web developers who are moving to SharePoint site creation. This article will explain in detail how an ASP.NET webpage developed in Visual Studio can be converted into a SharePoint site. If there is a requirement for a website created in Visual Studio, just the old fashioned way with the code-behind logic and other layers like Data Access and Business Logic, to be converted into a SharePoint site, and still make it work the same way with the same code-behind, you are in the right place. The article here along with the code explains 3 core steps that will help you to transform your ASP.NET Web Application into a SharePoint site. Step1: Add a Web Deployment Project to your website solution that will create a single DLL for the website. This step will give us the code-behind DLL and other dependency DLLs for the website. Step2: Copy the bin folder items (DLLs) into the SharePoint site, and tweak the web configuration file of the SharePoint site to use the copied DLLs. Step3: Open your created SharePoint site in SharePoint Designer and import the web pages from our web application and link it to the appropriate DLLs. Code and detail step by step instructions on code project - http://www.codeproject.com/KB/sharepoint/ASPNET_to_Sharepoint.aspx There are more instructions @ http://aspnet2sp.codeplex.com/ http://weblogs.asp.net/bsimser/pages/spsmigration.aspx

Wednesday, September 21, 2011

Build 2011 microsoft @ Anaheim

Build day 1 Key notes and Session videos here -
http://channel9.msdn.com/events/BUILD/BUILD2011/KEY-0001

Speakers: Chris Jones , Steven Sinofsky , Antoine Leblonde , Mike Angiulo , Julie Larson-Green

Build day 2 Key notes and Session videos here -
http://channel9.msdn.com/events/BUILD/BUILD2011/KEY-0002
Speakers: Scott Guthrie , Jeff Sandquist , John Shewchuk , Steve Ballmer , Jason Zander , Bryon Surace , Satya Nadella , Dan Fernandez

Covered topics include -
o Windows Server 8, Azure,
o Virtualization & Cloud
o Identity & secure access
o VS 2011 Developer Preview, Windows Azure SDK, Windows Azure Toolkit 1.5 available
• Application lifecycle management
• Visual Studio TFS on Azure as SAAS

Device + Cloud
• Advance debugging in windows azure - (ability to do performance profiling on code deployed)
• Feature: Find Matching Clones(find copies of source code)
o Alpha blending etc

Web and Mobile Reach - ASP.Net MVC 4 Preview
• Page Inspector/DOM Explorer/Source View
• Unification/Bunding feature, folder reference
• jQuery.Mobile.MVC
• Shipping jquery as part of ASP.Net/Visual Studio 11

Windows Server 8
• High availability built into win8
• Ability to move private network to cloud along with IP infrastructure
More on Channel9 videos here - http://channel9.msdn.com/events/BUILD/BUILD2011

Wednesday, May 21, 2008

Best Practices for implementing web services

Here's a codeproject article I went through for best practices for implementing web services (worth a read) - http://www.codeproject.com/KB/cpp/Web_Services.aspx

Thanks - Dipesh

Wednesday, February 13, 2008

How to post xml file or any other file onto server through .net web services?

I was in Dallas last week and working on a release of which i was not supposed to be part of it initially and then working on a Silverlight contest (still working.) btw, you too can take part in the Silverlight contest by Microsoft here -
http://silverlight.net/Showcase/

Regardless, working little bit more on web services i figured that it is absolutely ok to pass XMl as a set of string data through .net web service.
Also, i found this interesting simple article on how to upload XML or for that matter any file onto server - http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx

HTH, Thanks - Dipesh

Calling .net web service through HTTP Post

Below are the steps how you would call a web service from .net code through HTTP POST -

Dim oXmlhttpCaller as Object;

' Create Object of MSXml2.XMLHTTP
Set oXmlhttpCaller = Server.CreateObject("Msxml2.XMLHTTP")

'oXmlhttpCaller.open "GET","http://localhost/HelloWorld/Service.asmx/HelloWorldWit'hCustomMessage?s_msg= Hope you like this article.", False

oXmlhttpCaller.open "POST","http://localhost/HelloWorld/Service.asmx/
HelloWorldWithCustomMessage", False

oXmlhttpCaller.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXmlhttpCaller.send("Msg= Hello World!")

HTH, in my next post i wiill try and show how to send XML message as part of your input paramter. Thanks - Dj

Thursday, January 10, 2008

Calling web services from remote machines easy way: Test environment

If you are faced with the web service error while invoking the service from remote machine, by default, it would display the message "The test form is only available for requests from the local machine."

Add this piece of section in your web.config to enable your web service to be invoked from remote machines,
Add the following settings to the Web.Config file of the Web Service -

(XML start << and >> signs are not visible...dont know how to do that with this blogger editor!)
system.web
webservices
protocols
add name="HttpGet"
add name="HttpPost"
/protocols
/webservices>
/SYSTEM.WEB

This would enable the Web service to be able to be invoked from remote machine. This setting would only be useful in development / testing scenarios and it is advisable to remove /comment the above section when releasing for production, due to security reasons.
HTH - DJ

Tuesday, January 08, 2008

Generate code from WSDL/XSD from Visual Studio 2005

In my search of doing my job faster in the development of web services i found this pretty helpful tool: WSCF - Web Services Contract First. This helps us generating .net code (C#, vb.net) from WSDL, XSD and so on. You can generate proxy classes for .net/java or any other client and also .net web service - server side code all from Visual Studio 2005.

You can find the latest version here- http://www.thinktecture.com/media/7478/wscf0.7.zip
You can find the walkthrough document here - http://www.thinktecture.com/resourcearchive/tools-and-software/wscf/wscf-walkthrough

Thanks - Dipesh

Friday, January 04, 2008

Improve web service performance

Mike has posted a nice article that helps one achieve faster web service performance by compressing SOAP. Read here - http://www.dotnetjunkies.com/Article/46630AE2-1C79-4D5F-827E-6C2857FF1D23.dcik

You may want to peek at Microsoft's article as well - http://msdn2.microsoft.com/en-us/library/s25h0swd.aspx

Hope that helps. - DJ

Wednesday, January 02, 2008

XSDObjectGen - nested schema (imports) error with XSD.exe tool

If you read my previous post http://archdipesh.blogspot.com/2008/01/xml-xsdexe-usage-tips.html you may be good if you are using a simple XSD file (no nesting). But if i have multiple XSD files and they are all nested then there is a problem! Using XSD.exe tool doesn't help and fails for nested schema files.

It seems XSD.exe doesn’t seem to recognize element when generating code file...and it spits out the error ... "Class generation failed, cannot recognize root element". If you are facing the same error remove imports element from the XSD just include the namespace and try specifying multiple XSD file names from the command line while executing xsd.exe tool.

OR ... sweet way would be to look at XSDObjectGen tool. This is pretty exhaustive and can handle imports/mutiple xsd files easily. (though one level down). This code can then be used as a class exposed by web services.
Download Sample Code generator from here - http://www.microsoft.com/downloads/details.aspx?familyid=89e6b1e5-f66c-4a4d-933b-46222bb01eb0&displaylang=en

Saves lot of time and pain for sure! HTH, Thanks - Dipesh

XML, XSD.exe usage tips

Here are few quick tips that can help you understand and start with XML basics...

Questions - (preferably in this sequence)
How do you generate XSD ?
You need to have a valid XML file for which you want to have a schema generated ( XSD)
If you have VS .net you can just open the xml file into VS.net and then under XML menu you should see "Create Schema" option that should generate an .xsd file for you!

How do you create classes from an XSD schema?
You can create .net (C#, VB, J#) source code from the xsd using XSD tool (command line) along with MS .net framework.
http://samples.gotdotnet.com/quickstart/howto/doc/xmlserialization/xsdtocls.aspx

How do you convert (deserialize) XML into an object that you can read through .net code?
AND
How do you write out an XML file (serialize) from an object through .net code?

http://samples.gotdotnet.com/quickstart/howto/doc/xmlserialization/rwobjfromxml.aspx

Thats simple ...is it? Thanks - Dipesh

How do i authenticate web service requests before invoking web methods ?

How do i pass user name, password when calling web services ? or
How do i authenticate the web service request before invoking web methods ?

There are several ways to do this and one of the most easiest way is to pass user name, password as input parameters to web method called. but na, that is not a good way to implement as this information is at the periphery of the core business functionality of the web service exposed. Hence keeping this out makes more sense.

Another way to control anonymous access can be achieved through IIS (web server) settings. Just uncheck the anonymous access or limit the IPs that can hit your web services or validate it against your windows account group... but again you may want to implement partial anonymous access! Few web methods can be accessed by everyone, few have restricted access.

In that case, better way to do this is to pass this information into SOAP header (SOAP web services communicate through SOAP messages - which include SOAP envelope (inc. namespace and root element), SOAP Header (this is optional) and SOAP body (contains web method, input parameters and response result)

Working with SOAP Headers in order to have a Web service accept a SOAP header we need to perform the following three tasks:
1> Define a SOAP header class in the Web service project

public class AuthenticationHeader : SoapHeader
{
public string Username;
public string Password;
}

2> Add a public member variable of the SOAP header class created in step (1) to the Web service class

[WebService(Namespace=
http://www.comp.com/yournamespace )]
public class MyWebService : System.Web.Services.WebService
{
public AuthenticationHeader AuthHeader;
... The Web service's methods would be defined down here ...
}

3> Add the SoapHeader attribute to the Web method(s) that need to be able to programmatically access the value of the header

Once we perform these three steps at the Web service's end, our next task is to configure the client so that it can invoke a Web service method and pass along data for the appropriate SOAP header(s). The first step, as we've discussed in earlier installments of this article series, is to create a proxy class on the client. This will auto-generate the SOAP header class defined in the Web service project and will add a public property to the proxy class through which an instance of the SOAP header can be affixed to outgoing messages.

To actually pass along a populated SOAP header when calling a Web method the client needs to first create an instance of the proxy's SOAP header class, populate its values, and then assign this header class instance to the appropriate proxy class property. Finally, calling one of the Web service's methods will invoke the method, passing along the SOAP header.

[WebMethod(), SoapHeader("AuthHeader")]
public string GetMessage()
{
// Only allow valid user/password to access this secret message...
if (AuthHeader.Username == "user" && AuthHeader.Password == "password")
return "This is the secret message!!!";
else
return "YOU ARE NOT AUTHORIZED TO SEE THIS MESSAGE!";
}

In order to send a SOAP header to the Web service method, the client should do the following:
1> Create an instance of the proxy class,
2> Create an instance of the SOAP header class and populate its values,
3> Affix the SOAP header to the proxy class by assigning the SOAP header class instance created in step (2) to the proxy class's AuthHeaderValue property, and, finally
4> Call the Web service method

The following code illustrates these four steps. The GetMessage() Web method is invoked from the client passing along a username/password pair of scott and password.

// step 1, create the proxy class
localhost.MyWebService proxy = new localhost.MyWebService();
// step 2, create and populate the header class
localhost.AuthenticationHeader authInfo = new localhost.AuthenticationHeader();
authInfo.Username = "user";
authInfo.Password = "password";
// step 3, affix the SOAP header to the proxy
proxy.AuthHeaderValue = authInfo;
// step 4, call the method
string result = proxy.GetMessage();
The value returned from GetMessage() will contain the appropriate message, based on the username/password sent via the SOAP header.

Conclusion - If you want to know more or learn real sweet about the whole web services or SOAP basics and details visit
Scott Mitchell's article on http://aspnet.4guysfromrolla.com/articles/123103-1.aspx. He has written 11 part series about .net web services. Hope that helps! Thanks - Dipesh

XML Serialization: what can be XML serialized and what cannot be ?

Few points that you would like to know about XML serialization that may be also important if you are planning to face an interview soon :P)

Realize that XML serialization:
1> XML serialization can only be applied to classes that contain a public default (parameterless) constructor. If you create a class in the Web service that does not have a public default constructor, the Web service will still compile, but when attempting to generate the proxy class on the client's end you'll receive an error message.

2> Read-only class properties are NOT serialized. That is, if a property in the class has only a get accessor, and not a set accessor as well, the property will not be serialized.

3> ONLY public properties and fields are serialized. Private properties are not serialized.

4> To serialize a strongly-typed collection of objects, have the class derived from System.Collections.CollectionBase adding an Add() method and an indexer.
Alternatively you can send an array of the specified type.

On the last point, consider the case where you want a Web service method to accept a set of custom class instances. For example, imagine you wanted to build a Web method that accepted a number of instances of type CreditCardInfo. One option is to have the method accept an array of type CreditCardInfo, like so:

[WebMethod()]
public void FooBar(CreditCardInfo [] collectionOfCCInfos)
{
...
}
Another option is to create a strongly-typed collection class derived from System.Collections.CollectionBase. You'd then pass in an instance of this strongly-typed collection class. For example, you'd first create the class:

public class CreditCardInfoCollection : System.Collections.CollectionBase
{
public void Add(CreditCardInfo cc)
{
this.InnerList.Add(cc);
}

public CreditCardInfo this[int index]
{
get { return (CreditCardInfo) this.InnerList[index]; }
set { this.InnerList[index] = value; }
}
}
And then you'd have the Web service method accept an input of this strongly-typed collection class:
[WebMethod()]
public void FooBar(CreditCardInfoCollection collectionOfCCInfos)
{
...
}

See this article for more details on web services and XML related basics...
http://aspnet.4guysfromrolla.com/articles/121703-1.aspx


btw, Happy New Year 2008 :)
Happy programming - DJ