Xamarin : Master and Detail page


Xamarin : Master and Detail page



Steps 
  1. Create new page and give name "masterpage"
  2. Change "ContentPage" to "MasterDetailPage" at the fist line in the design 
  3. open cs file and inherit with "MasterDetailPage" public partial class MasterDetailMainPage : MasterDetailPage
  4. Add class name in the first tag line in the design
    xmlns:local="clr-namespace:App1;assembly=App1"  
    App1 is your application name
  5. Create left menu as below
      <MasterDetailPage.Master>
        <ContentPage Title="Menu">
          <StackLayout Orientation="Vertical">
            <Label Text="This is slide out menu"></Label>
            <Button Text="One" Clicked="Menu1"></Button>
            <Button Text="Two"  Clicked="Menu2"></Button>
            <Button Text="Three" Clicked="Menu3"></Button>
          </StackLayout>
        </ContentPage>
      </MasterDetailPage.Master>
    
    
  6. Create detail container view
    <MasterDetailPage.Detail>
        <ContentPage Title="Menu">
          <StackLayout Orientation="Vertical"></StackLayout>
        </ContentPage>
      </MasterDetailPage.Detail>
  7. Full design code as like below
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:local="clr-namespace:App1;assembly=App1"      
             x:Class="App1.MasterDetailMainPage"
                   Title="Master Detail Page">
 
  <MasterDetailPage.Master>
    <ContentPage Title="Menu">
      <StackLayout Orientation="Vertical">
        <Label Text="This is slide out menu"></Label>
        <Button Text="One" Clicked="Menu1"></Button>
        <Button Text="Two"  Clicked="Menu2"></Button>
        <Button Text="Three" Clicked="Menu3"></Button>
      </StackLayout>
    </ContentPage>
 
  </MasterDetailPage.Master>
  
  
  <MasterDetailPage.Detail>
    <ContentPage Title="Menu">
      <StackLayout Orientation="Vertical"></StackLayout>
    </ContentPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>


Code:
Write a code to redirect to menu selected page

Open file - MasterDetailMainPage.xaml.cs

        void Menu1(object sender, EventArgs e)
        {
            Detail = new NavigationPage(new MasterDetailPageOne());
            IsPresented = false;
        }
        void Menu2(object sender, EventArgs e)
        {
            Detail = new NavigationPage(new MasterDetailPageTwo());
            IsPresented = false;
        }
        void Menu3(object sender, EventArgs e)
        {
            Detail = new NavigationPage(new MasterDetailPageThree());
            IsPresented = false;
        }



Output





Xamarin : Create Carousel Page


Xamarin : Create Carousel Page



Steps

  1. Create new page
  2. Change "ContentPage" to "CarouselPage" on the first line of the design code
  3. Create multiple "ContentPage" tags, that how many you want carousel pages
  4. write design and code in "<StackLayout>" tag
    
    




<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.CarasoulSample">
 
  <ContentPage>
    <StackLayout>
 
      <Label Text="I am Red color"
           VerticalOptions="Start"
           HorizontalTextAlignment="Center"
           FontSize="Large"
           FontAttributes="Bold"
           TextColor="Red" />
 
      <BoxView Color="Red" VerticalOptions="FillAndExpand"></BoxView>
    </StackLayout>
  </ContentPage>
 
  <ContentPage>
    <StackLayout>
      <Label Text="I am Blue color"
           VerticalOptions="Start"
           HorizontalTextAlignment="Center"
           FontSize="Large"
           FontAttributes="Bold"
           TextColor="Blue" />
 
      <BoxView Color="Blue" VerticalOptions="FillAndExpand"></BoxView>
    </StackLayout>
  </ContentPage>
 
  <ContentPage>
 
    <StackLayout>
 
      <Label Text="I am Green color"
           VerticalOptions="Start"
           HorizontalTextAlignment="Center"
           FontSize="Large"
           FontAttributes="Bold"
           TextColor="Green" />
 
      <BoxView Color="Green" VerticalOptions="FillAndExpand"></BoxView>
    </StackLayout>
  </ContentPage>
</CarouselPage>

Xamarin : How to submit form data using API POST method

Xamarin : How to submit form data using API POST method



Design

<StackLayout Orientation="Vertical">
 
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="30"></RowDefinition>
      <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
 
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
 
    <Label Grid.Row="0" Grid.Column="0"  Text="Username:"></Label>
    <Entry Grid.Row="1" Grid.Column="0"  x:Name="txtUsername"></Entry>
                                         
    <Label Grid.Row="2" Grid.Column="0"  Text="Password:"></Label>
    <Entry Grid.Row="3" Grid.Column="0"  x:Name="txtPassword"></Entry>
                                         
    <Label Grid.Row="4" Grid.Column="0"  Text="First Name:"></Label>
    <Entry Grid.Row="5" Grid.Column="0"  x:Name="txtFirstName"></Entry>
                                         
    <Label Grid.Row="6" Grid.Column="0"  Text="Last Name:"></Label>
    <Entry Grid.Row="7" Grid.Column="0"  x:Name="txtLastName"></Entry>
                                         
    <Label Grid.Row="8" Grid.Column="0"  Text="Email:"></Label>
    <Entry Grid.Row="9" Grid.Column="0"  x:Name="txtEmailId"></Entry>
                                         
    <Label Grid.Row="10" Grid.Column="0" Text="Mobile:"></Label>
    <Entry Grid.Row="11" Grid.Column="0" x:Name="txtMobile"></Entry>
 
    <Label Grid.Row="12" Grid.Column="0" x:Name="OutputName" FontSize="15" 
                  HorizontalTextAlignment="Center" ></Label>
 
    <Button Grid.Row="13" Grid.Column="0" Text="Submit" Clicked="OnSubmit" ></Button>
    
  </Grid>
  </StackLayout>


Code


async void OnSubmit(object sender, EventArgs e)
       {
           if (!string.IsNullOrEmpty(txtUsername.Text) 
                  && !string.IsNullOrEmpty(txtPassword.Text) 
                  && !string.IsNullOrEmpty(txtFirstName.Text) 
                  && !string.IsNullOrEmpty(txtLastName.Text) 
                  && !string.IsNullOrEmpty(txtEmailId.Text) 
                  && !string.IsNullOrEmpty(txtMobile.Text))
           {
               try
               {
                   HttpClient client = new HttpClient();
 
                   string requestPayload = "{\"UserName\": \""+txtUsername.Text+"\"" + "," +
                           "\"Password\": \"" +txtPassword.Text+"\"" +","+ 
                           "\"FirstName\":\""+txtFirstName.Text+ "\"" + "," +
                           "\"LastName\": \"" +txtLastName.Text+ "\"" + "," +
                           "\"EmailId\":  \"" +txtEmailId.Text+ "\"" + "," +
                           "\"Mobile\":   \"" +txtMobile.Text+ "\"" + "}"  ;
                   var response = await client.PostAsync("http://domainname/DemoAPI/API/User/AddUser"
                                       new StringContent(requestPayload, Encoding.UTF8, "application/json"));
 
                   if (response.StatusCode == HttpStatusCode.OK)
                   {
                       OutputName.Text = "Data Saved.";
                   }
               }
               catch (Exception ex)
               {
                   OutputName.Text = ex.Message;
               }
           }
           else
           {
               OutputName.Text = "Please fill up complete form";
           }
       }

Output






Error : Validation failed for one or more entities. See 'EntityValidationErrors' property for more details



Validation failed for one or more entities. 

See 'EntityValidationErrors' property for more details





To resolve this issue, you can find where is the issue using below code...


 catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }

Xamarin : How to call API POST method




Xamarin : API call



How to consume API method in xamarin application ? 

I tried on google but couldn't find proper example. I got help of my friend who have knowledge of xamarin and some help from google, and created successful demo, which I am sharing with you.

Steps:
  1. First check that API is working or not
  2. Install "newtonsoft json" from NuGet package manager


Design 


<Grid>



    <Grid.RowDefinitions>

      <RowDefinition Height="50"></RowDefinition>

      <RowDefinition Height="50"></RowDefinition>

      <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"></ColumnDefinition>      
    </Grid.ColumnDefinitions>

    <Button Text="Get Data"
            Clicked="OnGetDataButtonClicked"
            Grid.Row="0"
            Grid.Column="0"></Button>
    <Label x:Name="lblMsg"
           Grid.Row="1"
           Grid.Column="0"></Label>

    <ListView x:Name="MainList"  ItemTapped="OnTapped" Grid.Row="2" Grid.Column="0"> 
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Orientation="Horizontal">
              <Label Text="{Binding EmailId}"></Label> 
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    
  </Grid>


Code

async void OnGetDataButtonClicked(object sender, EventArgs e)
        {
            try
            {
                HttpClient client = new HttpClient();

                string requestPayload = @"{
""UserId"": ""123"",
""dataTableCommon"":{
""param"" :{""Start"": ""21"",
""Length"": ""10"",
""Draw"" :""1""}
}
}";
                var response = await client.PostAsync("http://Domainname/DemoAPI/API/User/GetUsersList", 
new StringContent(requestPayload, Encoding.UTF8, "application/json"));

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var json = await response.Content.ReadAsStringAsync();
   
                    //Here you need to create class for output results
    // To generate class, you can use http://json2csharp.com

                    var results = JsonConvert.DeserializeObject<RootObject>(json);

                    MainList.ItemsSource = results.data;                    
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;
            }            
        }

        void OnTapped(object sender, ItemTappedEventArgs e)
        {
            var selected = e.Item as Users;

            DisplayAlert("Name", selected.FirstName + " " + selected.LastName, "Okay");
        }


Generate Class

    // To generate class, you can use http://json2csharp.com

    

    public class Users

    {

        public string UserId { get; set; }    

        public string FirstName { get; set; }

        public string LastName { get; set; }
        public string EmailId { get; set; }
    }

    public class RootObject
    {        
        public List<Users> data { get; set; } 
    }


Output


























































I hope, you like the article !!! ENJOY !!!



Xamarin : Resource Contents - Stylesheet



Xamarin : Resource Contents - Stylesheet


Design Page

<ContentPage.Resources>
    <ResourceDictionary>
      <Style x:Key="ColorfullLabel" TargetType="Label">
        <Setter Property="TextColor" Value="Red"></Setter>
        <Setter Property="BackgroundColor" Value="Yellow"></Setter>
      </Style>
      <Style x:Key="lblMargin" TargetType="Label">
        <Setter Property="Margin" Value="20"></Setter>
        <Setter Property="FontSize" Value="20"></Setter>
      </Style>
      <Style x:Key="btnMargin" TargetType="Button">
        <Setter Property="Margin" Value="20"></Setter>
        <Setter Property="FontSize" Value="20"></Setter>
        <Setter Property="Rotation" Value="20"></Setter>
        <Setter Property="BorderWidth" Value="20"></Setter>
      </Style>
    </ResourceDictionary>
  </ContentPage.Resources>
  
  <StackLayout Orientation="Vertical">

    <Label Text="Different color"
           Style="{StaticResource ColorfullLabel}"></Label>

    <Label Text="Font Size"
           FontSize="20"></Label>

    <Label Text="Margin"
           Style="{StaticResource lblMargin}"></Label>

    <Label Text="Italic"
           FontAttributes="Italic"></Label>

    <Label Text="Left Justified"
           HorizontalTextAlignment="End"
           FontSize="Large"></Label>

    <Label Text="Hello, World!"
         VerticalOptions="Start"
         HorizontalTextAlignment="Center"
         Rotation="-15"
         IsVisible="true"
         FontSize="Large"
         FontAttributes="Bold"
         TextColor="Blue" />

    <Button Text="Verticle Button"
        Style="{StaticResource btnMargin}">
    </Button>

  </StackLayout>