Published April 22, 2017 by with 5 comments

Cognitive Services Computer Vision In Xamarin Forms


Before jumping into the cognitive service, we first have an idea of what the cognitive services do in the real life. So let us take a real life example of a Blind Person. Saqib Sheikh is blind from both eyes and he lost his vision at the age of seven. However, thanks to Microsoft Cognitive services he is still feels the emotions as well as picture of everything by using the Microsoft Cognitive Services. So today, we are talking about the World best Cognitive Services from the Microsoft end and latter we will implement this in Xamarin Forms so every single person can enjoy the Cognitive Services.
So let’s get started, The very first thing you need to know is Restful Api and then you simply switch to https://www.microsoft.com/cognitive-services where we have couple of restful API’s . So in short, we will consume the rest API’s in Xamarin Forms by using the Vision Nugget Package. So let’s switch to Visual Studio 2015 or Xamarin Studio and create a new project, add a few xaml lines to your xaml file i.e.
<StackLayout Padding="50">
    <Button x:Name="BtnImage" Text="Pick Image" Clicked="BtnImage_OnClicked" />
    <Image x:Name="Img" WidthRequest="200" HeightRequest="200"/>
    <Label x:Name="LblResult" FontSize="32"  />
  </StackLayout>
Then import a following nugget package Microsoft.ProjectOxford.Vision
After this add one more package for Camera that is Xam.Plugin.Media.
Now just initialize the Camera and add a few lines of code so you could access the camera of mobile and desktop devices.

var media = Plugin.Media.CrossMedia.Current;
await media.Initialize();
var file = await media.TakePhotoAsync(new StoreCameraMediaOptions { SaveToAlbum = false });
Img.Source = ImageSource.FromStream(() => file.GetStream());
Then it’s time to call a vision client just like HttpClient.
Therefore, what I am going to do is I will simply add few lines of code here for accessing the Cognitive Services calling and feedback response and then populate the actual result into the Label.

  var visionclient = new VisionServiceClient(visionKey);
  var result = await visionclient.DescribeAsync(file.GetStream());
  LblResult.Text = result.Description.Captions.First().Text;

Then it's time to call the Dispose function to avoid memory leakage and memory flaws in your applications by using the following line i.e. 
file.Dispose();
Now all you need is just a device or an internet connection for accessing the JSON response and calling to the Microsoft cognitive services API.
Let us see how it looks like when I take a picture from camera and what comes via JSON response.
                                                


Read More
Published April 15, 2017 by with 23 comments

Shopping Cart Counter In Navigation Bar

Many of you have tried the Navigation Bar in xamarin forms.But it has some limitations and you can't do every thing with this. For example many people want's to add an eCommerce cart counter in the navigation bar but unfortunately xamarin forms don't have any kinda such navigation bar as well.Yeah most people show some intelligence and they install third party plugins for that purpose. However this is not good approach to handle such kinda things. Also some plugins are not free and they charge heavy amount for a single code repository. What I'm trying to say is please don't install or purchase third party plugins because we'll do in xamarin forms XAML and C# as well. So let's jump into the code section. Create a new project and add a few lines of code in your Main Page . So what I'm gonna do is I'll simply add a new button on Page 1 and also make a clicked event of this button with the following lines of code.

    <StackLayout Spacing="0" VerticalOptions="Center">
    <Image Source="http://cdn.playbuzz.com/cdn/ca011f28-6e7a-4b07-8eb8-ff122e799508/c0439c4d-891a-410a-8a24-b3b586bced7a.jpg"
WidthRequest="320"
HeightRequest="480"
Aspect="AspectFit"/>
    <Button Text="Go to Page 2" Clicked="Button_OnClicked"/>
  </StackLayout>

After this simply add few lines of code in the code behind of Page 1. 

 public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();
            BindingContext = this;
        }

        private async void Button_OnClicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new ProfilePagexaml());
        }
    }

So once you've done with the Main Page simply add a new Content View for your custom Navigation Bar and simply add the few lines of code .

<ContentView.Content>
<Grid RowSpacing="0" ColumnSpacing="0" BackgroundColor="#F44336">
<Grid.RowDefinitions>
<RowDefinition Height="44"></RowDefinition>
<RowDefinition Height="1"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="44"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ContentView Grid.Row="0" Grid.Column="0">
<Image Source="https://maxcdn.icons8.com/Share/icon/androidL/Arrows//back1600.png" 
WidthRequest="30" 
HeightRequest="30"
HorizontalOptions="Center" VerticalOptions="Center"/>
<ContentView.GestureRecognizers>
    <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped"  />
</ContentView.GestureRecognizers>
</ContentView>
<Label x:Name="lblTitle" TextColor="#333333"
HorizontalOptions="CenterAndExpand" 
VerticalOptions="CenterAndExpand"
Grid.Row="0" Grid.Column="1"/>
<ContentView Grid.Row="0" Grid.Column="2" Margin="0,5,5,0">
        
  <RelativeLayout>

    <Image Source="http://simpleicon.com/wp-content/uploads/Shopping-Cart-9.png" HeightRequest="30" WidthRequest="30" x:Name="yellowBoxView"
             RelativeLayout.YConstraint="{ConstraintExpression 
         Type=RelativeToParent,
         Property=Height,
         Factor=0.018,Constant=0}"
       
        RelativeLayout.XConstraint="{ConstraintExpression 
         Type=RelativeToParent,
         Property=Width,
         Factor=0.85,Constant=0}"
    />

    <Image Source="http://www.iconsdb.com/icons/preview/red/circle-xxl.png" HeightRequest="15" WidthRequest="15" x:Name="redBoxView"
             RelativeLayout.YConstraint="{ConstraintExpression 
         Type=RelativeToView,
         Property=Y,
         ElementName=yellowBoxView,
         Factor=1,Constant=-5}"
       
        RelativeLayout.XConstraint="{ConstraintExpression 
         Type=RelativeToView,
         Property=X,
         ElementName=yellowBoxView,
         Factor=1,Constant=25}"
    />
    <Label HorizontalTextAlignment="Center"  FontSize="9" TextColor="White" HeightRequest="10" WidthRequest="20" x:Name="labelText"
               RelativeLayout.YConstraint="{ConstraintExpression 
         Type=RelativeToView,
         Property=Y,
         ElementName=yellowBoxView,
         Factor=1,Constant=-5}"
       
          RelativeLayout.XConstraint="{ConstraintExpression 
         Type=RelativeToView,
         Property=X,
         ElementName=yellowBoxView,
         Factor=1,Constant=25}"
    />

</RelativeLayout>
        
<ContentView.GestureRecognizers>
    <TapGestureRecognizer x:Name="tapcart" Tapped="Tapcart_OnTapped" />
</ContentView.GestureRecognizers>
</ContentView>
      
<BoxView BackgroundColor="Red" Grid.ColumnSpan="3"
Grid.Row="1" Grid.Column="0" />
</Grid>
</ContentView.Content>

Also add  the following backend for Content View as well .

  public partial class NavigationBarViewxaml : ContentView
    {
        public NavigationBarViewxaml()
        {
            InitializeComponent();
        }

        public Label FirstNameLabel
        {
            get
            {
                return labelText;
            }
        }

        private void TapGestureRecognizer_OnTapped(object sender, EventArgs e)
        {
            Navigation.PopAsync();
        }

        public static readonly BindableProperty TitleProperty =
            BindableProperty.Create(
                "Title",
                typeof(string),
                typeof(NavigationBarViewxaml),
                "this is Title",
                propertyChanged: OnTitlePropertyChanged
            );
        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        static void OnTitlePropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var thisView = bindable as NavigationBarViewxaml;
            var title = newValue.ToString();
            thisView.lblTitle.Text = title;
        }

        private void Tapcart_OnTapped(object sender, EventArgs e)
        {
            Navigation.PushAsync(new MainPage());
        }
    }

Now the next step is to add a New Page in your Xamarin Forms Project and add the Content Page code along with the Navigation Content View that I've created so far.

<?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:xWebService="clr-namespace:X_WebService;assembly=X_WebService"
             x:Class="X_WebService.ProfilePagexaml" 
             NavigationPage.HasNavigationBar="false"
            NavigationPage.HasBackButton="false" Title="Profile Is Happy">

  <ContentPage.Content>
    <StackLayout Spacing="0">
      <StackLayout>
        <xWebService:NavigationBarViewxaml x:Name="NavigationBarView" Title="{Binding Title}"  />
        <Label Text="Asfend"/>
        <Label Text="asfend@hotmail.com"/>
        <Label Text="+923114737885"/>
        
        <Button Text="Leave" Clicked="Button_OnClicked" />
        <Button Text="Add to Cart" x:Name="BtnIncrement" Clicked="BtnIncrement_OnClicked"></Button>
      </StackLayout>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

Also add some backend code as well. 

    public partial class ProfilePagexaml : ContentPage
    {
        public ProfilePagexaml()
        {
            InitializeComponent();
            BindingContext = this;

        }

        protected override bool OnBackButtonPressed()
        {
            return true;
        }
        private async void Button_OnClicked(object sender, EventArgs e)
        {
            await Navigation.PopAsync();
        }

       public double clicks = 0;
        private void BtnIncrement_OnClicked(object sender, EventArgs e)
        {
             clicks += 1;
            NavigationBarView.FirstNameLabel.Text = clicks.ToString();

        }
    }

Now one last thing is to make your Page 1 as root by simply going into the App.xaml.cs and in the constructor of the page set MainPage = new NavigationPage(new Page1);


Now it's time to watch the magic with the following output ...













Read More
Published April 06, 2017 by with 5 comments

StackLayout In Xamarin Forms

Stack Layout is used to arrange the view in one aspect . It could be vertical or horizontal . Stack Layout is the most simple layout control in xamarin forms.
We can also use nested Stack Layout depending on our requirements.
We can design beautiful Screens by using the Stack Layout. If you're familiar with the Microsoft XAML for UWP and WPF where we used the StackPanel then you could easily understand the Stack Layout as well.

Let's design a Login Screen by using Stack Layout and from that you'll get a clear point of how to use that control in xamarin forms.

So let's Add a few lines of XAML code in the Content Page. Let's create a beautiful Skype Login Page with the Stack Layout so let's switch to Visual Studio Or Xamarin Studio and add few lines of code there.


By default the orientation of StackLayout is Vertical but if you want the horizontal fashion of Stack Layout then you can easily do that by simply adding an Orientation = "Horizontal" in the Stack Layout .


<?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:XF_Blogger"
             x:Class="XF_Blogger.MainPage" BackgroundColor="#00aff0">

  <StackLayout Margin="15,50,15,0">
    <Image Source="skype.png" VerticalOptions="Center" HorizontalOptions="Center"/>
    <StackLayout VerticalOptions="Center">
      <Entry BackgroundColor="White" Placeholder="Enter Skype ID" PlaceholderColor="Gray"/>
      <Entry BackgroundColor="White" Placeholder="Password" PlaceholderColor="Gray"/>
      <Button BackgroundColor="#078fc1" Text="Sign In"/>
      <Label Text="Problems signing in?" HorizontalTextAlignment="Center"></Label>
    </StackLayout>
  </StackLayout>
</ContentPage>

Now let's run this on the simulator or real device and just look at your UI for Login screen.



WOW ... Amazing it seems that we've almost design the same kinda Login Page in Xamarin Forms by just using the XAML.

Read More
Published April 06, 2017 by with 1 comment

Grid In Xamarin Forms


In this article we’ll learn about Grid in Xamarin Forms. Basically grid is used for arranging views into rows and columns. Although StackLayout is good enough but when we want to create some complex layout then it’s better to use Grid. If you ever see a graph paper then it’s easy for you to learn the Grid in xamarin forms.

      
So before going into detail you’ve to learn three more important things that’s RowDefinitions and ColumnDefinitions and Height and Width of these two.
After creating the grid we first define its rows and latter define the height of rows after this we’ll need to define a column and width of this column.   
Let’s look at the following code.
<Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*" />
      <RowDefinition Height="*" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
   
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
</Grid>
The important point here is that you’ll see Height="*" and Width="*" .Don’t confuse with these asterisk (*).It means specifying one row or a column with Height="*" or Width="*"will cause it to fill the available space.
Now let’s add four different BoxView controls in xaml page and give the reference of these Grid.Row and Grid.Columns.The important point to remember is that we’ll set Grid.Row  = 0 and Grid. Column = 0 for first row and first column .In precise Rows and Columns starts with 0 not 1 just like arrays.    



Let’s try to run it and see what’s happening on the device screen. I’ll test it on Android Device. The result will be the same on iOS as well as Windows Device family.



It makes sense but we’ve space left for one BoxView .What if we want to expand the Blue BoxView then we’ll add Grid.ColumnSpan="2" and it will expand it to two Columns the same concept applies with Rows.
                                                               

Hope it’ll makes sense. Let’s run it one more time and try to figure out what’s actually happening.
                                                            
Read More