Simplest WCF Example


You need add three projects on your solution. 2 console application, 1 class library.
1 Class library for your Service where one interface and one class will be there,
1 Console App for hosting your service,
1 Console App for consuming your service.
Reference - System.ServiceModel is needed to be added(by add reference option),
use it over using namespace option.

Now have this 3 code example over your solution.

HelloWCFClassLibrary


namespace HelloWCFClassLibrary
{
    [ServiceContract]
    public interface IHelloWCFService
    {
        [OperationContract]
        string SayHello(string msg);
    }
}




namespace HelloWCFClassLibrary
{
    public class HelloWCFService:IHelloWCFService
    {
        public string SayHello(string msg)
        {
            return string.Format("Hello" + msg);
        }
    }
}



HelloWCFServiceApplication


namespace HelloWCFServiceApplication
{
    class HelloWCFServiceHostClass
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(HelloWCFService));
            host.AddServiceEndpoint(typeof(IHelloWCFService),new BasicHttpBinding(),new Uri("http://localhost:3127/"));
            host.Open();
            Console.WriteLine("Server started");
            Console.Read();           

        }
    }
}

HelloWCFClientApp



class Program
    {
        static void Main(string[] args)
        {
            BasicHttpBinding mybinding=new BasicHttpBinding();
            EndpointAddress myaddress= new EndpointAddress("http://localhost:3127/");

            /*Below two lines is require */
            mybinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            mybinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
               
            ChannelFactory<IHelloWCFService> myChannelFactory = new ChannelFactory<IHelloWCFService>(mybinding, myaddress);
            IHelloWCFService proxy = myChannelFactory.CreateChannel();

            ((IClientChannel)proxy).Open();

            Console.WriteLine(proxy.SayHello("Pradip "));

            Console.Read();


        }
    }


That's all required to have this simplest example.

Create a Hit Counter Using the Global.asax File in ASP.NET




You can place the below code in Global.asax file and you need to call that variable in the aspx page. Example:

Global.asax Code

     void Application_Start(object sender, EventArgs e)
        { 
            Application["TotalHitCount"] = 0;
        }

Not required to put anything in other events in this file if you want to test while Page loading.Keep the below code on Page_Load() like below and press F5 to test it.

Code Behind

protected void Page_Load(object sender, EventArgs e)
        {
            Application["TotalHitCount"] = Convert.ToInt32(Application["TotalHitCount"]) + 1;
            lblTotCount.Text = Application["TotalHitCount"].ToString();
        }


Otherwise you can use like below in place of Page_Load(), 

Alternative Procedure

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            Application.Lock();
            Application["TotalHitCount"] = Convert.ToInt32(Application["TotalHitCount"]) + 1;
            Application.UnLock();
        }
        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends.
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer
            // or SQLServer, the event is not raised.
            Application["TotalHitCount"] = Convert.ToInt32(Application["TotalHitCount"]) - 1;
        }


Show or use it as per your application's requirement.

Online Test References

Common Issues


Error Message: “Unable to step in to the server”.

You may get this error while debugging from your source code to the additional code on different/same server.
For example Debugger is in a method ‘GetPatientDetailsList()’ and you press F11 to step in. If the source code is in your server/system, this issue can be resolved by pressing ‘Ctrl+alt+P’ or selecting the option ‘Debug->Attach to Process..’. Select W3WP.exe and press ok. If W3WP.exe is not showing on the Process list check the Option ‘Show Processes from all users’ or ‘Show Processes in all sessions’ as per your criteria and press ‘Refresh’ button to get new processes list. Select W3WP.exe and press ok. Though you are unable to get W3WP.exe , make sure whether you are having Admin access.If you are aware about this, do attach the process before step in [i.e Press F11 on the specific method on debugging].
When your source code is in different server, you have only consumed a particular service then the above work around will not help. In that case you can keep a local copy of the source code in your IIS.


Error Message: “The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'”


The main root cause of this issue is as the web service is running in the ASP.Net development web server, not in IIS ,authentication mode/default setting can be conflicted.  
Genarally, WCF uses anonymous authentication, whereas the ASP.Net development web server uses NTLM.
so you may change of  trying to make the development web server support anonymous authentication, but the simplest solution here is to change WCF to use NTLM authentication.


You may use this below code in client side. No change is needed from host or class library end.

            
            BasicHttpBinding mybinding=new BasicHttpBinding();

            EndpointAddress myaddress= new EndpointAddress("http://localhost:3127/");

            /*Below two lines is required */
            mybinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            mybinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;





Error Message: " There was no endpoint listening at http://SomeAddress:PortNo/ that could accept the message. This is often caused by an incorrect address or SOAP action."
Or,
"EndpointNotFoundException was unhandled."

First check with the address and port number you mentioned on client end whether it is correct and available or not. The same port number can be associated with other binding.
If the above you find are okay, Check with the Host Application is up and running or not. You may keep some message to ensure server started like below.

ServiceHost host = new ServiceHost(typeof(HelloWCFService));
host.Open();
Console.WriteLine("Server started");




Once you started an instance of the host (i.e. Right Click on ApplicationàDebugàStart New Instance), you may start your client application with the same debugging procedure.


Error Message: "Cannot obtain Metadata from http://localhost/XXX.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing..."


Add the below tag over Web.config file, which will enable sharing metadata with client(WSDL will be generated and accessible for client).

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 

After adding this if you found it is raising an issue(in some cases) as you have already an existing endpoint , so you may have a tag called a BaseAddress within Host as below which will help IIS to keep a base address and others endpoint address as a relative address.

   <host>
          <baseAddresses>           
             <add baseAddress="https://ServerName:PortNo/XYZ.Services" />
             <add baseAddress="https://localhost/XYZ.Services" />
          </baseAddresses>
   </host>



Error Message: "Contract requires Session, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it" 

If you have implemented like below,i.e. Included session over your contracts....

[ServiceContract(Namespace = "http://localhost/xxx.Services/first.svc",SessionMode = SessionMode.Required)]
public interface IMyCalcService{ ...

and the Contracts like below

[OperationContract(Name = "TestmyLoginSoap", IsInitiating=true,IsTerminating=false)]       
ResultSet TestmyLogin(string userName, string password);

or any other Implementation of session then basicHttpBindings will not work as it is not handled Session whereas "wsHttpBinding" supports session for it's newer WS specification.




For any further issues you may connect me @   nit.pradip@gmail.com.


Basic Dot Net Interview Questions


1.       Why ’ViewState’ Encryption is required? How to do that?
2.       What are the http verbs available? Differences between GET and POST?
3.       Can overloading possible in WCF?
4.       How Agile Methodology works? Advantages over other processes? Link 
5.       What is worker process in IIS and in ASP.net? Link  Link2 Link3 Link4
6.       How to recycling Worker Process in IIS? Link
7.       How to configure Web Garden ? link2
8.       How GC.Collect works?
9.       Difference between Debug and Release? Link
10.   How to host WCF through WAS?
11.   How to use MarshalByRefObject ?
12.   What is UDF in SQL and how to use it?
13.   System.Diagnostics, how to use this namspace  and purpose?
14.   What is duplex contract and how to use it? link
15.   Transaction in WCF?
16.   Why service behavior is require on interface?
17.   What is the difference between Explicitly Implement and Normal Implement of interface
18.   Difference between debug and release mode
19.   What is channel Factory?
20.   Why rendering is slow for some cases? How to improve the performance?
21.   How to send Bulk data to the SP from DA layer?
22.   What is cross post back?
23.   How to use view state in asp.net page and also in JavaScript?
24.   What is custom serializer?
25.   How to work with Marshal by ref object?
26.   How to interact with multiple servers in C#?
27.   What is static Virtual method? Is static class inherited? If not, why?
28.   How to use IHttphandler and IhttpModule?
29.   How to use IDisposable interface? Why should I use it?
30.   Can I use Store Procedure as an inline function?
31.   In which Scenario I will use Clustered and non clustered Index?
32.   In where clause what type of index used?
33.   What is Connection and Object pooling?
34.   What are the types you know on Generic List?
35.   Why Should I use properties and why not constructor?
36.   How to use net.pipe binding?
37.   Difference between DataContract and Xml Serilizer?
38.   Difference between basicHttp and WSHttp binding?
39.   Details of time out property in wcf client config ?
40.   What SSL mode? Difference between http and https?
41.   Version control in wcf. How do I know as a client that a new version has introduced.
42.   Performance testing in WCF. How to improve performance.
43.   Session provider. What is it and how to work with it.
44.   How to track wcf call later.
45.   Call back method over netTcp binding
46.   Net.tcp and Http binding, which one is best and why?
47.   How to work with sql transaction? What are the properties it has?
48.   What are the available Extension methods? How to work with it?
49.   Implementation details in Heap?
50.   What are the Http verbs?
51.   Design pattern in your project?
52.   Some ideas on .net framework 4.0?
53.   Asynchronous methods and how to use it?
54.   System.IO namespace?
55.   How much experience do you have with threading?  
56.   How to work with Async. delegates, thread pools and the System.Threading classes
57.    Difference between MSI and CAB ,XCopy Deployment ?
58.   How to access outside Assembly class?
59.   Difference between Trace and Debug?
60.   What provider ASP.Net use by default?
61.   Whether index will helpful while update or not?
62.   When garbage collection usually does?
63.   What is Isolation in SQL Server? SQL Profiler?


     You may take a look on this Link for more.
  

Can Multicast Delegate have return types ?


Please take a look on the below example code :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestHome
{
    class Program
    {
        public delegate int AddMulDel(int no1,int no2);
        public int Add(int num1st,int num2nd)
        {
            return num1st+num2nd;
        }
        public int Mul(int num1st, int num2nd)
        {
            return num1st * num2nd;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            AddMulDel objamDEL = p.Add;
            Console.WriteLine(objamDEL(10, 20)); // Result = 30

            objamDEL += p.Mul;
            Console.WriteLine(objamDEL.Invoke(10, 20)); // Result = 200
            //Though you have two methods[Add and Mul] in Delegate reference 'objamDEL',
            //Mul method is getting ovirwritten over Add method

            foreach (AddMulDel dm in objamDEL.GetInvocationList())
            {
                List<int> lstInt = new List<int>();
                lstInt.Add(dm(10, 20));
               
                foreach (int item in lstInt)
                    Console.WriteLine(item); //Result :- 30 and 200
            }
            Console.Read();

           
        }
    }
}

.