Xamarin : SQLite Local Database



Xamarin : SQLite - Local Database



1. Install "SQLite.Net-PCL" package using nuget package manager. Install in all projects in solution.


2. Create service signature using interface.

using SQLite.Net;

namespace App_LocalDataBase
{
    public interface ISQLite
    {
        SQLiteConnection GetConnection();
    }
}

3. Create service manager to implement Interface method.

For Android
using System;
using Xamarin.Forms;
using LocalDataBase.Droid;
using System.IO;

[assembly: Dependency(typeof(SqliteService))]
namespace App_LocalDataBase.Droid
{
    public class SqliteService : ISQLite
    {
        public SqliteService() { }

        public SQLite.Net.SQLiteConnection GetConnection()
        {
            var sqliteFilename = "SQLiteEx.db3";
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);
            Console.WriteLine(path);
            if (!File.Exists(path)) File.Create(path);
            var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
            var conn = new SQLite.Net.SQLiteConnection(plat, path);
            // Return the database connection 
            return conn;
        } 
    }
}

4. Create class in Droid project  implement

using LocalDataBase.iOS;
using System;
using System.IO;
using Xamarin.Forms;

[assembly: Dependency(typeof(SqliteService))]
namespace App_LocalDataBase.iOS
{
    public class SqliteService : ISQLite
    {
        public SqliteService()
        {
        }

        public SQLite.Net.SQLiteConnection GetConnection()
        {
            var sqliteFilename = "SQLiteEx.db3";
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
            var path = Path.Combine(libraryPath, sqliteFilename);

            // This is where we copy in the prepopulated database
            Console.WriteLine(path);
            if (!File.Exists(path))
            {
                File.Create(path);
            }

            var plat = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
            var conn = new SQLite.Net.SQLiteConnection(plat, path);

            // Return the database connection 
            return conn;
        }
 }
}

5. Write database operation methods in PCL project. Create class name - DataAccess

using SQLite.Net;
using Xamarin.Forms;

namespace App_LocalDataBase
{
    public class DataAccess
    {
        SQLiteConnection dbConn;
        public DataAccess()
        {
            dbConn = DependencyService.Get<ISQLite>().GetConnection();
            // create the table(s)
            dbConn.CreateTable<Employee>();
        }
        public List<Employee> GetAllEmployees()
        {
            return dbConn.Query<Employee>("Select * From [Employee]");
        }
        public int SaveEmployee(Employee aEmployee)
        {
            return dbConn.Insert(aEmployee);            
        }
        public int DeleteEmployee(Employee aEmployee)
        {
            return dbConn.Delete(aEmployee);
        }
        public int EditEmployee(Employee aEmployee)
        {
            return dbConn.Update(aEmployee);
        }
    }
}

6. Create  table model in PCL project.

using SQLite.Net.Attributes;
using System;

namespace App_LocalDataBase
{
    public class Employee
    {
        [PrimaryKey, AutoIncrement]
        public long EmpId
        { get; set; }
        [NotNull]
        public string EmpName
        { get; set; }
        public string Designation
        { get; set; }
        public string Department
        { get; set; }
        public string Qualification
        { get; set; }
    }
}

7. Create the static object property of ‘DataAccess‘ in ‘App‘ class
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace App_LocalDataBase
{
    public class App : Application
    {
        static DataAccess dbUtils;
        public App()
        {
            // The root page of your application
            MainPage = new NavigationPage(new ManageEmployee());
        }
        public static DataAccess DAUtil
        {
            get
            {
                if (dbUtils == null)
                {
                    dbUtils = new DataAccess();
                }
                return dbUtils;
            }
        }
        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}
 
8. Now its turn to create CRUD operation

  1. Manage Employees (ManageEmployee.xaml)
  2. Add Employee (AddEmployee.xaml)
  3. Show Employee Details ShowEmplyee.xaml
  4. Edit Employee (EditEmployee.xaml)
9. Manage Employee page
Design 
<ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness" iOS="0, 20, 0, 0" />
  </ContentPage.Padding>
  <ContentPage.Content>
    <ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer"  ItemSelected="OnSelection" >
      <ListView.HeaderTemplate>
        <DataTemplate>
          <StackLayout Orientation="Horizontal" BackgroundColor="Blue" Padding="5,5,5,5">
            <Label Text="Name" FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
            <Label Text="Designation" FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
            <Label Text="Department" FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
          </StackLayout>
        </DataTemplate>
      </ListView.HeaderTemplate>
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Orientation="Horizontal" Padding="5,5,5,5">
              <Label Text="{Binding EmpName}" FontSize="Medium" />
              <Label Text="{Binding Designation}" FontSize="Medium" />
              <Label Text="{Binding Department}" FontSize="Medium" />
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
      <ListView.FooterTemplate>
        <DataTemplate>
          <StackLayout Orientation="Horizontal" Padding="5,5,5,5">
            <Button Text="Add New Employee" Clicked="OnNewClicked" />
          </StackLayout>
        </DataTemplate>
      </ListView.FooterTemplate>
    </ListView>
  </ContentPage.Content>
 

Code

public ManageEmployee()
        {
            InitializeComponent();
            var vList = App.DAUtil.GetAllEmployees();
            lstData.ItemsSource = vList;
        }
 
        void OnSelection(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return;
                //ItemSelected is called on deselection, 
                //which results in SelectedItem being set to null
            }
            var vSelUser = (Employee)e.SelectedItem;
            Navigation.PushAsync(new ShowEmplyee(vSelUser));
        }
        public void OnNewClicked(object sender, EventArgs args)
        {
            Navigation.PushAsync(new AddEmployee());
        }

10. Add Employee Page
Design 
<ContentView.Content>
    <TableView Intent="Settings" BackgroundColor="White">
      <TableRoot>
        <TableSection Title="Add New Employee">
          <EntryCell x:Name="txtEmpName" Label="Employee Name" Keyboard="Text" />
          <EntryCell x:Name="txtDesign" Label="Designation" Keyboard="Text" />
          <EntryCell x:Name="txtDepartment" Label="Department" Keyboard="Text" />
          <EntryCell x:Name="txtQualification" Label="Qualification" Keyboard="Text" />
          <ViewCell>
            <ContentView Padding="0,0">
              <ContentView.Padding>
                <OnPlatform x:TypeArguments="Thickness" iOS="10,0" WinPhone="0,15,0,0" />
              </ContentView.Padding>
              <ContentView.Content>
                <Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked" />
              </ContentView.Content>
            </ContentView>
          </ViewCell>
        </TableSection>
      </TableRoot>
    </TableView>
  </ContentView.Content>
 

Code
public AddEmployee()
        {
            InitializeComponent();
        }
 
        public void OnSaveClicked(object sender, EventArgs args)
        {
            var vEmployee = new Employee()
            {
                EmpName = txtEmpName.Text,
                Department = txtDepartment.Text,
                Designation = txtDesign.Text,
                Qualification = txtQualification.Text
            };
            App.DAUtil.SaveEmployee(vEmployee);
            Navigation.PushAsync(new ManageEmployee());
        }

11. View Employee Page
Design 

<ContentView.Content>
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
 
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="10"/>
      </Grid.ColumnDefinitions>
 
      <Label Grid.Row ="0" Grid.Column="0" Grid.ColumnSpan="2" Text="Employee Details" />
      <Label Grid.Row ="1" Grid.Column="1" Text="Name" />
      <Label Grid.Row="1" Grid.Column="2" Text ="{Binding EmpName}" />
      <Label Grid.Row ="2" Grid.Column="1" Text="Designation" />
      <Label Grid.Row="2" Grid.Column="2" Text ="{Binding Designation}"/>
      <Label Grid.Row ="3" Grid.Column="1" Text="Department" />
      <Label Grid.Row="3" Grid.Column="2" Text ="{Binding Department}"/>
      <Label Grid.Row ="4" Grid.Column="1" Text="Qualification" />
      <Label Grid.Row="4" Grid.Column="2" Text ="{Binding Qualification}" />
      <Button Grid.Row ="5" Grid.Column="1" Text="Edit Details" Clicked="OnEditClicked" />
      <Button Grid.Row="5" Grid.Column="2" Text="Delete" Clicked="OnDeleteClicked" />
    </Grid>
  </ContentView.Content>
 
 Code 
Employee mSelEmployee;
        public ShowEmplyee(Employee aSelectedEmp)
        {
            InitializeComponent();
            mSelEmployee = aSelectedEmp;
            BindingContext = mSelEmployee;
        }
 
        public void OnEditClicked(object sender, EventArgs args)
        {
           // Navigation.PushAsync(new EditEmployee(mSelEmployee));
        }
        public async void OnDeleteClicked(object sender, EventArgs args)
        {
            bool accepted = await DisplayAlert("Confirm""Are you Sure ?""Yes""No");
            if (accepted)
            {
                App.DAUtil.DeleteEmployee(mSelEmployee);
            }
            await Navigation.PushAsync(new ManageEmployee());
        }



12. Edit Employee Page

Design 
 <ContentView.Content>
    <TableView Intent="Settings" BackgroundColor="White">
      <TableRoot>
        <TableSection Title="Edit Employee">
          <EntryCell x:Name="txtEmpName" Label="Employee Name" Text ="{Binding EmpName}" Keyboard="Text" />
          <EntryCell x:Name="txtDesign" Label="Designation" Text ="{Binding Designation}" Keyboard="Text" />
          <EntryCell x:Name="txtDepartment" Label="Department" Text ="{Binding Department}" Keyboard="Text" />
          <EntryCell x:Name="txtQualification" Label="Qualification" Text ="{Binding Qualification}" Keyboard="Text" />
          <ViewCell>
            <ContentView Padding="0,0">
              <ContentView.Padding>
                <OnPlatform x:TypeArguments="Thickness" iOS="10,0" WinPhone="0,15,0,0" />
              </ContentView.Padding>
              <ContentView.Content>
                <Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked" />
              </ContentView.Content>
            </ContentView>
          </ViewCell>
        </TableSection>
      </TableRoot>
    </TableView>
  </ContentView.Content>


Code 

Employee mSelEmployee;
       public EditEmployee(Employee aSelectedEmp)
       {
           InitializeComponent();
           mSelEmployee = aSelectedEmp;
           BindingContext = mSelEmployee;
       }
 
       public void OnSaveClicked(object sender, EventArgs args)
       {
           mSelEmployee.EmpName = txtEmpName.Text;
           mSelEmployee.Department = txtDepartment.Text;
           mSelEmployee.Designation = txtDesign.Text;
           mSelEmployee.Qualification = txtQualification.Text;
           App.DAUtil.EditEmployee(mSelEmployee);
           Navigation.PushAsync(new ManageEmployee());
       }




Xamarin | How to set application published name and version



Xamarin | How to set application published name and version


Set Application name

1. Open "AndroidManifest.xml" file from ProjectName\ProjectName.Droid\Properties folder

2. set application name which you want in blow property,

<application android:label="MyApp"></application> 
 
 
 
 
 
Set Application Version

1. Open "AssemblyInfo.cs" file from ProjectName\ProjectName.Droid\Properties

2. Set version number which you want,

[assemblyAssemblyVersion("1.0.0.0")]
[assemblyAssemblyFileVersion("1.0.0.0")]

 

Xamarin : Splash Screen




Xamarin : Splash Screen



1. Create images for respective resolutions and store it in the same folder in Resources folder of "ProjectName.Droid" project

MDPI         =  320 × 480 dp = 320x480px (The Default x1)
XHDPI       =  2 x MDPI = 640x960px
XXHDPI     =  3 x MDPI = 960x1440px
XXXHDPI   =  4 x MDPI = 1280x1920px


2. Create new activity name "SplashActivity.cs" in Droid project 

    [Activity(Theme = "@style/Theme.Splash",
        MainLauncher = true,
        NoHistory = true)]
    public class SplashActivity : Activity
    {       
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            System.Threading.Thread.Sleep(3000);
            StartActivity(typeof(MainActivity));
        }
    }

3.  Open "MainActivity.cs"  File and set MainLauncher = false

4. Set styles, open styles.xml from Resources -> Values folder 

   <style name="Theme.Splash" parent="MainTheme.Base">
    <item name="android:background">@drawable/splashscreen</item>
    <item name="windowNoTitle">True</item>
  </style>

  <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">  </style>

5. Run the application and see the splash screen


6. For windows phone and windows 8.1 project, please follow the steps as mentioned in below image,





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;
            }