Search This Blog

Sunday 25 December 2016

Button Click

Loction Button Click Event:-
-----------------------------
  string strLatitute = e.lat.ToString();
  string strLongitute = e.lng.ToString();
  var address = await DependencyService.Get<IReverseGeocode>().ReverseGeoCodeLatLonAsync(Convert.ToDouble(strLatitute), Convert.ToDouble(strLongitute));
  lblSummaryLoction.Text = address.Address1;



 if (App.isFifthPage)
            {
                btnMedicationNext.Text = "SUBMIT";
            }
            else {
                btnMedicationNext.Text = "NEXT";
            }

            btnMedicationNext.Clicked += delegate
            {
                if (App.isFifthPage)
                {
                    App.isFifthPage = false;
                    Navigation.PopModalAsync();

                }

Android ReverseGeocode Class

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.Runtime.CompilerServices;
using Mig.Droid;
using Xamarin.Forms;
using Android.Locations;
using System.Threading.Tasks;

[assembly: Xamarin.Forms.Dependency(typeof(ReverseGeocode))]
namespace Mig.Droid
{
    public class ReverseGeocode : IReverseGeocode
    {
        public ReverseGeocode()
        {

        }
        public async Task<LocationAddress> ReverseGeoCodeLatLonAsync(double lat, double lon)
        {
            var geo = new Geocoder(Forms.Context);
            var addresses = await geo.GetFromLocationAsync(lat, lon, 1);
            if (addresses.Any())
            {
                var place = new LocationAddress();
                var add = addresses[0];
                place.Name = add.FeatureName;
                if (add.MaxAddressLineIndex > 0)
                {
                    place.Address1 = add.GetAddressLine(0);
                }
                place.City = add.Locality;
                place.Province = add.AdminArea;
                place.ZipCode = add.PostalCode;
                place.Country = add.CountryCode;
                return place;
            }

            return null;
        }
    }
}

LocationAddress Class in PCL

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

namespace Mig
{
   public class LocationAddress
    {
        public LocationAddress()
        {
        }
        public string Name { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
        public string Country { get; set; }
    }
}

IReverseGeocode Interface Class

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

namespace Mig
{
   public interface IReverseGeocode
    {
        Task<LocationAddress> ReverseGeoCodeLatLonAsync(double lat, double lon);
    }
}

Full Address Url site

https://visualstudiomagazine.com/articles/2015/09/01/native-services-with-xamarinforms.aspx

Thursday 22 December 2016

Restrict

 int _Medicianlimit = 3;
            etMedicationName.TextChanged += (sender, args) =>
            {
                string _text = etMedicationName.Text;      //Get Current Text
                bool isDotValue = isDot(etMedicationName);

                if (_text.Length == 2)
                {
                    char[] chars = _text.ToCharArray();
                    if (chars[1]!='.')
                    {
                        _text = _text.Remove(_text.Length - 1);
                        etMedicationName.Text = _text;
                    }
                }
                else
                {
                    if (_text.Length > _Medicianlimit)       //If it is more than your character restriction
                    {
                        _text = _text.Remove(_text.Length - 1);  // Remove Last character
                        etMedicationName.Text = _text;        //Set the Old value
                    }
                }
            };

Wednesday 21 December 2016

naviga

App.Xaml.Cs:
After Partial Class

 public static bool isFifthPage = false;
-----------------------------------------

MEdication page Button Click:
   btnMedicationNext.Clicked += delegate
            {
                if (App.isFifthPage)
                {
                    App.isFifthPage = false;
                    Navigation.PopModalAsync();

                }
                else
                {

                    string strMedicationName = "";
                    foreach (var eachItem in objMEdicationWithDosage)
                    {
                 
-------------------------------------------------------------

Last Page Button Click:

 var startTap = new TapGestureRecognizer();
            startTap.Tapped += (s, e) =>
            {
                App.isFifthPage = true;
                Navigation.PushModalAsync(new MedicationPage());
            };     

Tuesday 20 December 2016

Address API

http://maps.googleapis.com/maps/api/geocode/json?latlng=18.589235,73.738853&sensor=true

https://maps.googleapis.com/maps/api/geocode/json?latlng=18.589235,73.738853&key=AIzaSyBkimSBhY8b1SQKeXWitEJ7ntCOVIl6uUw

Entery With Validation

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

using Xamarin.Forms;

namespace Mig
{
    public partial class NotePage : ContentPage
    {
        String strMessage = "";
        public NotePage()
        {
            Title = "Note";
            InitializeComponent();
            btnNoteRemindme.Clicked += delegate
            {
                Navigation.PushModalAsync(new SummaryPage());
            };
            btnNoteNext.Clicked += delegate
            {
                Navigation.PushModalAsync(new SummaryPage());
            };


            etNote.TextChanged += EtNote_TextChanged;

            var TapPaininAbdomen = new TapGestureRecognizer();
            TapPaininAbdomen.Tapped += (sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(etNote.Text))
                {
                    etNote.Text = (etNote.Text + "Pain in the abdomen" + ", ");
                }
                else
                {
                    string strName = etNote.Text;
                    string strNewChar = strName.Substring(Math.Max(0, strName.Length - 2));

                    if (strNewChar == ", ")
                    {
                        if (etNote.Text.Length > 0)
                        {
                            etNote.Text = etNote.Text.Substring(0, etNote.Text.Length - 2);
                            bool isExisting = false;
                            string[] items = etNote.Text.ToString().Split(',');
                            foreach (var eachItem in items)
                            {
                                if (eachItem == "Pain in the abdomen")
                                {
                                    isExisting = true;
                                    break;
                                }
                            }
                            if (!isExisting)
                            {
                                etNote.Text = (etNote.Text + ", " + "Pain in the abdomen" + ", ");
                            }
                        }
                    }
                }
            };
            lblPainInTheAbdomen.GestureRecognizers.Add(TapPaininAbdomen);

            var TapLossOfPain = new TapGestureRecognizer();
            TapLossOfPain.Tapped += (sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(etNote.Text))
                {
                    etNote.Text = (etNote.Text + "Loss of appetite" + ", ");
                }
                else
                {
                    if (etNote.Text.Length > 0)
                    {
                        string strName = etNote.Text;
                        string strNewChar = strName.Substring(Math.Max(0, strName.Length - 2));
                        if (strNewChar == ", ")
                        {
                            etNote.Text = etNote.Text.Substring(0, etNote.Text.Length - 2);
                            bool isExisting = false;
                            string[] items = etNote.Text.ToString().Split(',');
                            foreach (var eachItem in items)
                            {
                                if (eachItem == "Loss of appetite")
                                {
                                    isExisting = true;
                                    break;
                                }
                            }
                            if (!isExisting)
                            {
                                etNote.Text = (etNote.Text + ", " + "Loss of appetite" + ", ");
                            }
                        }
                    }
                }
            };
            lblLossOfPain.GestureRecognizers.Add(TapLossOfPain);

            var TapNauseaOfVomting = new TapGestureRecognizer();
            TapNauseaOfVomting.Tapped += (sender, e) =>
            {
                if (string.IsNullOrWhiteSpace(etNote.Text))
                {
                    etNote.Text = (etNote.Text + "Nausea or Vomiting" + ", ");
                }
                else
                {
                    string strName = etNote.Text;
                    string strNewChar = strName.Substring(Math.Max(0, strName.Length - 2));
                    if (strNewChar == ", ")
                    {
                        if (etNote.Text.Length > 0)
                        {
                            etNote.Text = etNote.Text.Substring(0, etNote.Text.Length - 2);
                            bool isExisting = false;
                            string[] items = etNote.Text.ToString().Split(',');
                            foreach (var eachItem in items)
                            {
                                if (eachItem == "Nausea or Vomiting")
                                {
                                    isExisting = true;
                                    break;
                                }
                            }
                            if (!isExisting)
                            {
                                etNote.Text = (etNote.Text + ", " + "Nausea or Vomiting" + ", ");
                            }
                        }
                    }
                }
            };
            lblNauseaOfVomting.GestureRecognizers.Add(TapNauseaOfVomting);
        }
           
        private void EtNote_TextChanged(object sender, TextChangedEventArgs e)
        {
            strMessage = e.NewTextValue;
        }
    }
}

Monday 12 December 2016

ad

  string strLatitute = e.lat.ToString();
            string strLongitute = e.lng.ToString();
            //string locationUrl = "http://api.openweathermap.org/data/2.5/weather?lat="+ strLatitute +"&lon="+ strLongitute + "&appid=b631adf3653df30af9ce66a72cf9b6de";



            string strNewsLocationUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+strLatitute+","+strLongitute+"&key=AIzaSyBkimSBhY8b1SQKeXWitEJ7ntCOVIl6uUw";

            HttpClient objHttpClient = new HttpClient();
            var locationDetails =await objHttpClient.GetStringAsync(strNewsLocationUrl);
            var Locations = JsonConvert.DeserializeObject<AddressModel>(locationDetails.ToString());

Sunday 11 December 2016

Numarical

 int _Dosagelimit = 3;
            etDosage.TextChanged += (sender, args) =>
            {
                int n;
                var isNumeric = int.TryParse(etDosage.Text, out n);
                if (isNumeric)
                {
                    string _text = etDosage.Text;      //Get Current Text
                    if (_text.Length > _Dosagelimit)       //If it is more than your character restriction
                    {
                        _text = _text.Remove(_text.Length - 1);  // Remove Last character
                        etDosage.Text = _text;        //Set the Old value
                    }
                }
                else
                {
                    string _text = etDosage.Text;
                    if (_text.Length > 0)
                    {
                        _text = _text.Remove(_text.Length - 1);
                        etDosage.Text = _text;
                    }
                }
            };

Change

  var TapJustNow = new TapGestureRecognizer();
            TapJustNow.Tapped += TapJustNow_Tapped;
            slJustNow.GestureRecognizers.Add(TapJustNow);

            var Tap15MinAgo = new TapGestureRecognizer();
            Tap15MinAgo.Tapped += Tap15MinAgo_Tapped;
            sl15MintsAgo.GestureRecognizers.Add(Tap15MinAgo);

            var Tap30MinAgo = new TapGestureRecognizer();
            Tap30MinAgo.Tapped += Tap30MinAgo_Tapped;
            sl30Mints.GestureRecognizers.Add(Tap30MinAgo);

            var Tap1HourAgo = new TapGestureRecognizer();
            Tap1HourAgo.Tapped += Tap1HourAgo_Tapped;
            sl1HourAgo.GestureRecognizers.Add(Tap1HourAgo);

            var Tap2HourAgo = new TapGestureRecognizer();
            Tap2HourAgo.Tapped += Tap2HourAgo_Tapped;
            sl2HoursAgo.GestureRecognizers.Add(Tap2HourAgo);
        }
        private void TapJustNow_Tapped(object sender, EventArgs e)
        {
            imgchangeJustNow.Source = "med_select.png";
            imgchange15Minago.Source = "med_deselect.png";
            imgchange30Minago.Source = "med_deselect.png";
            imgchange1HourAgo.Source = "med_deselect.png";
            imgchange2HourAgo.Source = "med_deselect.png";
            DateTime oDate = Convert.ToDateTime(App.strDateTime);
            long milli = (long)(oDate - new DateTime(1970, 1, 1)).TotalMilliseconds;
            var milliseconds = 0 * 60000;
            var diff = milli - milliseconds;
            string strNewTime = TimeUtility.getDate(diff.ToString());
            lblMainTime.Text = strNewTime;
        }
        private void Tap15MinAgo_Tapped(object sender, EventArgs e)
        {
            imgchange15Minago.Source = "med_select.png";
            imgchangeJustNow.Source = "med_deselect.png";
            imgchange30Minago.Source = "med_deselect.png";
            imgchange1HourAgo.Source = "med_deselect.png";
            imgchange2HourAgo.Source = "med_deselect.png";
            DateTime oDate = Convert.ToDateTime(App.strDateTime);
            long milli = (long)(oDate - new DateTime(1970, 1, 1)).TotalMilliseconds;
            var milliseconds = 15 * 60000;
            var diff = milli - milliseconds;
            string strNewTime = TimeUtility.getDate(diff.ToString());
            lblMainTime.Text = strNewTime;
        }
        private void Tap30MinAgo_Tapped(object sender, EventArgs e)
        {
            imgchange30Minago.Source = "med_select.png";
            imgchangeJustNow.Source = "med_deselect.png";
            imgchange15Minago.Source = "med_deselect.png";
            imgchange1HourAgo.Source = "med_deselect.png";
            imgchange2HourAgo.Source = "med_deselect.png";
            DateTime oDate = Convert.ToDateTime(App.strDateTime);
            long milli = (long)(oDate - new DateTime(1970, 1, 1)).TotalMilliseconds;
            var milliseconds = 30 * 60000;
            var diff = milli - milliseconds;
            string strNewTime = TimeUtility.getDate(diff.ToString());
            lblMainTime.Text = strNewTime;
        }
        private void Tap1HourAgo_Tapped(object sender, EventArgs e)
        {
            imgchange1HourAgo.Source = "med_select.png";
            imgchangeJustNow.Source = "med_deselect.png";
            imgchange15Minago.Source = "med_deselect.png";
            imgchange30Minago.Source = "med_deselect.png";
            imgchange2HourAgo.Source = "med_deselect.png";
            DateTime oDate = Convert.ToDateTime(App.strDateTime);
            long milli = (long)(oDate - new DateTime(1970, 1, 1)).TotalMilliseconds;
            var milliseconds = 60 * 60000;
            var diff = milli - milliseconds;
            string strNewTime = TimeUtility.getDate(diff.ToString());
            lblMainTime.Text = strNewTime;
        }
        private void Tap2HourAgo_Tapped(object sender, EventArgs e)
        {
            imgchange2HourAgo.Source = "med_select.png";
            imgchangeJustNow.Source = "med_deselect.png";
            imgchange15Minago.Source = "med_deselect.png";
            imgchange30Minago.Source = "med_deselect.png";
            imgchange1HourAgo.Source = "med_deselect.png";
            DateTime oDate = Convert.ToDateTime(App.strDateTime);
            long milli = (long)(oDate - new DateTime(1970, 1, 1)).TotalMilliseconds;
            var milliseconds = 120 * 60000;
            var diff = milli - milliseconds;
            string strNewTime = TimeUtility.getDate(diff.ToString());
            lblMainTime.Text = strNewTime;
        }

    }
}

Time

public class TimeUtility
    {
        public static string getCurrentDateTime(DateTime date)
        {
            DateTime dt = date;
            return dt.ToString("HH:mm tt  dd MMM yyyy");
        }

        public static string getDate(string startdatetime)
        {
            long microSec = Convert.ToInt64(startdatetime);
            DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(Convert.ToInt64(microSec) * 10000);
            return getCurrentDateTime(converted);
        }
    }
// App.strDateTime=TimeUtility.getCurrentDateTime(DateTime.Now);

Wednesday 7 December 2016

N

 public partial class MedicationPage : ContentPage
    {
        ObservableCollection<MedicationWithDosage> objMEdicationWithDosage = null;
        public MedicationPage()
        {
            Title = "Medication";
            InitializeComponent();

            btnSave.Clicked += BtnSave_Clicked;
            addMedicineDialogScroll.IsVisible = false;
            LoadMEdicationWithDosageData();
            btnMedicationRemindme.Clicked += delegate
            {
                Navigation.PushModalAsync(new NotePage());
            };
            btnMedicationNext.Clicked += delegate
            {
                string strMedicationName = "";
                foreach (var eachItem in objMEdicationWithDosage)
                {
                    if (eachItem.ImgPic == "med_select.png" && eachItem.MedicationName != "None")
                    {
                        strMedicationName = strMedicationName + eachItem.MedicationName + ",";
                    }
                }
                strMedicationName = strMedicationName.Substring(0, strMedicationName.Length - 1);
                strMedicationName = strMedicationName + ".";

             
                App.strMedicationName = strMedicationName;
                Navigation.PushModalAsync(new NotePage());
            };
            int _Medicianlimit = 30;
            etMedicationName.TextChanged += (sender, args) =>
            {
                string _text = etMedicationName.Text;      //Get Current Text
                if (_text.Length > _Medicianlimit)       //If it is more than your character restriction
                {
                    _text = _text.Remove(_text.Length - 1);  // Remove Last character
                    etMedicationName.Text = _text;        //Set the Old value
                }
            };
            int _Dosagelimit = 3;
            etDosage.TextChanged += (sender, args) =>
            {
                string _text = etDosage.Text;      //Get Current Text
                if (_text.Length > _Dosagelimit)       //If it is more than your character restriction
                {
                    _text = _text.Remove(_text.Length - 1);  // Remove Last character
                    etDosage.Text = _text;        //Set the Old value
                }
            };
        }
        private void BtnSave_Clicked(object sender, EventArgs e)
        {
            if(etMedicationName!=null && etMedicationName.Text.Trim().Length>0)
            {
                var selectedItems = (from p in objMEdicationWithDosage where p.MedicationName == etMedicationName.Text select p).ToList();
                if (selectedItems.Count > 0)
                {
                    DisplayAlert("error", "medicationName already you have added to List.", "ok");
                    return;
                }
                else
                {
                    objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = etMedicationName.Text, ImgPic = "med_deselect.png" });
                    lstMedicationWithDosage.ItemsSource = objMEdicationWithDosage;
                    etMedicationName.Text = "";
                    etDosage.Text = "";
                }
            }
            else
            {
                DisplayAlert("error", "Please Enter medicationName", "ok");
                return;
            }
        }
        public void Handle_Clicked(object sender, EventArgs e)
        {
            addMedicineDialogScroll.IsVisible = true;
        }

        public void OnSaveButtonClicked(object sender, EventArgs args)
        {
            addMedicineDialogScroll.IsVisible = false;
        }

        public void OnCancelButtonClicked(object sender, EventArgs args)
        {
            addMedicineDialogScroll.IsVisible = false;
        }
        public void LoadMEdicationWithDosageData()
        {
            objMEdicationWithDosage = new ObservableCollection<MedicationWithDosage>();
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "None", ImgPic = "med_select.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Zooming (600 mg)", ImgPic = "med_deselect.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Calpol (650 mg)", ImgPic = "med_deselect.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Figorty (230 mg)", ImgPic = "med_deselect.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Higtyui (500 mg)", ImgPic = "med_deselect.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Firtosia (300 mg)", ImgPic = "med_deselect.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Glinica (300 mg)", ImgPic = "med_deselect.png" });
            objMEdicationWithDosage.Add(new MedicationWithDosage { MedicationName = "Migoi (300 mg)", ImgPic = "med_deselect.png" });
            lstMedicationWithDosage.ItemsSource = objMEdicationWithDosage;

            lstMedicationWithDosage.ItemSelected += LstMedicationWithDosage_ItemSelected;
        }

        private void LstMedicationWithDosage_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return; // ensures we ignore this handler when the selection is just being cleared
            }
            lstMedicationWithDosage.ItemsSource = null;
            MedicationWithDosage item = e.SelectedItem as MedicationWithDosage;
            if (item.ImgPic == "med_select.png")
            {
                item.ImgPic = "med_deselect.png";
            }
            else
            {
                item.ImgPic = "med_select.png";
            }
            var selectedItems = (from s in objMEdicationWithDosage where s.ImgPic == "med_select.png"
                                 && s.MedicationName!= "None" select s).ToList();
            if (selectedItems.Count > 0)
            {
                objMEdicationWithDosage[0].ImgPic = "med_deselect.png";
            }
            else
            {
                objMEdicationWithDosage[0].ImgPic = "med_select.png";
            }

            if (item.MedicationName == "None")
            {
                var selectedItemsList = (from s in objMEdicationWithDosage
                                         where s.ImgPic == "med_select.png" select s).ToList();
                foreach(var eachItem in selectedItemsList)
                {
                    eachItem.ImgPic = "med_deselect.png";
                }
                item.ImgPic ="med_select.png";
            }
            lstMedicationWithDosage.ItemsSource = objMEdicationWithDosage;
            ((ListView)sender).SelectedItem = null;
        }
    }

Tuesday 6 December 2016

ListView Examples


 private void LstMedicationWithDosage_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            lstMedicationWithDosage.ItemsSource = null;
            var item = e.SelectedItem as MedicationWithDosage;
            if (item.ImgPic == "med_select.png")
            {
                item.ImgPic = "med_deselect.png";
            }
            else
            {
                item.ImgPic = "med_select.png";
            }
            var selectedItems = (from s in objMEdicationWithDosage where s.ImgPic == "med_select.png"
                                 && s.MedicationName!= "None" select s).ToList();
            if (selectedItems.Count > 0)
            {
                objMEdicationWithDosage[0].ImgPic = "med_deselect.png";
            }
            else
            {
                objMEdicationWithDosage[0].ImgPic = "med_select.png";
            }
            lstMedicationWithDosage.ItemsSource = objMEdicationWithDosage;
        }
------------------------------

 btnMedicationNext.Clicked += delegate
            {
                string strMedicationName = "";
                foreach (var eachItem in objMEdicationWithDosage)
                {
                    if (eachItem.ImgPic == "med_select.png" && eachItem.MedicationName != "None")
                    {
                        strMedicationName = strMedicationName + eachItem.MedicationName + ",";
                    }
                }
                //strMedicationName = strMedicationName.Substring(0, strMedicationName.Length - 1);
                App.strMedicationName = strMedicationName;
                Navigation.PushModalAsync(new NotePage());
            };
---------------------------------
    var strtap = new TapGestureRecognizer();
            strtap.Tapped += Strtap_Tapped;
            sl30Mints.GestureRecognizers.Add(strtap);
        }
        private void Strtap_Tapped(object sender, EventArgs e)
        {
            DateTime oDate = Convert.ToDateTime(App.strDateTime);
            var ms = (oDate - DateTime.MinValue).TotalMilliseconds;
            var ss = ms;
        }

Sunday 4 December 2016

LoctonEventRising

  private void showtheLocationDetails()
        {
            DependencyService.Get<IMyLocation>().ObtainMyLocation();
            DependencyService.Get<IMyLocation>().locationObtained += MainPage_locationObtained;
        }

        private async void MainPage_locationObtained(object sender, ILocationEventArgs e)
        {
            string strLatitute = e.lat.ToString();
            string strLongitute = e.lng.ToString();
            string locationUrl = "http://api.openweathermap.org/data/2.5/weather?lat="+ strLatitute +"&lon="+ strLongitute + "&appid=b631adf3653df30af9ce66a72cf9b6de";
            HttpClient objHttpClient = new HttpClient();
            var locationDetails =await objHttpClient.GetStringAsync(locationUrl);
            var Locations = JsonConvert.DeserializeObject<LocationModel>(locationDetails.ToString());

            lblSummaryLoction.Text = Locations.name;
            lblSummaryWeather.Text = (Locations.weather[0].description) +",," +(Locations.main.temp) + ",,"+(Locations.main.humidity) + (Locations.main.pressure);
            var ss = Locations;
        }

GetMyLocation

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 Mig.Droid;
using Android.Locations;
using Xamarin.Forms;

[assembly: Xamarin.Forms.Dependency(typeof(GetMyLocation))]
namespace Mig.Droid
{
   public class GetMyLocation : Java.Lang.Object,
                                IMyLocation,
                                ILocationListener {
        LocationManager lm;
        public void OnProviderDisabled(string provider) { }
        public void OnProviderEnabled(string provider) { }
        public void OnStatusChanged(string provider,
            Availability status, Android.OS.Bundle extras)
        { }
        //---fired whenever there is a change in location---
        public void OnLocationChanged(Location location)
        {
            if (location != null)
            {
                LocationEventArgs args = new LocationEventArgs();
                args.lat = location.Latitude;
                args.lng = location.Longitude;
                locationObtained(this, args);
            };
        }
        //---an EventHandler delegate that is called when a location
        // is obtained---
        public event EventHandler<ILocationEventArgs> locationObtained;
        //---custom event accessor that is invoked when client
        // subscribes to the event---
        event EventHandler<ILocationEventArgs> IMyLocation.locationObtained
        {
            add
            {
                locationObtained += value;
            }
            remove
            {
                locationObtained -= value;
            }
        }
        //---method to call to start getting location---
        public void ObtainMyLocation()
        {
            lm = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);
            lm.RequestLocationUpdates( LocationManager.NetworkProvider,
                    0,   //---time in ms---
                    0,   //---distance in metres---
                    this);
        }
        //---stop the location update when the object is set to
        // null---
        ~GetMyLocation()
        {
            lm.RemoveUpdates(this);
        }
}
  public class LocationEventArgs : EventArgs, ILocationEventArgs
    {
        public double lat { get; set; }
        public double lng { get; set; }
    }

}

LocationModel

namespace Mig.Model
{
   public class LocationModel
    {
        public Coord coord { get; set; }
        public List<Weather> weather { get; set; }

        public string newdata { get; set; }
        public Main main { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public Sys sys { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }


    public class Coord
    {
        public double lon { get; set; }
        public double lat { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

    public class Main
    {
        public double temp { get; set; }
        public double pressure { get; set; }
        public int humidity { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
        public double sea_level { get; set; }
        public double grnd_level { get; set; }
    }

    public class Wind
    {
        public double speed { get; set; }
        public double deg { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Sys
    {
        public double message { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }
}

PCL Interface

namespace Mig
{
   public interface IMyLocation
    {
        void ObtainMyLocation();
        event EventHandler<ILocationEventArgs> locationObtained;
    }

    public interface ILocationEventArgs
    {
        double lat { get; set; }
        double lng { get; set; }
    }
}

Tuesday 29 November 2016

BindableObjectExtensions

namespace App1
{
    public static class BindableObjectExtensions
    {
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bindableObject">The bindable object.</param>
        /// <param name="property">The property.</param>
        /// <returns>T.</returns>
        public static T GetValue<T>(this BindableObject bindableObject, BindableProperty property)
        {
            return (T)bindableObject.GetValue(property);
        }
    }
}

EventArgs{T}

namespace App1
{
    public class EventArgs<T> : EventArgs
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EventArgs"/> class.
        /// </summary>
        /// <param name="value">Value of the argument</param>
        public EventArgs(T value)
        {
            this.Value = value;
        }

        /// <summary>
        /// Gets the value of the event argument
        /// </summary>
        public T Value { get; private set; }
    }
}

checkbox Renderer

[assembly: ExportRenderer(typeof(CheckBox), typeof(App1.Droid.CheckBoxRenderer))]
namespace App1.Droid
{
    public class CheckBoxRenderer : ViewRenderer<CheckBox, Android.Widget.CheckBox>
    {
        private ColorStateList defaultTextColor;

        /// <summary>
        /// Called when [element changed].
        /// </summary>
        /// <param name="e">The e.</param>
        protected override void OnElementChanged(ElementChangedEventArgs<CheckBox> e)
        {
            base.OnElementChanged(e);

            if (this.Control == null)
            {


                var checkBox = new Android.Widget.CheckBox(this.Context);

                checkBox.CheckedChange += CheckBoxCheckedChange;

                defaultTextColor = checkBox.TextColors;
                this.SetNativeControl(checkBox);
            }

            Control.Text = e.NewElement.Text;
            Control.Checked = e.NewElement.Checked;
            UpdateTextColor();

            if (e.NewElement.FontSize > 0)
            {
                Control.TextSize = (float)e.NewElement.FontSize;
            }

            if (!string.IsNullOrEmpty(e.NewElement.FontName))
            {
                Control.Typeface = TrySetFont(e.NewElement.FontName);
            }
        }

        /// <summary>
        /// Handles the <see cref="E:ElementPropertyChanged" /> event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            switch (e.PropertyName)
            {
                case "Checked":
                    Control.Text = Element.Text;
                    Control.Checked = Element.Checked;
                    break;
                case "TextColor":
                    UpdateTextColor();
                    break;
                case "FontName":
                    if (!string.IsNullOrEmpty(Element.FontName))
                    {
                        Control.Typeface = TrySetFont(Element.FontName);
                    }
                    break;
                case "FontSize":
                    if (Element.FontSize > 0)
                    {
                        Control.TextSize = (float)Element.FontSize;
                    }
                    break;
                case "CheckedText":
                case "UncheckedText":
                    Control.Text = Element.Text;
                    break;
                default:
                    System.Diagnostics.Debug.WriteLine("Property change for {0} has not been implemented.", e.PropertyName);
                    break;
            }
        }

        /// <summary>
        /// CheckBoxes the checked change.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Android.Widget.CompoundButton.CheckedChangeEventArgs"/> instance containing the event data.</param>
        void CheckBoxCheckedChange(object sender, Android.Widget.CompoundButton.CheckedChangeEventArgs e)
        {
            this.Element.Checked = e.IsChecked;
        }

        /// <summary>
        /// Tries the set font.
        /// </summary>
        /// <param name="fontName">Name of the font.</param>
        /// <returns>Typeface.</returns>
        private Typeface TrySetFont(string fontName)
        {
            Typeface tf = Typeface.Default;
            try
            {
                tf = Typeface.CreateFromAsset(Context.Assets, fontName);
                return tf;
            }
            catch (Exception ex)
            {
                Console.Write("not found in assets {0}", ex);
                try
                {
                    tf = Typeface.CreateFromFile(fontName);
                    return tf;
                }
                catch (Exception ex1)
                {
                    Console.Write(ex1);
                    return Typeface.Default;
                }
            }
        }

        /// <summary>
        /// Updates the color of the text
        /// </summary>
        private void UpdateTextColor()
        {
            if (Control == null || Element == null)
                return;

            if (Element.TextColor == Xamarin.Forms.Color.Default)
                Control.SetTextColor(defaultTextColor);
            else
                Control.SetTextColor(Element.TextColor.ToAndroid());
        }
    }
}

checkBox Control

namespace App1
{
   public class CheckBox : Xamarin.Forms.View
    {
        /// <summary>
        /// The checked state property.
        /// </summary>
        public static readonly BindableProperty CheckedProperty =
            BindableProperty.Create<CheckBox, bool>(
                p => p.Checked, false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged);

        /// <summary>
        /// The checked text property.
        /// </summary>
        public static readonly BindableProperty CheckedTextProperty =
            BindableProperty.Create<CheckBox, string>(
                p => p.CheckedText, string.Empty, BindingMode.TwoWay);

        /// <summary>
        /// The unchecked text property.
        /// </summary>
        public static readonly BindableProperty UncheckedTextProperty =
            BindableProperty.Create<CheckBox, string>(
                p => p.UncheckedText, string.Empty);

        /// <summary>
        /// The default text property.
        /// </summary>
        public static readonly BindableProperty DefaultTextProperty =
            BindableProperty.Create<CheckBox, string>(
                p => p.Text, string.Empty);

        /// <summary>
        /// Identifies the TextColor bindable property.
        /// </summary>
        ///
        /// <remarks/>
        public static readonly BindableProperty TextColorProperty =
            BindableProperty.Create<CheckBox, Color>(
                p => p.TextColor, Color.Default);

        /// <summary>
        /// The font size property
        /// </summary>
        public static readonly BindableProperty FontSizeProperty =
            BindableProperty.Create<CheckBox, double>(
                p => p.FontSize, -1);

        /// <summary>
        /// The font name property.
        /// </summary>
        public static readonly BindableProperty FontNameProperty =
            BindableProperty.Create<CheckBox, string>(
                p => p.FontName, string.Empty);


        /// <summary>
        /// The checked changed event.
        /// </summary>
        public event EventHandler<EventArgs<bool>> CheckedChanged;

        /// <summary>
        /// Gets or sets a value indicating whether the control is checked.
        /// </summary>
        /// <value>The checked state.</value>
        public bool Checked
        {
            get
            {
                return this.GetValue<bool>(CheckedProperty);
            }

            set
            {
                if (this.Checked != value)
                {
                    this.SetValue(CheckedProperty, value);
                    this.CheckedChanged.Invoke(this, value);
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating the checked text.
        /// </summary>
        /// <value>The checked state.</value>
        /// <remarks>
        /// Overwrites the default text property if set when checkbox is checked.
        /// </remarks>
        public string CheckedText
        {
            get
            {
                return this.GetValue<string>(CheckedTextProperty);
            }

            set
            {
                this.SetValue(CheckedTextProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether the control is checked.
        /// </summary>
        /// <value>The checked state.</value>
        /// <remarks>
        /// Overwrites the default text property if set when checkbox is checked.
        /// </remarks>
        public string UncheckedText
        {
            get
            {
                return this.GetValue<string>(UncheckedTextProperty);
            }

            set
            {
                this.SetValue(UncheckedTextProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        public string DefaultText
        {
            get
            {
                return this.GetValue<string>(DefaultTextProperty);
            }

            set
            {
                this.SetValue(DefaultTextProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the color of the text.
        /// </summary>
        /// <value>The color of the text.</value>
        public Color TextColor
        {
            get
            {
                return this.GetValue<Color>(TextColorProperty);
            }

            set
            {
                this.SetValue(TextColorProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the size of the font.
        /// </summary>
        /// <value>The size of the font.</value>
        public double FontSize
        {
            get
            {
                return (double)GetValue(FontSizeProperty);
            }
            set
            {
                SetValue(FontSizeProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the name of the font.
        /// </summary>
        /// <value>The name of the font.</value>
        public string FontName
        {
            get
            {
                return (string)GetValue(FontNameProperty);
            }
            set
            {
                SetValue(FontNameProperty, value);
            }
        }
        /// <summary>
        /// Gets the text.
        /// </summary>
        /// <value>The text.</value>
        public string Text
        {
            get
            {
                return this.Checked
                    ? (string.IsNullOrEmpty(this.CheckedText) ? this.DefaultText : this.CheckedText)
                        : (string.IsNullOrEmpty(this.UncheckedText) ? this.DefaultText : this.UncheckedText);
            }
        }

        /// <summary>
        /// Called when [checked property changed].
        /// </summary>
        /// <param name="bindable">The bindable.</param>
        /// <param name="oldvalue">if set to <c>true</c> [oldvalue].</param>
        /// <param name="newvalue">if set to <c>true</c> [newvalue].</param>
        private static void OnCheckedPropertyChanged(BindableObject bindable, bool oldvalue, bool newvalue)
        {
            var checkBox = (CheckBox)bindable;
            checkBox.Checked = newvalue;
        }
    }
}

Sunday 27 November 2016

SearchXaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="WrapPanelDemo.SearchMediPage"
              xmlns:controls="clr-namespace:WrapPanelDemo.Controls;assembly=WrapPanelDemo">
  <ContentPage.Content>
    <StackLayout Orientation="Vertical">
      <SearchBar x:Name="sbMedicionName" Placeholder="What tablets you are using?" TextChanged="searchTabletName" VerticalOptions="Start" />
      <!--<StackLayout x:Name="slNewItem">
        <Label Text="No search found" FontSize="20"/>
      </StackLayout>-->
      <controls:AwesomeWrappanel x:Name="lbxMedicionsList"  ItemsSource="{Binding Persons}" Orientation="Horizontal">
        <controls:AwesomeWrappanel.ItemTemplate>
          <DataTemplate>
            <StackLayout >
              <Button Text="{Binding Name}" BackgroundColor="Red"/>
            </StackLayout>
          </DataTemplate>
        </controls:AwesomeWrappanel.ItemTemplate>
      </controls:AwesomeWrappanel>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

Search

namespace WrapPanelDemo
{
    public partial class SearchMediPage : ContentPage, INotifyPropertyChanged
    {
   
        public ObservableCollection<Person> TempPersonsList = new ObservableCollection<Person>();
        public SearchMediPage()
        {
            //Persons = new ObservableCollection<Person>();
            InitializeComponent();
            BindingContext = this;
            bindMedicionData();
          // slNewItem.IsVisible = false;
        }
        public void bindMedicionData()
        {
            TempPersonsList.Add(new Person { Name = "sivakodna"});
            TempPersonsList.Add(new Person { Name = "venugopal"});
            TempPersonsList.Add(new Person { Name = "chiranjeevi"});
            TempPersonsList.Add(new Person { Name = "venu"});
            TempPersonsList.Add(new Person { Name = "venkatrao"});
            TempPersonsList.Add(new Person { Name = "venkatraosas"});
            TempPersonsList.Add(new Person { Name = "venkatraosa"});
            TempPersonsList.Add(new Person { Name = "sudhaka"});
            TempPersonsList.Add(new Person { Name = "venkatrao"});
            TempPersonsList.Add(new Person { Name = "chinnapa"});

            //TempPersonsList = _Persons.ToList();
            //_Persons.Clear();
            lbxMedicionsList.IsVisible = false;
        }
        public void searchTabletName(Object sender, TextChangedEventArgs e)
        {
            string strMedicionName = e.NewTextValue.ToLower().ToString();
            //var medicionsList = (from s in objMedicionsList where s.MedicionName.Contains(strMedicionName) select s).ToList();
            // objMedicionsList.Clear();
            if (strMedicionName.Length > 0)
            {
                var medicionsList = (from s in TempPersonsList where s.Name.StartsWith(strMedicionName) select s).ToList();
                if (medicionsList.Count > 0)
                {
                    _Persons.Clear();
               
                    foreach (var eachItem in medicionsList)
                    {
                        _Persons.Add(eachItem);
                    }

                    OnPropertyChanged("Persons");
                    // slNewItem.IsVisible = false;
                    lbxMedicionsList.IsVisible = true;
                }
                else
                {

                    _Persons.Clear();
                     OnPropertyChanged("Persons");
                    // slNewItem.IsVisible = true;
                    lbxMedicionsList.IsVisible = false;
                }
            }
        }

        private ObservableCollection<Person> _Persons = new ObservableCollection<Person>();
        public ObservableCollection<Person> Persons
        {
            get { return _Persons; }
            set
            {
                if (_Persons == value)
                    return;
                _Persons = value;
                OnPropertyChanged("Persons");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Wednesday 23 November 2016

Searchbar Example

 http://opensource.org/licenses/MIT
MainPage.XAML:-
--------------------------
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SearchbarExample"
             x:Class="SearchbarExample.MainPage">
  <ContentPage.Content>
    <StackLayout Orientation="Vertical">
      <SearchBar x:Name="sbMedicionName" Placeholder="What tablets you are using?" TextChanged="searchTabletName" VerticalOptions="Start" />
      <StackLayout x:Name="slNewItem">
        <Label Text="No search found" FontSize="20"/>
      </StackLayout>
      <ListView x:Name="lbxMedicionsList">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
              <Label x:Name="lablName" Text="{Binding MedicionName}"/>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

MainPage.XAML.Cs:-
--------------------------
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Collections.ObjectModel;

namespace SearchbarExample
{
    public partial class MainPage : ContentPage
    {
        ObservableCollection<Medision> objMedicionsList = null;
        public MainPage()
        {
            InitializeComponent();
            bindMedicionData();
            slNewItem.IsVisible = false;
        }

        public void bindMedicionData()
        {
            objMedicionsList = new ObservableCollection<Medision>();
            objMedicionsList.Add(new Medision { MedicionName = "venkatrao" });
            objMedicionsList.Add(new Medision { MedicionName = "chiranjeevi" });
            objMedicionsList.Add(new Medision { MedicionName = "sivakonda" });
            objMedicionsList.Add(new Medision { MedicionName = "sudhakar" });
            objMedicionsList.Add(new Medision { MedicionName = "venky" });
            objMedicionsList.Add(new Medision { MedicionName = "chinappureddy" });
            //lbxMedicionsList.ItemsSource = objMedicionsList;
        }
        public void searchTabletName(Object sender,TextChangedEventArgs e)
        {
            string strMedicionName = e.NewTextValue.ToLower().ToString();
            //var medicionsList = (from s in objMedicionsList where s.MedicionName.Contains(strMedicionName) select s).ToList();
            // objMedicionsList.Clear();
            if (strMedicionName.Length > 0) {
                var medicionsList = (from s in objMedicionsList where s.MedicionName.StartsWith(strMedicionName) select s).ToList();
                if (medicionsList.Count > 0)
                {
                    lbxMedicionsList.ItemsSource = medicionsList;
                    slNewItem.IsVisible = false;
                    lbxMedicionsList.IsVisible = true;
                }
                else
                {
                    slNewItem.IsVisible = true;
                    lbxMedicionsList.IsVisible = false;
                }
            }
        }
    }
}

Medision.Cs:-
----------------------
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SearchbarExample
{
   public class Medision
    {
        public string MedicionName { get; set; }
    }
}