CRUD operations in UWA using Web API

In this article we will learn how to achieve CRUD (Create, Read, Update, and Delete) operations in UWA (Universal Windows App) using Web API.

First of all create a new Web API.

Create Web API

  • Start Visual Studio 2015
  • Create a new project
  • Click Visual C# and Web
  • Click on ASP.NET Web Application
  • Provide the name and location of project and OK


Image 1.

Now select Web API template and click OK.


Image 2.

Without wasting no more time I am attaching a screenshot of my Web API Data.


Image 3.

Getting Started UWA

Here are the steps to get started with Windows Universal App:

  • Start Visual Studio 2015
  • Create a new project
  • Click Visual C# and Windows, then select Universal
  • Click on Blank App (Universal Windows)
  • Provide the name and location of project
  • Click OK


Image 4.

First of all start App.xaml.cs and declare the members and initialize the singleton application object.

  1. // Declare the members  
  2.   
  3. public static Uri BaseUri = new Uri("http://localhost:40752/api/books");  
  4.   
  5. public static Frame RootFrame { get; set; }  
  6.   
  7. public static Book Books { get; set; }  
  8.   
  9. public App()  
  10.   
  11. {  
  12.   
  13. this.InitializeComponent();  
  14.   
  15. this.Suspending += OnSuspending;  
  16.   
  17. using (var client = new HttpClient())  
  18.   
  19. {  
  20.   
  21. var response = "";  
  22.   
  23. client.MaxResponseContentBufferSize = 266000;  
  24.   
  25. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  26.   
  27. Task task = Task.Run(async () =>  
  28.   
  29. {  
  30.   
  31. response = await client.GetStringAsync(App.BaseUri);  
  32.   
  33. });  
  34.   
  35. task.Wait(); // Wait  
  36.   
  37. App.Books = JsonConvert.DeserializeObject<List<Book>>(response)[0];  
  38.   
  39. }  
  40.   
  41. }  

 

Now change RootFrame which is initialized as Frame property in OnLaunched application event.

  1. protected override void OnLaunched(LaunchActivatedEventArgs e)  
  2.   
  3. {  
  4.   
  5. #if DEBUG  
  6.   
  7. if (System.Diagnostics.Debugger.IsAttached)  
  8.   
  9. {  
  10.   
  11. this.DebugSettings.EnableFrameRateCounter = true;  
  12.   
  13. }  
  14.   
  15. #endif  
  16.   
  17. RootFrame = Window.Current.Content as Frame;  
  18.   
  19. // Do not repeat app initialization when the Window already has content,  
  20.   
  21. // just ensure that the window is active  
  22.   
  23. if (RootFrame == null)  
  24.   
  25. {  
  26.   
  27. // Create a Frame to act as the navigation context and navigate to the first page  
  28.   
  29. RootFrame = new Frame();  
  30.   
  31. RootFrame.NavigationFailed += OnNavigationFailed;  
  32.   
  33. if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)  
  34.   
  35. {  
  36.   
  37. //TODO: Load state from previously suspended application  
  38.   
  39. }  
  40.   
  41. // Place the frame in the current Window  
  42.   
  43. Window.Current.Content = RootFrame;  
  44.   
  45. }  
  46.   
  47. if (RootFrame.Content == null)  
  48.   
  49. {  
  50.   
  51. // When the navigation stack isn't restored navigate to the first page,  
  52.   
  53. // configuring the new page by passing required information as a navigation  
  54.   
  55. // parameter  
  56.   
  57. RootFrame.Navigate(typeof(MyBooks), e.Arguments);  
  58.   
  59. }  
  60.   
  61. // Ensure the current window is active  
  62.   
  63. Window.Current.Activate();  
  64.   
  65. }  
Now let’s add some buttons on a page for CRUD operations and navigate to them on specific pages.

 

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid Margin="10">

<Grid.RowDefinitions>

<RowDefinition Height="110"/>

<RowDefinition />

</Grid.RowDefinitions>

<StackPanel Grid.Row="0">

<TextBlock FontSize="30" HorizontalAlignment="Center" FontWeight="Bold">Universal Windows App Using Web API</TextBlock>

<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" FontStyle="Italic">This application would guide you through different stages of performing CRUDs operations in Universal Windows APP using WebAPI.</TextBlock>

</StackPanel>

<StackPanel Grid.Row="1" Margin="10, 0, 10, 0">

<Button Margin="0, 10, 0, 0" Click="Button_Click">Create New Book</Button>

<Button Margin="0, 10, 0, 0" Click="Button_Click">My Books</Button>

<Button Margin="0, 10, 0, 0" Click="Button_Click">Update Book</Button>

<Button Margin="0, 10, 0, 0" Click="Button_Click">Delete a Book</Button>

</StackPanel>

</Grid>

</Grid>

  1. private void Button_Click(object sender, RoutedEventArgs e)  
  2.   
  3. {  
  4.   
  5. switch ((sender as Button).Content.ToString())  
  6.   
  7. {  
  8.   
  9. case "Create":  
  10.   
  11. App.RootFrame.Navigate(typeof(CreateOrUpdate), true);  
  12.   
  13. break;  
  14.   
  15. case "My Books":  
  16.   
  17. App.RootFrame.Navigate(typeof(ShowBooks));  
  18.   
  19. break;  
  20.   
  21. case "Update Book":  
  22.   
  23. App.RootFrame.Navigate(typeof(CreateOrUpdate), false);  
  24.   
  25. break;  
  26.   
  27. case "Delete":  
  28.   
  29. App.RootFrame.Navigate(typeof(DeleteBook));  
  30.   
  31. break;  
  32.   
  33. default:  
  34.   
  35. break;  
  36.   
  37. }  
  38.   
  39. }  
Now let’s show books list on ShowBooks page.

 

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" >

<Grid Name="viewList">

<Grid.RowDefinitions>

<RowDefinition Height="100"/>

<RowDefinition />

</Grid.RowDefinitions>

<StackPanel Grid.Row="0">

<TextBlock FontSize="25" FontWeight="Bold" HorizontalAlignment="Center">Books</TextBlock>

<TextBlock HorizontalAlignment="Center">On this page you will see a list of books.</TextBlock>

<Button Margin="10, 0, 0, 0" Click="Button_Click">Go Back</Button>

</StackPanel>

<StackPanel Grid.Row="1">

<ListView Name="listView" SelectionChanged="listView_SelectionChanged" >

<ListView.ItemTemplate>

<DataTemplate>

<Grid Margin="5" Background="AliceBlue" Width="900" >

<Grid.RowDefinitions>

<RowDefinition></RowDefinition>

<RowDefinition></RowDefinition>

<RowDefinition></RowDefinition>

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="300"></ColumnDefinition>

<ColumnDefinition Width="200"></ColumnDefinition>

<ColumnDefinition></ColumnDefinition>

</Grid.ColumnDefinitions>

<TextBlock Text="{Binding Title}" Grid.Row="0" Grid.Column="0" Style="{StaticResource BaseTextBlockStyle}"></TextBlock>

<TextBlock Text="{Binding PublishDate}" Grid.Row="0" Grid.Column="1" Style="{StaticResource CaptionTextBlockStyle}"></TextBlock>

<TextBlock Text="{Binding Author}" Grid.Row="0" Grid.Column="2" Style="{StaticResource CaptionTextBlockStyle}"></TextBlock>

<TextBlock Text="{Binding Description}" Grid.Row="1" Grid.ColumnSpan="2"></TextBlock>

<TextBlock Text="{Binding Price}" Grid.Row="2" Grid.Column="0"></TextBlock>

<TextBlock Text="{Binding Genre}" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="1"></TextBlock>

</Grid>

</DataTemplate>

</ListView.ItemTemplate>

</ListView>

</StackPanel>

</Grid>

<Grid Name="viewSingle" Visibility="Collapsed">

<StackPanel Margin="10">

<TextBlock Name="Title" Style="{StaticResource BaseTextBlockStyle}"></TextBlock>

<TextBlock Name="Author" FontStyle="Italic"></TextBlock>

<TextBlock Name="Genre" FontStyle="Italic"></TextBlock>

<TextBlock Name="Price" FontStyle="Italic"></TextBlock>

<TextBlock Name="PublishDate" FontStyle="Italic"></TextBlock>

<TextBlock Name="Descrition" FontStyle="Italic"></TextBlock>

<Button Click="Button_Click">View Books</Button>

</StackPanel>

</Grid>

</Grid>

  1. protected override void OnNavigatedTo(NavigationEventArgs e)  
  2.   
  3. {  
  4.   
  5. using (var client = new HttpClient())  
  6.   
  7. {  
  8.   
  9. var response = "";  
  10.   
  11. Task task = Task.Run(async () =>  
  12.   
  13. {  
  14.   
  15. response = await client.GetStringAsync(App.BaseUri);  
  16.   
  17. });  
  18.   
  19. task.Wait(); // Wait  
  20.   
  21. listView.ItemsSource = JsonConvert.DeserializeObject<List<Book>>(response);  
  22.   
  23. App.Books = JsonConvert.DeserializeObject<List<Book>>(response)[0];  
  24.   
  25. }  
  26.   
  27. }  
  28.   
  29. private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)  
  30.   
  31. {  
  32.   
  33. var item = ((sender as ListView).SelectedItem as Book);  
  34.   
  35. App.Books = item;  
  36.   
  37. Title.Text = item.Title;  
  38.   
  39. Author.Text = item.Author;  
  40.   
  41. Genre.Text = item.Genre;  
  42.   
  43. Price.Text = item.Price.ToString();  
  44.   
  45. PublishDate.Text = item.PublishDate.ToString();  
  46.   
  47. Descrition.Text = item.Description;  
  48.   
  49. // Change the UI  
  50.   
  51. viewList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;  
  52.   
  53. viewSingle.Visibility = Windows.UI.Xaml.Visibility.Visible;  
  54.   
  55. }  
  56.   
  57. private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)  
  58.   
  59. {  
  60.   
  61. switch ((sender as Button).Content.ToString())  
  62.   
  63. {  
  64.   
  65. case "Go Back":  
  66.   
  67. App.RootFrame.Navigate(typeof(MyBooks));  
  68.   
  69. break;  
  70.   
  71. case "View Books":  
  72.   
  73. viewList.Visibility = Windows.UI.Xaml.Visibility.Visible;  
  74.   
  75. viewSingle.Visibility = Windows.UI.Xaml.Visibility.Collapsed;  
  76.   
  77. break;  
  78.   
  79. default:  
  80.   
  81. break;  
  82.   
  83. }  
  84. }  

 


Image 5.

If you click on a book.


Image 6.

Click on delete button

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<StackPanel Name="panel" Margin="10">

<TextBlock Name="message"></TextBlock>

<Button Click="Button_Click">Yes</Button>

<Button Click="Button_Click" Margin="70, -33, 0, 0">Cancel</Button>

</StackPanel>

</Grid>

  1. protected override void OnNavigatedTo(NavigationEventArgs e)  
  2.   
  3. {  
  4.   
  5. message.Text = string.Format("Are you sure you want to delete {0}?", App.Books.Title);  
  6.   
  7. }  
  8.   
  9. private void Button_Click(object sender, RoutedEventArgs e)  
  10.   
  11. {  
  12.   
  13. switch ((sender as Button).Content.ToString())  
  14.   
  15. {  
  16.   
  17. case "Yes":  
  18.   
  19. // Send a request to delete the book  
  20.   
  21. using (var client = new HttpClient())  
  22.   
  23. {  
  24.   
  25. Task task = Task.Run(async () =>  
  26.   
  27. {  
  28.   
  29. await client.DeleteAsync(App.BaseUri + "/" + App.Books.Id.ToString());  
  30.   
  31. });  
  32.   
  33. task.Wait();  
  34.   
  35. }  
  36.   
  37. App.RootFrame.Navigate(typeof(ShowBooks));  
  38.   
  39. break;  
  40.   
  41. case "Cancel":  
  42.   
  43. App.RootFrame.Navigate(typeof(ShowBooks));  
  44.   
  45. break;  
  46.   
  47. default:  
  48.   
  49. break;  
  50.   
  51. }  
  52.   
  53. }  

 

Image 7.

Create a new record

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid.RowDefinitions>

<RowDefinition Height="80"/>

<RowDefinition Height="220"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel Grid.Row="0">

<TextBlock FontSize="25" FontWeight="Bold" HorizontalAlignment="Center">Create a new Book</TextBlock>

<TextBlock FontStyle="Italic" HorizontalAlignment="Center">Update the following form and submit. It would update the current data source in Web API.</TextBlock>

</StackPanel>

<StackPanel Grid.Row="1" Margin="0,0,0,10" Grid.RowSpan="2">

<Grid Height="310" Margin="20, 10, 10, 0">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="100"/>

<ColumnDefinition />

</Grid.ColumnDefinitions>

<StackPanel Grid.Column="0" Margin="0,0,0,60" d:LayoutOverrides="TopPosition, BottomPosition">

<TextBlock Margin="0, 10, 0, 8">

<Run Text="Id"/>

</TextBlock>

<TextBlock Margin="0, 6, 0, 8">

<Run Text="Title"/>

</TextBlock>

<TextBlock Margin="0, 7, 0, 6">

<Run Text="Author"/>

</TextBlock>

<TextBlock Margin="0, 10, 0, 0">

<Run Text="Genre"/>

</TextBlock>

<TextBlock Margin="0, 10, 0, 0">

<Run Text="Price"/>

</TextBlock>

<TextBlock Margin="0, 20, 0, 0">

<Run Text="Publish Date"/>

</TextBlock>

<TextBlock Margin="0, 20, 0, 0">

<Run Text="Description"/>

</TextBlock>

</StackPanel>

<StackPanel Grid.Column="1" Margin="0,0,0,60" d:LayoutOverrides="TopPosition, BottomPosition">

<TextBox x:Name="Id" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Title" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Author" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Genre" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Price" Margin="0, 2, 0, 2"/>

<TextBox x:Name="PublishDate" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Description" Margin="0, 2, 0, 2"/>

</StackPanel>

<Button x:Name="actionButton" Grid.Column="1" Margin="0,0,0,4" Click="Button_Click" VerticalAlignment="Bottom" Content="Create"/>

</Grid>

<Button Margin="20, 0, 0, 0" Click="Button_Click">Cancel</Button>

</StackPanel>

</Grid>

  1. private void Button_Click(object sender, RoutedEventArgs e)  
  2.   
  3. {  
  4.   
  5. if ((sender as Button).Content.ToString() == "Cancel")  
  6.   
  7. {  
  8.   
  9. // Go to default page  
  10.   
  11. App.RootFrame.Navigate(typeof(ShowBooks));  
  12.   
  13. return// and cancel the event.  
  14.   
  15. }  
  16.   
  17. // Otherwise  
  18.   
  19. var newbook = new Book  
  20.   
  21. {  
  22.   
  23. Id = Id.Text,  
  24.   
  25. Title = Title.Text,  
  26.   
  27. Author = Author.Text,  
  28.   
  29. Genre = Genre.Text,  
  30.   
  31. Price = decimal.Parse(Price.Text.ToString()),  
  32.   
  33. PublishDate = DateTime.Parse(PublishDate.Text.ToString()),  
  34.   
  35. Description = Description.Text  
  36.   
  37. };  
  38.   
  39. using (var client = new HttpClient())  
  40.   
  41. {  
  42.   
  43. var content = JsonConvert.SerializeObject(newbook);  
  44.   
  45. // Send a POST  
  46.   
  47. Task task = Task.Run(async () =>  
  48.   
  49. {  
  50.   
  51. var data = new HttpFormUrlEncodedContent(  
  52.   
  53. new Dictionary<string, string>  
  54.   
  55. {  
  56.   
  57. ["value"] = content  
  58.   
  59. }  
  60.   
  61. );  
  62.   
  63. await client.PostAsync(App.BaseUri, data);  
  64.   
  65. });  
  66.   
  67. task.Wait();  
  68.   
  69. }  
  70.   
  71. App.RootFrame.Navigate(typeof(ShowBooks));  
  72.   
  73. }  

 


Image 8.

Update a record

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid.RowDefinitions>

<RowDefinition Height="80"/>

<RowDefinition Height="220"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

<StackPanel Grid.Row="0">

<TextBlock FontSize="25" FontWeight="Bold" HorizontalAlignment="Center">Create a new Book</TextBlock>

<TextBlock FontStyle="Italic" HorizontalAlignment="Center">Update the following form and submit. It would update the current data source in Web API.</TextBlock>

</StackPanel>

<StackPanel Grid.Row="1" Margin="0,0,0,10" Grid.RowSpan="2">

<Grid Height="310" Margin="20, 10, 10, 0">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="100"/>

<ColumnDefinition />

</Grid.ColumnDefinitions>

<StackPanel Grid.Column="0" Margin="0,0,0,60" d:LayoutOverrides="TopPosition, BottomPosition">

<TextBlock Margin="0, 10, 0, 8">

<Run Text="Id"/>

</TextBlock>

<TextBlock Margin="0, 6, 0, 8">

<Run Text="Title"/>

</TextBlock>

<TextBlock Margin="0, 7, 0, 6">

<Run Text="Author"/>

</TextBlock>

<TextBlock Margin="0, 10, 0, 0">

<Run Text="Genre"/>

</TextBlock>

<TextBlock Margin="0, 10, 0, 0">

<Run Text="Price"/>

</TextBlock>

<TextBlock Margin="0, 20, 0, 0">

<Run Text="Publish Date"/>

</TextBlock>

<TextBlock Margin="0, 20, 0, 0">

<Run Text="Description"/>

</TextBlock>

</StackPanel>

<StackPanel Grid.Column="1" Margin="0,0,0,60" d:LayoutOverrides="TopPosition, BottomPosition">

<TextBox x:Name="Id" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Title" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Author" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Genre" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Price" Margin="0, 2, 0, 2"/>

<TextBox x:Name="PublishDate" Margin="0, 2, 0, 2"/>

<TextBox x:Name="Description" Margin="0, 2, 0, 2"/>

</StackPanel>

<Button x:Name="actionButton" Grid.Column="1" Margin="0,0,0,4" Click="Button_Click" VerticalAlignment="Bottom" Content="Update"/>

</Grid>

<Button Margin="20, 0, 0, 0" Click="Button_Click">Cancel</Button>

</StackPanel>

</Grid>

  1. protected override void OnNavigatedTo(NavigationEventArgs e)  
  2.   
  3. {  
  4.   
  5. if (e.Parameter as bool? == false)  
  6.   
  7. {  
  8.   
  9. var book = App.Books;  
  10.   
  11. Id.Text = book.Id.ToString();  
  12.   
  13. Title.Text = book.Title;  
  14.   
  15. Author.Text = book.Author;  
  16.   
  17. Genre.Text = book.Genre;  
  18.   
  19. Price.Text = book.Price.ToString();  
  20.   
  21. PublishDate.Text = book.PublishDate.ToString();  
  22.   
  23. Description.Text = book.Description;  
  24.   
  25. }  
  26.   
  27. }  
  28.   
  29. private void Button_Click(object sender, RoutedEventArgs e)  
  30.   
  31. {  
  32.   
  33. if ((sender as Button).Content.ToString() == "Cancel")  
  34.   
  35. {  
  36.   
  37. // Go to default page  
  38.   
  39. App.RootFrame.Navigate(typeof(ShowBooks));  
  40.   
  41. return// and cancel the event.  
  42.   
  43. }  
  44.   
  45. // Otherwise  
  46.   
  47. var existingbook = new Book  
  48.   
  49. {  
  50.   
  51. Id = Id.Text,  
  52.   
  53. Title = Title.Text,  
  54.   
  55. Author = Author.Text,  
  56.   
  57. Genre = Genre.Text,  
  58.   
  59. Price = decimal.Parse(Price.Text.ToString()),  
  60.   
  61. PublishDate = DateTime.Parse(PublishDate.Text.ToString()),  
  62.   
  63. Description = Description.Text  
  64.   
  65. };  
  66.   
  67. using (var client = new HttpClient())  
  68.   
  69. {  
  70.   
  71. var content = JsonConvert.SerializeObject(existingbook);  
  72.   
  73. // Send a PUT  
  74.   
  75. Task task = Task.Run(async () =>  
  76.   
  77. {  
  78.   
  79. var data = new HttpFormUrlEncodedContent(  
  80.   
  81. new Dictionary<string, string>  
  82.   
  83. {  
  84.   
  85. ["value"] = content,  
  86.   
  87. ["id"] = App.Books.Id.ToString()  
  88.   
  89. }  
  90.   
  91. );  
  92.   
  93. await client.PutAsync(App.BaseUri, data);  
  94.   
  95. });  
  96.   
  97. task.Wait();  
  98.   
  99. }  
  100.   
  101. App.RootFrame.Navigate(typeof(ShowBooks));  
  102.   
  103. }  

 

Image 9

Up Next
    Ebook Download
    View all
    Learn
    View all