Sridhar Poduri's Blog, page 4
May 12, 2013
Modern C++ and Windows Store apps giveaway – An update
I wanted to provide a quick update on the winning responses so far to book contest I have announced a few weeks back. I am humbled by the responses I have received so far. The winning responses, from the mails I have received until now are:
“I am excited to apply modern C++ to code snappy and responsive Windows 8 metro apps using asynchronous functions, now wonderfully described in Sridhar’s book on Windows 8 application programming. I’ve been trying to find the best sources of information for Windows 8 application programming to write apps that work on phone/tablet and PC. I plan to write applications that are education games or tools related to biology.”
“Thanks for writing a book on using modern C++ with Windows 8. I am a long time C++ developer, having worked for many years with Symbian and Qt. This book has come at the right time for me to update my skills The fascinating thing about Windows has always been its reach. No question about it. But with Windows 8, I feel that Microsoft is now at the forefront of design as well. I love the way the “modern” apps look and perform on my tablet, and I am amazed by their performance even on this old device. Modern C++ provides me with an easy pathway to the Windows 8 ecosystem. Ever since Microsoft released the source for Project Austin, I have been looking at the possibility of developing an application for Windows 8 with C++. With the release of your book, I hope to learn a few tricks which will make my task much easier.”
“My name is XXXX and I work for a XYZ company and write software that processes large amounts of data and visualizes it using various plot types such as scatter, histogram, density, and contour plots. The software also controls the hardware during run-time data acquisition. Currently the software runs on the desktop using WPF and C#. As the data rates and file sizes increase I am starting to hit the threshold of the C# – .Net technology. I am now seriously considering writing the software in C++ 11 and Windows Store App. Previously I did some prototyping with C++/CLI and WPF, and the performance while better was not enough to justify the move. The boundary between C++ and C# forced some design compromises and to be honest had some performance problems. With WinRT C++/CX and native XAML the story becomes very intriguing. While there are still boundary problems to aware of (avoid ‘chatty’ api’s) I believe the design will be much cleaner and have much better performance. Additionally I have been working with C++ Amp to do a lot of parallel processing. The results have been very encouraging. It seems as though the stars have aligned in terms of performance (C++, and AMP), Fast and Fluid UI (Windows Store App), and my existing knowledge of Xaml and WPF. I believe this combination will give me the opportunity to write some great software that performs well, and looks great and runs on tablet and eventually mobile (reduced function set.) I think that the combination will truly give me full power at my fingertips to extract the most from the hardware available. I am looking for the knowledge of how to best use Modern C++ with the new WinRT framework to quickly come come up to speed. ”
I still have 6 copies to giveaway. If you want a copy, please do let me know.
-Sridhar
April 19, 2013
Modern C++ and Windows Store apps giveaway
BUILD 2013 is 9 weeks away. In anticipation of BUILD 2013, I am listing a giveaway for my book, “Modern C++ and Windows Store apps”. Every week leading to the BUILD 2013 conference, I will give out a copy of my book. Sounds interesting? Want a copy? Getting a copy is easy. All you have to do is put on your thinking caps and send me a mail about “What interests you about Windows 8 and Modern C++ put together to develop Windows Store apps?”
Each week I will select the best quote I receive, and send out a copy of my book to the person who has sent me the quote. I will also share the quote on my blog, twitter and Facebook feed. So, put your thinking caps on and send me mail at win8book at sridharpoduri dot com.
Please do not post your quotes as comments to this blog post as I will not be considering those. J
Rules and Regulations:
Only one entry per person. I cannot verify duplicates but would expect everyone as professionals to be honorable.
I reserve the right to select what I believe is best entry every week.
I will share the best entry every week.
I will not share the details of the person who sent the best entry (email address or any other personally identifiable details).
After I post the selection of the best entry please look out for an email from me asking for your mailing address.
I will bear the cost of shipment of the book to your address. You do not have to pay for shipping or the book cost. J
Feel free to tweet or share this on your social networks!
Bring those interesting thoughts on!!!
Cheers,
Sridhar
March 25, 2013
Purchase Modern C++ and Windows Store apps in India
Hi,
Wanted to provide a quick update on the availability of my book, “Modern C++ and Windows Store apps”, in India.
Get the eBook in Adobe PDF: http://www.infibeam.com/eBooks/modern-c-windows-store-apps-sridhar-poduri-pdf-ebook-download/9780989020800-BEPDF.html
Get the paperback edition: http://www.junglee.com/Modern-C-Windows-Store-Apps/dp/0989020800/ref=sr_1_1?ie=UTF8&qid=1364203192&sr=8-1
Thanks,
Sridhar
March 22, 2013
Where can I purchase “Modern C++ and Windows Store apps” book
There are a few avenues by which you can purchase a copy of my book, “Modern C++ and Windows Store apps”.
Obtaining a paperback edition
You can purchase a copy directly from my Createspace eStore here. Use discount code 5C56GCKN to get 20% off MRP. Please note that all orders placed via this site are fulfilled by Amazon and shipping charges apply based on destination and shipping speed.
If you are in the United States, you can purchase the book directly from Amazon by going here. I do not have any discount codes for purchases made directly at the Amazon site. Amazon also ships to various destinations across the world and shipping charges will apply.
If you are in one of the following countries, you can obtain a paperback copy by visiting the country specific Amazon site(s).
United Kingdom
France
Italy
Spain
Germany
Obtaining an electronic edition
You can obtain a Kindle edition by visiting any Amazon site and searching for “Modern C++ and Windows Store apps”. Look for the Kindle edition and you should be able to purchase one easily.
For folks who prefer an ePub version, you can obtain one from Smashwords. For a limited time, you can use discount code AH86C
to get a discount off MRP.
For folks who prefer a PDF version, you can search for “Modern C++ and Windows Store apps” ebook on google. There are multiple websites offering a PDF edition for sale.
Although most PDF versions are offered as Adobe DRM’d copies, there are no restrictions whatsoever on the title itself. It is a side effect of self-publishing that Adobe Digital Editions is needed to read the PDF version L
The book samples can be downloaded from the “Downloads” page of this blog. Please send feedback/comments to win8book at sridharpoduri dot com
Thanks and happy reading.
Sridhar Poduri
March 19, 2013
[Updated with purchase and discount links] Modern C++ and Windows Store Apps – A book about Modern C++ and native technologies
Over the past few months, I have been writing a book on developing apps using C++ and the various native technologies shipping as part of the Windows 8 wave. Some of these technologies include: C++11, C++ /CX, native XAML, the Windows Runtime, C++AMP, Windows Azure Mobile Services etc. I am happy to announce that the Kindle version of “Modern C++ and Windows Store apps” will be available shortly for purchase via the Amazon website. A paperback edition will also be available soon.
For purchasing the paperback edition of the book, please visit this link. You can use the discount code 5C56GCKN to get 20% discount off MRP.
For folks interested in an electronic edition, you can purchase a Kindle edition on Amazon
A quick update: This is just me self-publishing the book thereby bringing the work to its logical conclusion.
For the benefit of everyone, I am listing some of the topics that await anyone who picks up a copy of this book. For the more adventurous amongst us who would rather prefer to play with code, the book samples can be downloaded from the Downloads section of this blog.
The new native API
What is a Windows 8 App?
Quick walkthrough of a Windows 8 App
Hello Modern C++
Move semantics
Welcome to the Component Extensions
The C++ /CX Type System
Asynchronous Programming in C++ /CX
Building a WinRT component using C++ /CX and ISO-C++
Guidance on the use of C++ /CX
Introduction to XAML
Hello World with XAML and C++ /CX
Basic XAML Syntax
Using Panels to Layout UX
Basic XAML Controls
Windows 8 Signature XAML Controls
Handling Events
Markup Extensions
Data Binding
Binding to a Data Model
Building a XAML custom control
Using Animations in XAML Controls
Introduction to XAML + DirectX
SurfaceImageSource
VirtualSurfaceImageSource
Design considerations when using SiS and VSiS
SwapChainBackgroundPanel
The DrawIt Application – C++, XAML and DirectX
The C++ AMP Library
The ImageEffects application
Playing by the rules of the Windows Runtime
Introduction to the Windows Runtime Library
Hello World XAML App using Windows Runtime Library
Getting Started with Windows Store apps and Windows Azure Mobile Services
Creating a simple Windows Store app with Windows Azure Mobile Services
Supporting Push Notifications using Windows Azure Mobile Services
And more….
I had a lot of fun writing this stuff and learning along the way. I hope there are concepts that you can apply to your work as you build apps for the Windows 8 Store using C++.
Please send feedback on the book contents directly to win8book at sridharpoduri dot com
March 3, 2013
C++ for non-C++ developers
Some of us folks who have been coding using C++ have never left the C++ fold as other languages have come into vogue and gone out of fashion. We did take an occasional peek and try to understand what the hoopla over a new programming language was all about, and made efforts to learn concepts that we were able to successfully apply in our daily routines using the best tool for the job. As C++ programmers, we constantly remind ourselves: one size does not fit all.
These days, there is an increasing number of folks who are either moving back to coding in C++ or are beginning the process of transition into C++. While I will not delve into the reasons or motivations for their change of heart, it is worth noting the number of learning resources that are being created to cater to folks approaching C++ from other programming languages. One such resource is the book titled “C++ Succintly” written by Michael McLaughlin and published by the SyncFusion Technology Resource Portal.
Disclaimer: I reached out to Sync Fusion asking for permission to use their icons for my upcoming book. While granting permission for the same, SyncFusion asked me to review one of their books/products and as a compliment for reviewing their product; they have offered a personal key to one of their products. I must note that their offering is not affecting my review of the book.
Michael does a good job of distilling the large number of C++ features into a palatable set for the C# developers, who are the target audience for his book. He does a commendable job of mapping C++ concepts that do have C# equivalents and ones that folks are familiar with. The book starts off with an introduction to the C++ type system and then moves on to explaining namespace and functions/classes. All of these concepts are explained while contrasting them with equivalent C# constructs thereby helping the C# developer rationalize the C++ constructs.
Once the basics are explained, the focus moves to Constructors and Destructors. Object lifetimes and behavior is obviously very different in C++ when compared to GC-controlled languages and the contrast is explained using C++11 memory management smart pointers: shared_ptr, weak_ptr and unique_ptr. One of the most widely used paradigms in C++, for object destruction, is the Resource Acquisition is Initialization or the RAII pattern. This pattern is widely used in the C++ world to design well behaving programs that do not leak! When put together with object creation, destruction and a pattern to manage lifetimes, it becomes increasingly clear why C++ programmers shy away from having to use a GC. The book does a good job of explaining these concepts to C# developers.
The focus then shifts to explaining pointers: a perennial source of confusion and frustration to a lot of non-C++ developers, references and using ‘const’. All of these concepts are explained in a brief and succinct format. This chapter then leads to a discussion on strings, all the more relevant since there are a multitude of string types supported by C++: from plain char* to std::string types.
A few C++-esque idioms are introduced along the way, including the use of pre-increment operator within a ‘for’ loop, using ‘nullptr’ instead of NULL etc.
The final few chapters focus on templates, C++ lambdas, the Standard Library and finally a chapter devoted to using Microsoft Visual Studio and C++.
All in all, it is a good book for explaining C++ in a succinct format for non-C++ developers, especially for folks using C# and are probably staring at the prospects of having to use C++ in one of their upcoming projects. This book however is not an encyclopedia of C++ nor does it cover everything that is part of the modern C++ programming language. In all fairness to the author, he does make it very clear at the beginning itself, that this book does not cover everything but instead only focuses on aspects of the C++ language that folks from non-C++ world find useful and enhance their knowledge/skills. For the folks who are in the C++ realm already, there is little value in this book, unless you are not up-to-date with C++11. If you are still coding using the older C++98 style and want to get a good digest of C++11 features, definitely read this book. For non-C++ folks, this is a good “go-to” book to get you started with modern C++.
January 25, 2013
Title change for my book
Based on technical review feedback, we (Microsoft Press, the reviewers and the author) have mutually agreed to change the title of my upcoming Microsoft Press book from “Programming Windows 8 Apps using Microsoft Visual C++” to “Modern Microsoft Visual C++ and the Windows Runtime”. The major focus of the book is about “Modern C++” not just C++ /CX (the component extensions) but also about C++11 and how you can take advantage of various features of C++11 to develop Windows Store apps.
In addition, the book also shows how C++11 features such as lambdas, the ‘auto’ keyword and shared_ptr’s can be used in conjunction with C++ /CX to develop Windows Store applications.
DirectX is a proven and well tested graphics API and the book contains full fledged samples that showcase how XAML and DirectX can be mixed and mashed together to produce Windows Store applications.
So, the book TOC has been revised to better align with the focus on Modern C++.
1. Introduction to Windows 8 Apps
2. Modern C++ and C++ /CX
3. Programming XAML using C++ /CX
4. C++ /CX, XAML and DirectX – Better together
5. Advanced GPGPU Programming
6. Under the covers
And a bunch of appendix contents on Unit testing C++ apps, tips and tricks etc.
We still remain on schedule for a launch this April.
Many thanks to all the folks who have been waiting for the launch of this book. I hope you will like the book and the content shared within it.
-Sridhar
P.S: The various links on O’Reilly, Amazon and other sites will be reflecting the new title shortly.
November 7, 2012
Book Review : Getting Started with Windows 8 Apps
I picked up the “Getting Started with Windows 8 Apps” by Ben Dewey recently, as part of the O’Reilly Blogger Review Program and wanted to provide a quick review of the book here.
The book is primarily targeted at existing .NET developers who want to jumpstart their sojourn with building Windows 8 apps. The author walks through creating an application from scratch using C# and Visual Studio 2012 and walks through the paces of explaining how to integrate the app with the various OS integration points: Share, Search, Live Tiles etc.
The application design itself is geared towards using the Model-View-ViewModel (MVVM) pattern and how such a pattern can best be used while writing Windows 8 Apps using XAML and C#. I personally do not like technical books preaching the “one true way” of designing applications as I strongly believe that good, competent developers come up with designs and patterns that are applicable for their scenarios. A good technical book explains the concepts and gives enough flexibility for its readers to come up with innovative ways to incorporating the concepts in their daily work. But maybe it is just me who looks at things this way!
The book also does not explain the finer nuances of this new API, the WinRT. It looks at WinRT purely from the prism of a .NET layer. Maybe this is deliberate as the target audience for the book is existing .NET developers but I feel that explaining the WinRT from a more detailed perspective would benefit folks who are writing apps for this modern platform. After all, we just don’t want folks to move their existing code and feel happy, we also want to them to understand the platform and build truly shining apps that delight their users.
All in all, a good starting point if you are an existing C# developer who wants to jump into the world of WinRT.
Rating:
October 25, 2012
Binding WebView directly to Html Content using C++ /CX
This post is inspired by Tim Heuer’s Html Source extension property that uses the WebView’s NavigateToString method to bind webview directly to Html Content. Tim’s code is written using C#. I wanted a C++ version of the same for one of my sample projects and here it is. Feel free to use it in your projects and let me know when you use it. That would make me happy!
Typical Usage scenarios for this extension:
1. You use the SyndicationClient API from the Windows.Web.Syndication namespace and parse a RSS feed of interest.
2. Your UI is a GridView and each GridViewItem displays one article from the RSS feed parsed above.
3. You want to display formatted HTML content instead of unformatted HTML content as string.
For more information, look at this blog post by Soma.
WebViewExtension.h
#pragma once
#include "pch.h"
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Interop;
using namespace Platform;
namespace Callisto
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class WebViewExtension sealed
{
public:
static String^ GetHtmlSource(WebView^ view)
{
if (nullptr == view)
throw ref new Platform::InvalidArgumentException("view");
return view->GetValue(HtmlSourceProperty)->ToString();
}
static void SetHtmlSource(WebView^ view, Platform::String^ value)
{
if (nullptr == view)
throw ref new Platform::InvalidArgumentException("view");
view->SetValue(HtmlSourceProperty, value);
}
private:
static void OnHtmlSourcePropertyChanged(DependencyObject^ o, DependencyPropertyChangedEventArgs^ e)
{
auto view = dynamic_cast(o);
if (nullptr == o)
{
throw ref new Platform::NotImplementedException("The HtmlSource attached dependency property is only valid for WebView instances.");
}
// Determine new HTML content
auto newString = dynamic_cast(e->NewValue);
auto newHtml = newString->IsEmpty() ? "" : newString;
view->NavigateToString(newHtml);
}
static Windows::UI::Xaml::DependencyProperty^ HtmlSourceProperty;
};
}
WebViewExtension.cpp
//
// Copyright (c) 2012 Sridhar Poduri
// Based on Tim Heuer's C-Sharp version available at
// https://github.com/timheuer/callisto/...
//
// Licensed under the Microsoft Public License (Ms-PL) (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://opensource.org/licenses/Ms-PL....
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Derived from http://blogs.msdn.com/b/delay/archive...
#include "pch.h"
#include "WebViewExtension.h"
using namespace Callisto;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Interop;
using namespace Platform;
Windows::UI::Xaml::DependencyProperty^ Callisto::WebViewExtension::HtmlSourceProperty =
DependencyProperty::RegisterAttached(ref new String(L"HtmlSource"), TypeName(String::typeid), TypeName(WebViewExtension::typeid),
ref new PropertyMetadata(nullptr, ref new PropertyChangedCallback(OnHtmlSourcePropertyChanged)));
Once you have this header and cpp file in your solution, using them from XAML markup is pretty easy, such as the simple example below.
Enjoy!
-Sridhar
October 15, 2012
C++ Windows Store apps and Windows Azure Mobile Services
I had promised earlier that I will blog about using C++ /CX and Windows Azure Mobile Services to develop Windows Store apps. Today is the big day
Before you begin
In order to successfully build Metro-style apps that communicate with Windows Azure Mobile Services, you should obtain the Mobile Services SDK from http://www.windowsazure.com/en-us/develop/mobile/tutorials/create-a-windows-azure-account.
Creating a simple Windows Store app with Windows Azure Mobile Services
Open Microsoft Visual Studio 2012. Select File->New Project->Templates->Visual C++->Windows Store and pick a Blank App (XAML) project template. Save the project with a name, such as, MobileServicesApp.
Add a reference to the Windows Azure Mobile Services by right clicking on the project file and choosing References.
In the References dialog, click on Add New Reference. In the Add Reference dialog, choose Windows Azure Mobile Services Native Client from the Windows->Extensions node.
Replace the xaml markup in the MainPage.xaml with the one shown below. When you replace the markup, make sure to do so only the section in the Grid and not the complete Page markup.
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="50,50,10,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.ColumnSpan="2" Margin="0,0,0,20">
<StackPanel>
<TextBlock Foreground="#0094ff" FontFamily="Segoe UI Light" Margin="0,0,0,6">WINDOWS AZURE MOBILE SERVICES</TextBlock>
<TextBlock Foreground="Gray" FontFamily="Segoe UI Light" FontSize="45" >Windows Azure Mobile Services App</TextBlock>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<StackPanel>
<local:Task Number="1" Title="Create a Todo Item" Description="Enter some text below and click Save to insert a new todo item into your database" />
<StackPanel Orientation="Horizontal" Margin="72,0,0,0">
<TextBox Name="TextInput" Margin="5" MinWidth="300"></TextBox>
<Button Name="ButtonSave" Click="ButtonSave_Click">Save</Button>
</StackPanel>
</StackPanel>
</Grid>
<Grid Grid.Row="1" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel>
<local:Task Number="2" Title="Refresh List" Description="Click refresh below to load the unfinished todo items from your database." />
<Button Margin="72,0,0,0" Name="ButtonRefresh" Click="ButtonRefresh_Click">Refresh </Button>
</StackPanel>
<ListView Name="ListItems" Margin="62,10,0,0" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Complete, Mode=TwoWay}" Checked="CheckBox_Checked_1" Content="{Binding Text}" Margin="10,5" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Grid>
</Grid>
Right click on the project file and choose Add->New Item. From the Add New Item dialog, choose User Control. Save it as Task.xaml
Replace the xaml markup in Task.xaml with the one below.
<UserControl
x:Class="MobileServicesApp.Task"
xmlns="http://schemas.microsoft.com/winfx/20..."
xmlns:x="http://schemas.microsoft.com/winfx/20..."
xmlns:local="using:MobileServicesApp"
xmlns:d="http://schemas.microsoft.com/expressi..."
xmlns:mc="http://schemas.openxmlformats.org/mar..."
mc:Ignorable="d">
<Grid VerticalAlignment="Top">
<StackPanel Orientation="Horizontal">
<Border BorderThickness="0,0,1,0" BorderBrush="DarkGray" Margin="0,10" MinWidth="70">
<TextBlock Text="{Binding Number}" FontSize="45" Foreground="DarkGray" Margin="20,0"/>
</Border>
<StackPanel>
<TextBlock Text="{Binding Title}" Margin="10,10,0,0" FontSize="16" FontWeight="Bold"/>
<TextBlock Text="{Binding Description}" Margin="10,0,0,0" />
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
We will use a Number, Title and Description for each of our tasks. All of these, Number, Title and Description are dependency properties and their values will be set through the backing logic in the code-behind.
Replace the contents of the Task.xaml.h with the following code.
//
// Task.xaml.h
// Declaration of the Task class
//
#pragma once
#include "Task.g.h"
namespace MobileServicesApp
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Task sealed
{
public:
Task();
virtual ~Task(){};
public:
property int Number
{
int get()
{
return static_cast<int>(GetValue(NumberProperty_));
}
void set(int number)
{
SetValue(NumberProperty_, number);
}
}
property Platform::String^ Title
{
Platform::String^ get()
{
return static_cast(GetValue(TitleProperty_));
}
void set(Platform::String^ s)
{
SetValue(TitleProperty_, s);
}
}
property Platform::String^ Description
{
Platform::String^ get()
{
return static_cast(GetValue(DescriptionProperty_));
}
void set(Platform::String^ description)
{
SetValue(DescriptionProperty_, description);
}
}
private:
static Windows::UI::Xaml::DependencyProperty^ NumberProperty_;
static Windows::UI::Xaml::DependencyProperty^ TitleProperty_;
static Windows::UI::Xaml::DependencyProperty^ DescriptionProperty_;
};
}
Replace the contents of Tasks.xaml.cpp with the following code.
//
// Task.xaml.cpp
// Implementation of the Task class
//
#include "pch.h"
#include "Task.xaml.h"
using namespace MobileServicesApp;
using namespace Platform;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Interop;
Windows::UI::Xaml::DependencyProperty^ MobileServicesApp::Task::NumberProperty_
= DependencyProperty::Register(ref new String(L"Number"), TypeName(int::typeid), TypeName(Task::typeid), ref new PropertyMetadata(nullptr) );
Windows::UI::Xaml::DependencyProperty^ MobileServicesApp::Task::TitleProperty_
= DependencyProperty::Register(ref new String(L"Title"), TypeName(String::typeid), TypeName(Task::typeid),ref new PropertyMetadata(nullptr) );
Windows::UI::Xaml::DependencyProperty^ MobileServicesApp::Task::DescriptionProperty_
= DependencyProperty::Register(ref new String(L"Description"), TypeName(String::typeid),
TypeName(Task::typeid), ref new PropertyMetadata(nullptr) );
Task::Task()
{
InitializeComponent();
this->DataContext = this;
}
We are now ready to connect our app with the Windows Azure Mobile Services.
Add four methods to the MainPage.xaml.h in the MainPage class as shown below.
virtual void CheckBox_Checked_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
virtual void ButtonRefresh_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
virtual void ButtonSave_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
void RefreshData();
Add a new class named “ToDoItems” as shown below. This can be added in the MainPage.xaml.h class. This class will have the BindableAttribute set. We will use data binding to set values to the right XAML elements from the properties exposed by this class. This class and its properties also correspond to the table we create on the Windows Azure Mobile Services backend.
[BindableAttribute]
public ref class ToDoItems sealed
{
public:
ToDoItems()
{
text_ = L"";
complete_ = false;
}
property int ID
{
int get()
{
return ID_;
}
void set(int value)
{
ID_ = value;
}
}
property Platform::String^ Text
{
Platform::String^ get()
{
return text_;
}
void set(Platform::String^ value)
{
text_ = value;
}
}
property bool Complete
{
bool get()
{
return complete_;
}
void set(bool value)
{
complete_ = value;
}
}
private:
int ID_;
Platform::String^ text_;
bool complete_;
};
Also add a Vector of ToDoItems in the MainPage class.
private:
Vector^ items_;
Connect your app to the Windows Azure Mobile Services. In the App constructor, create an instance of the Mobile Service client.
client_ = ref new MobileServiceClient(ref new Uri(L"Your app URI/"),
ref new String(L"Your Secret Key"));
Inserting data into the table in easy. You create an instance of a “ToDoItem”, create a JSON object from the item and call the InsertAsync method of the corresponding table in the Windows Azure Mobile Service.
void MainPage::ButtonSave_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args)
{
auto item = ref new ToDoItems();
item->Text = TextInput->Text;
item->Complete = false;
//save data to AzureMobile
auto client = App::MobileClient;
auto jsonObject = ref new JsonObject();
jsonObject->Insert(L"text", JsonValue::CreateStringValue(item->Text));
jsonObject->Insert(L"complete", JsonValue::CreateBooleanValue(item->Complete));
auto table = client->GetTable("TodoItem");
task insertTask(table->InsertAsync(jsonObject));
insertTask.then([this, item](IJsonValue^ V)
{
auto results = V->Stringify();
JsonObject^ savedItem = ref new JsonObject();
if (JsonObject::TryParse(results, &savedItem))
{
item->ID = savedItem->GetNamedNumber("id");
items_->Append(item);
ListItems->ItemsSource = items_;
}
});
}
Updating the items follows a similar process as inserting items. You create a JSON object of the “ToDoItem” to be updated and call the UpdateAsync method on the table.
void MainPage::CheckBox_Checked_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args)
{
auto cb = dynamic_cast(sender);
ToDoItems^ item = dynamic_cast(cb->DataContext);
auto client = App::MobileClient;
auto jsonObject = ref new JsonObject();
int ID = item->ID;
bool Status = item->Complete;
jsonObject->Insert(L"id", JsonValue::CreateNumberValue(item->ID));
jsonObject->Insert(L"complete", JsonValue::CreateBooleanValue(item->Complete));
auto table = client->GetTable("TodoItem");
task updateTask(table->UpdateAsync(jsonObject));
updateTask.then([this, item](IJsonValue^ V)
{
int x = items_->Size;
for (int i = 0; i < x; ++i)
{
if (items_->GetAt(i) == item)
{
items_->RemoveAt(i);
}
}
});
}
Querying the table for all records is also simple. You create a simple “SQL” query and call the ReadAsync method on the table. The response is a JSONValue that can be parsed and populated as per your needs. In our case, we update the list of items for our sample.
void MainPage::RefreshData()
{
String^ query = "Select * from TodoItem";
auto client = App::MobileClient;
auto table = client->GetTable("TodoItem");
task readTask(table->ReadAsync(query));
readTask.then([this](IJsonValue^ V)
{
auto list = V->Stringify();
JsonArray^ mapValue = ref new JsonArray();
if(JsonArray::TryParse(list, &mapValue))
{
auto vec = mapValue->GetView();
std::for_each(begin(vec), end(vec), [this](IJsonValue^ M)
{
if (M->GetObject()->GetNamedBoolean("complete") == false)
{
String^ str = M->Stringify();
ToDoItems^ item = ref new ToDoItems();
item->Text = M->GetObject()->GetNamedString("text");
item->ID = M->GetObject()->GetNamedNumber("id");
item->Complete = M->GetObject()->GetNamedBoolean("complete");
items_->Append(item);
}
});
ListItems->ItemsSource = items_;
}
});
}
Now you can go to the Windows Azure Management portal and verify that insertion and updating of records work. You can get the complete project here or from http://code.msdn.microsoft.com
Windows Azure Mobile Services coupled with the JSON APIs in the Windows Runtime (these APIs can be found under the Windows.Data.json namespace) make it very easy to communicate with the Azure Mobile Services. The JSON APIs are light weight APIs and can also be used to communicate with Windows Live Services such as Skydrive etc. Hopefully this project has whetted your interest in these new APIs and will encourage you to explore more of the awesomeness of the Windows Runtime!
Stay tuned for more!
-Sridhar