Wednesday, 22 August 2018

Xamarin WCF Call


Xamarin is a popular software platform for cross platform software development.Xamarin is used for development of mobile applications for both windows ,Android and iOS platform. Xamarin comes with Microsoft Visual Studio package and code can be written in Visual Studio language likes C#. 

In this lesson we will learn how to develop a Xamarin application that connect and WCF service.For this purpose , we have build two project.One project is WCF service another project for calling the WCF service. The second project will be written on Xamarin.

WCF service Project
open Visual Studio, from the "File" menu select "New Project", then choose "WCF". A new project will be open.





An interface will automatically created, the name of interface  "IService1" interface.We have to declare service contract.Below is the code of service contract. 


[ServiceContract]
public interface IService1
{
        [OperationContract]
           string GetMessage(string Name);

       [OperationContract]
         string GetMemberName(string ClientId, string SessionId);

       [OperationContract]
          string GetConection(string clientID);

}


Now , we have to build a message contact.Below is the code of Message Contract.


[MessageContract]
          public class RemoteFileInfo : IDisposable
        {
                   [MessageHeader(MustUnderstand = true)]
                    public string FileName;

                   [MessageHeader(MustUnderstand = true)]
                   public long Length;

                   [MessageBodyMember(Order = 1)]
                   public System.IO.Stream FileByteStream;

                   public void Dispose()
                  {
                        if (FileByteStream != null)
                          {
                                FileByteStream.Close();
                                FileByteStream = null;
                         }
                }
}



Here is the full code of the file

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.IO;
[ServiceContract]
public interface IService1
{
           [OperationContract]
           string GetMessage(string Name);

           [OperationContract]
           string GetMemberName(string ClientId, string SessionId);

           [OperationContract]
           string GetConection(string clientID);

}

[MessageContract]
public class RemoteFileInfo : IDisposable
{
             [MessageHeader(MustUnderstand = true)]
             public string FileName;

              [MessageHeader(MustUnderstand = true)]
              public long Length;

              [MessageBodyMember(Order = 1)]
              public System.IO.Stream FileByteStream;

              public void Dispose()
              {
                     if (FileByteStream != null)
                     {
                           FileByteStream.Close();
                           FileByteStream = null;
                      }
             }
}

 We have modified our web.config for this purpose.here is the full code of web.config.


xml version="1.0"?>
<configuration>
<system.web>
                  <compilation debug="true" targetFramework="4.0" />
                       <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="14400" />
               <webServices>
                  <protocols>
                       <remove name ="Documentation"/>
                             <add name="HttpGet"/>
                             <add name="HttpPost"/>
                   </protocols>
                  </webServices>
</system.web>
<system.webServer>
                <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

<system.serviceModel>
<services>
             <service name="wcf.Service1" behaviorConfiguration="ServiceBehavior">
            
             <endpoint address="http://localhost:8080/Service1" binding="wsHttpBinding"    contract="IService1">
<identity>
                 <dns value="localhost"/>
</identity>

</endpoint>
             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
              <basicHttpBinding>
               <binding name="wcf.IService1" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed" >
                 <readerQuotas maxDepth="32" maxBytesPerRead="200000000" maxArrayLength="200000000" maxStringContentLength="200000000" />
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">

<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>

</system.serviceModel>

</configuration>

Now we have added a class file "Program.cs". The full code of program file is.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Description;
using wcf;

namespace ServiceHost1
{
class Program
{
static ServiceHost m_svcHost = null;
static void Main(string[] args)
{

string strAdr = "http://localhost:8080/Service1";
try
{
                Uri adrbase = new Uri(strAdr);
               m_svcHost = new ServiceHost(typeof(wcf.Service1), adrbase);

               ServiceMetadataBehavior ServiceBehavior = new ServiceMetadataBehavior();
               m_svcHost.Description.Behaviors.Add(ServiceBehavior);
                m_svcHost.AddServiceEndpoint(typeof(IMetadataExchange),
               MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

                BasicHttpBinding httpb = new BasicHttpBinding();
                m_svcHost.AddServiceEndpoint(typeof(wcf.IService1), httpb, strAdr);
                m_svcHost.Open(); 
 
Console.WriteLine("Host is Starting " + DateTime.Now.ToString());
Console.ReadLine();
}
catch (Exception eX)
{
}
}
}
}
Run the application , you will get a blank screen.


Application for Consume WCF Service
Open visual studio, File >>New Project>>



Select Single View App
A new project will be open.From the Solution explorer,Layout folder,select activity_main.axml.Go to source of the file.



Add "IService1" cs file same as WFc project.
Below is the code of "IService1.cs"

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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.ServiceModel;
using System.IO;

[ServiceContract]
public interface IService1
{
        [OperationContract]
         string GetMessage(string Name);

        [OperationContract]
        string GetMemberName(string ClientId, string SessionId);

        [OperationContract]
        string GetConection(string clientID);

         [OperationContract]
        string GetdataWCF(string names);
}

[MessageContract]
public class RemoteFileInfo : IDisposable
{
       [MessageHeader(MustUnderstand = true)]
       public string FileName;

      [MessageHeader(MustUnderstand = true)]
      public long Length;

       [MessageBodyMember(Order = 1)]
       public System.IO.Stream FileByteStream;

       public void Dispose()
      {
            if (FileByteStream != null)
             {
            FileByteStream.Close();
            FileByteStream = null;
           }
     }
}

Add code for adding button


<Button
android:id="@+id/BtnLogin"
android:layout_width="100dp"
android:layout_height="45dp"
android:text="Call WCF"
android:background="#F18D00"
android:gravity="center" />

Open file MainActivity.cs , modify the existing code to handle the click event.


protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);

SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById
btn.Click += Login;
}



Here is the code for callinh WFC

ChannelFactory channelFactory = null;
EndpointAddress ep = null;
string result = string.Empty;

string strEPAdr = "http://" + "you host ip address:8080/Service1";

try
{
ep = new EndpointAddress(strEPAdr);
BasicHttpBinding httpb = new BasicHttpBinding();
channelFactory = new ChannelFactory(httpb);
IService1 mathSvcObj = channelFactory.CreateChannel(ep);

result=mathSvcObj.GetdataWCF(data);

channelFactory.Close();
}
catch (Exception eX)
{
Console.WriteLine("Error while performing operation [" + eX.Message + "] \n\n Inner Exception [" + eX.InnerException + "]");
}



No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...