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.
-
-
- public static Uri BaseUri = new Uri("http://localhost:40752/api/books");
-
- public static Frame RootFrame { get; set; }
-
- public static Book Books { get; set; }
-
- public App()
-
- {
-
- this.InitializeComponent();
-
- this.Suspending += OnSuspending;
-
- using (var client = new HttpClient())
-
- {
-
- var response = "";
-
- client.MaxResponseContentBufferSize = 266000;
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
- Task task = Task.Run(async () =>
-
- {
-
- response = await client.GetStringAsync(App.BaseUri);
-
- });
-
- task.Wait();
-
- App.Books = JsonConvert.DeserializeObject<List<Book>>(response)[0];
-
- }
-
- }
Now change RootFrame which is initialized as Frame property in OnLaunched application event.
- protected override void OnLaunched(LaunchActivatedEventArgs e)
-
- {
-
- #if DEBUG
-
- if (System.Diagnostics.Debugger.IsAttached)
-
- {
-
- this.DebugSettings.EnableFrameRateCounter = true;
-
- }
-
- #endif
-
- RootFrame = Window.Current.Content as Frame;
-
-
-
-
-
- if (RootFrame == null)
-
- {
-
-
-
- RootFrame = new Frame();
-
- RootFrame.NavigationFailed += OnNavigationFailed;
-
- if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
-
- {
-
-
-
- }
-
-
-
- Window.Current.Content = RootFrame;
-
- }
-
- if (RootFrame.Content == null)
-
- {
-
-
-
-
-
-
-
- RootFrame.Navigate(typeof(MyBooks), e.Arguments);
-
- }
-
-
-
- Window.Current.Activate();
-
- }
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>
- private void Button_Click(object sender, RoutedEventArgs e)
-
- {
-
- switch ((sender as Button).Content.ToString())
-
- {
-
- case "Create":
-
- App.RootFrame.Navigate(typeof(CreateOrUpdate), true);
-
- break;
-
- case "My Books":
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- break;
-
- case "Update Book":
-
- App.RootFrame.Navigate(typeof(CreateOrUpdate), false);
-
- break;
-
- case "Delete":
-
- App.RootFrame.Navigate(typeof(DeleteBook));
-
- break;
-
- default:
-
- break;
-
- }
-
- }
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>
- protected override void OnNavigatedTo(NavigationEventArgs e)
-
- {
-
- using (var client = new HttpClient())
-
- {
-
- var response = "";
-
- Task task = Task.Run(async () =>
-
- {
-
- response = await client.GetStringAsync(App.BaseUri);
-
- });
-
- task.Wait();
-
- listView.ItemsSource = JsonConvert.DeserializeObject<List<Book>>(response);
-
- App.Books = JsonConvert.DeserializeObject<List<Book>>(response)[0];
-
- }
-
- }
-
- private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
-
- {
-
- var item = ((sender as ListView).SelectedItem as Book);
-
- App.Books = item;
-
- Title.Text = item.Title;
-
- Author.Text = item.Author;
-
- Genre.Text = item.Genre;
-
- Price.Text = item.Price.ToString();
-
- PublishDate.Text = item.PublishDate.ToString();
-
- Descrition.Text = item.Description;
-
-
-
- viewList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
-
- viewSingle.Visibility = Windows.UI.Xaml.Visibility.Visible;
-
- }
-
- private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
-
- {
-
- switch ((sender as Button).Content.ToString())
-
- {
-
- case "Go Back":
-
- App.RootFrame.Navigate(typeof(MyBooks));
-
- break;
-
- case "View Books":
-
- viewList.Visibility = Windows.UI.Xaml.Visibility.Visible;
-
- viewSingle.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
-
- break;
-
- default:
-
- break;
-
- }
- }
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>
- protected override void OnNavigatedTo(NavigationEventArgs e)
-
- {
-
- message.Text = string.Format("Are you sure you want to delete {0}?", App.Books.Title);
-
- }
-
- private void Button_Click(object sender, RoutedEventArgs e)
-
- {
-
- switch ((sender as Button).Content.ToString())
-
- {
-
- case "Yes":
-
-
-
- using (var client = new HttpClient())
-
- {
-
- Task task = Task.Run(async () =>
-
- {
-
- await client.DeleteAsync(App.BaseUri + "/" + App.Books.Id.ToString());
-
- });
-
- task.Wait();
-
- }
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- break;
-
- case "Cancel":
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- break;
-
- default:
-
- break;
-
- }
-
- }
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>
- private void Button_Click(object sender, RoutedEventArgs e)
-
- {
-
- if ((sender as Button).Content.ToString() == "Cancel")
-
- {
-
-
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- return;
-
- }
-
-
-
- var newbook = new Book
-
- {
-
- Id = Id.Text,
-
- Title = Title.Text,
-
- Author = Author.Text,
-
- Genre = Genre.Text,
-
- Price = decimal.Parse(Price.Text.ToString()),
-
- PublishDate = DateTime.Parse(PublishDate.Text.ToString()),
-
- Description = Description.Text
-
- };
-
- using (var client = new HttpClient())
-
- {
-
- var content = JsonConvert.SerializeObject(newbook);
-
-
-
- Task task = Task.Run(async () =>
-
- {
-
- var data = new HttpFormUrlEncodedContent(
-
- new Dictionary<string, string>
-
- {
-
- ["value"] = content
-
- }
-
- );
-
- await client.PostAsync(App.BaseUri, data);
-
- });
-
- task.Wait();
-
- }
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- }
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>
- protected override void OnNavigatedTo(NavigationEventArgs e)
-
- {
-
- if (e.Parameter as bool? == false)
-
- {
-
- var book = App.Books;
-
- Id.Text = book.Id.ToString();
-
- Title.Text = book.Title;
-
- Author.Text = book.Author;
-
- Genre.Text = book.Genre;
-
- Price.Text = book.Price.ToString();
-
- PublishDate.Text = book.PublishDate.ToString();
-
- Description.Text = book.Description;
-
- }
-
- }
-
- private void Button_Click(object sender, RoutedEventArgs e)
-
- {
-
- if ((sender as Button).Content.ToString() == "Cancel")
-
- {
-
-
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- return;
-
- }
-
-
-
- var existingbook = new Book
-
- {
-
- Id = Id.Text,
-
- Title = Title.Text,
-
- Author = Author.Text,
-
- Genre = Genre.Text,
-
- Price = decimal.Parse(Price.Text.ToString()),
-
- PublishDate = DateTime.Parse(PublishDate.Text.ToString()),
-
- Description = Description.Text
-
- };
-
- using (var client = new HttpClient())
-
- {
-
- var content = JsonConvert.SerializeObject(existingbook);
-
-
-
- Task task = Task.Run(async () =>
-
- {
-
- var data = new HttpFormUrlEncodedContent(
-
- new Dictionary<string, string>
-
- {
-
- ["value"] = content,
-
- ["id"] = App.Books.Id.ToString()
-
- }
-
- );
-
- await client.PutAsync(App.BaseUri, data);
-
- });
-
- task.Wait();
-
- }
-
- App.RootFrame.Navigate(typeof(ShowBooks));
-
- }
Image 9