Thursday, 28 May 2015

How to call local host WCF service in Xamarin Android - Step by Step

1. Create WCF service. Sample 
    WCF service can be read from this link

2. Create solution from Xamarin.
3. Add the WCF service as  Web reference in the solution.
    My WCF service reference name is n192_168_50_233
4. Create one activity and place the controls in the below format,
 
      <TextView>       <EditText>
                                  <Button>
      <ListView>

   Sample UI code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:text="Search"
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />
    <EditText
        android:id="@+id/txtPatentType"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffe4e9f0"
        android:layout_toRightOf="@+id/txtView"
        android:layout_margin="10dp" />
    <Button
        android:id="@+id/btnSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnText"
        android:layout_below="@+id/txtView"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp" />
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/FeedsCollection"
        android:layout_below="@+id/btnSearch"
        android:layout_margin="10dp" />
    <TextView
        android:text=""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:layout_below="@+id/txtView"
        android:layout_toLeftOf="@+id/btnSearch"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp" />
</RelativeLayout>

5. Write the below code in Activity.cs file.


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.Threading;

namespace PatentDetails
{
[Activity (Label = "Patent Feeds", MainLauncher=true, Icon = "@drawable/icon")]
public class GetPatentFeedActivity : Activity
{

private Button search;
private EditText patentType;
private ListView feedsCollection;
protected override void OnCreate (Bundle bundle)
{

base.OnCreate (bundle);
SetContentView (Resource.Layout.GetPatentFeed);

search = FindViewById<Button> (Resource.Id.btnSearch);
patentType = FindViewById<EditText> (Resource.Id.txtPatentType);
feedsCollection = FindViewById<ListView> (Resource.Id.FeedsCollection);
search.Click += SearchPatentType;

}

public void SearchPatentType(object sender, EventArgs args){

feedsCollection.Adapter = null;
var feedProgress = ProgressDialog.Show (this, "", "Contacting server. Please wait..", true);
n192_168_50_233.Service1 service = new  PatentDetails.n192_168_50_233.Service1 ();
new Thread (new ThreadStart (delegate {
RunOnUiThread(()=>{
feedProgress.Show();
IAsyncResult asyncResult=service.BeginGetPatentList (patentType.Text, patentFeeds => { },null);
var patent = service.EndGetPatentList (asyncResult);

Toast.MakeText (this,"Feeds count " + patent.Length,ToastLength.Long).Show();

//Load Feeds in CustomFeedsLayout
feedsCollection.Adapter =new FeedsAdapter(this,patent);} );
RunOnUiThread(()=>feedProgress.Hide());
})).Start ();







}
  }

}


6. Write the below code in FeedsAdapter.cs
using System;
using Android.Widget;
using PatentDetails.n192_168_50_233;
using Android.App;
using Android.Views;

namespace PatentDetails
{
public class FeedsAdapter : BaseAdapter<PatentModel>
{
PatentModel[] patentList;
Activity activity;
 

public FeedsAdapter(Activity _activity, PatentModel[] _patentList):base(){
activity = _activity;
patentList = _patentList;

}


#region implemented abstract members of BaseAdapter

public override PatentModel this [int index] {
get {
return patentList [index];
}
}

public override long GetItemId (int position)
{
return position;
}

public override Android.Views.View GetView (int position, Android.Views.View convertView, Android.Views.ViewGroup parent)
{
var patentItem = patentList [position];
View view = convertView;
if (view == null)
view = activity.LayoutInflater.Inflate (Resource.Layout.CustomFeedsLayout, null);
view.FindViewById<TextView> (Resource.Id.textViewTitle).Text = patentItem.Title;
view.FindViewById<TextView> (Resource.Id.textViewLink).Text = patentItem.Link;
view.FindViewById<TextView> (Resource.Id.textViewDescription).Text = patentItem.Description;
view.FindViewById<TextView> (Resource.Id.textViewPublishedDate).Text = patentItem.PublishedDate;
return view;
}

public override int Count {
get {
return patentList.Length;
}
}

#endregion
}
}

7. Create One Layout file in  the name of CustomFeedsLayout.XAML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:text="Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textViewTitle"
        android:textColor="#ffec9f10" />
    <TextView
        android:text="Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textViewLink"
        android:textColor="#ff577ae8" />
    <TextView
        android:text="Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textViewDescription"
        android:textColor="#ffe20ddf" />
    <TextView
        android:text="Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textViewPublishedDate"
        android:textColor="#ff38d6d6" />
</LinearLayout>


8. Xamarin with WCF service consume project is ready..
9. Happy coding.

Simple WCF - Service

1.  Create Interface like,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace PatentService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        List<PatentModel> GetPatentList(string PatentType);
       
    }


    [DataContract]
    public class PatentModel
    {
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public string Link { get; set; }
        [DataMember]
        public string Description { get; set; }
        [DataMember]
        public string PublishedDate { get; set; }
    }
}


2.  In the SVC.cs file.

using PatentService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace PatentService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public List<PatentModel> GetPatentList(string PatentType)
        {
            try
            {
                List<PatentModel> patentList = new List<PatentModel>();
                PatentModel patentInfo = new PatentModel() { Description = "No patents available" };

                XDocument xDocument = XDocument.Load(HttpContext.Current.Server.MapPath(@"~\Files\PatentTypeList.xml"));
                var FeedList = xDocument.Element("Feeds").Elements();
                if (FeedList.Count() > 0)
                {
                    List<PatentTypeModel> availablePatentList = FeedList.Select(p => new PatentTypeModel
                    {
                        Category = p.Element("Category").Value,
                        FeedURL = p.Element("FeedURL").Value,
                        Type = p.Element("Type").Value
                    }).ToList();


                    PatentTypeModel selectedPatent = availablePatentList.Find(p => p.Type.ToLower() == PatentType.ToLower());
                    if (selectedPatent != null)
                    {

                        string feedSource = new WebClient().DownloadString(selectedPatent.FeedURL);
                        XDocument feedDocument = XDocument.Parse(feedSource);
                        var feeds = feedDocument.Descendants("channel").Elements("item");
                        if (feeds.Count() > 0)
                        {
                            patentList = feeds.Select(f => new PatentModel
                           {
                               Title = f.Element("title").Value,
                               Description = f.Element("description").Value,
                               Link = f.Element("link").Value,
                               PublishedDate = f.Element("pubDate").Value
                           }).ToList();
                            return patentList;

                        }

                        else
                        {
                            patentList.Add(patentInfo);
                            return patentList;
                        }
                    }
                    else
                    {
                        patentList.Add(patentInfo);
                        return patentList;
                    }
                }
                else
                {
                    patentList.Add(patentInfo);
                    return patentList;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

    }
}


3. Create XML file in Files\ folder
<?xml version="1.0" encoding="utf-8" ?>
<Feeds>
  <Feed>
    <Category>Computers</Category>
    <Type>Graphic processing</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat345.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Computers</Category>
    <Type>I/O Systems</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat710.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Computers</Category>
    <Type>CPUs</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat712.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Computers</Category>
    <Type>Dynamic Storage</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat369.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Computers</Category>
    <Type>Static Storage</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat365.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Computers</Category>
    <Type>Printers/Printing </Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat347.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Software</Category>
    <Type>Artificial Intelligence</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat706.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Software</Category>
    <Type>Databases</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat707.xml</FeedURL>
  </Feed>
  <Feed>
    <Category>Software</Category>
    <Type>Development</Type>
    <FeedURL>http://www.freepatentsonline.com/rssfeed/rsspat717.xml</FeedURL>
  </Feed>
</Feeds>

4.  Change the Web.Config file (in bold letters are needs to add)

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <!-- START :: Need to configure services and behaviors section while deploy in to IIS-->
    <services>

      <service behaviorConfiguration="PatentServiceBehavior" name="PatentService.Service1">
        <endpoint address="http://localhost:59285/Service1.svc" binding="basicHttpBinding" contract="PatentService.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="PatentServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- END :: Need to configure services and behaviors section while deploy in to IIS-->
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>


5. Save and run the SVC file in WCF Test client environment. 

Happy coding....

WCF - Web Config while deploy

 <?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <!-- START :: Need to configure services and behaviors section while deploy in to IIS-->
    <services>

      <service behaviorConfiguration="PatentServiceBehavior" name="PatentService.Service1">
        <endpoint address="http://192.168.50.233/Patent%20WCF/Service1.svc" binding="basicHttpBinding" contract="PatentService.IService1">
          <identity>
            <dns value="192.168.50.233"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="PatentServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- END :: Need to configure services and behaviors section while deploy in to IIS-->
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

Tuesday, 19 May 2015

Select All - Un Select All using Java script

 var EnabledCheckBoxCount=0;     //For Get all enabled check box count in the current page
        var CheckedCheckBoxCount=0;    // Get Checked check box count in the current page
        var CheckedCheckBoxItems="";
        var PickCheckboxGroup = {
            Counter: 0,
            HeaderClick:
                function (CheckBox)
                    {
                        EnabledCheckBoxCount=document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_HdnEnabledCheckBoxCount").value;
                        CheckedCheckBoxCount=document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_HdnCheckedCheckBoxCount").value;
                        CheckedCheckBoxItems=document.getElementById("ctl00_cphData_HdnCheckedCheckBoxItems").value;
                       
                        var TargetBaseControl = document.getElementById('<%= this.grd_CADTakeOffList.ClientID %>');
                        var TargetChildControl = "chk_PickSelect";
                       
                        //Get all the control of the type INPUT in the base control.
                        var Inputs = TargetBaseControl.getElementsByTagName("input");
                       
                        //Checked/Unchecked all the checkBoxes in side the GridView.
                        for (var n = 0; n < Inputs.length; ++n)
                        {
                            if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 && Inputs[n].disabled == false)
                            {
                                Inputs[n].checked = CheckBox.checked;
                                   if(Inputs[n].parentElement.title!="")
                                    {
                                        if(CheckBox.checked)
                                        {
                                            CheckedCheckBoxCount =parseInt(CheckedCheckBoxCount)+ 1;
                                            CheckedCheckBoxItems+=Inputs[n].parentElement.title + ",";
                                        }
                                        else
                                        {
                                            CheckedCheckBoxCount=CheckedCheckBoxCount==0?0:parseInt(CheckedCheckBoxCount)-1;
                                            CheckedCheckBoxItems=(CheckedCheckBoxItems).replace(Inputs[n].parentElement.title,"");
                                        }
                                    }
                            }
                        }
                        document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_HdnCheckedCheckBoxCount").value =CheckedCheckBoxCount;
                        document.getElementById("ctl00_cphData_HdnCheckedCheckBoxItems").value =CheckedCheckBoxItems;
                    }
             ,
            ChildClick:
                function (Chk_CADMasterID)
                    {
                        EnabledCheckBoxCount=document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_HdnEnabledCheckBoxCount").value;
                        CheckedCheckBoxCount=document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_HdnCheckedCheckBoxCount").value;
                        CheckedCheckBoxItems=document.getElementById("ctl00_cphData_HdnCheckedCheckBoxItems").value;
                       
                        var HeaderCheckBox = document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_chk_PickSelectAll");
                       
                        if(CheckedCheckBoxItems.length==0 || CheckedCheckBoxItems.indexOf(Chk_CADMasterID)==-1)
                        {
                            CheckedCheckBoxItems += Chk_CADMasterID + ',';
                            CheckedCheckBoxCount=CheckedCheckBoxCount==0?1:parseInt(CheckedCheckBoxCount)+ 1;  
                        }
                        else
                        {
                            CheckedCheckBoxItems=(CheckedCheckBoxItems).replace(Chk_CADMasterID+',', "");
                            CheckedCheckBoxCount=CheckedCheckBoxCount==0?0:parseInt(CheckedCheckBoxCount)-1;
                        }
                        document.getElementById("ctl00_cphData_grd_CADTakeOffList_ctl01_HdnCheckedCheckBoxCount").value =CheckedCheckBoxCount;
                        document.getElementById("ctl00_cphData_HdnCheckedCheckBoxItems").value =CheckedCheckBoxItems;
                       
                        if(EnabledCheckBoxCount==CheckedCheckBoxCount)
                            HeaderCheckBox.checked = true;
                        else
                            HeaderCheckBox.checked = false;
                       
                       
                       
                    }
        };