Category Archives: Uncategorized

My C++ articles for MSDN Magazine

How does C++ fit in the “all in the cloud” meme we hear non-stop these days? Are C++ developers staring at a scenario where we need to use other languages just to connect to the “cloud” and consume web services? If you are increasingly staring at this scenario and wondering what options exist out there, then I have some great news for you.

The C++ team is investing in a modern C++ based library for connecting C++ to cloud services. This project, called the C++REST SDK (code-named Casablanca) allows a C++ developer write modern C++ code (C++11) and connect their apps to any REST-based cloud service. More details on C++REST SDK are here and you can get the bits here.

If you are interested in learning how to connect C++ applications to the cloud, I have written an article for MSDN Magazine. In the article, published in the August edition of the magazine, I discuss how to upload a file to Dropbox using C++REST SDK and the Dropbox REST-based endpoint. The sample is a Windows desktop application using MFC and illustrates how one can integrate C++REST SDK with little effort in existing codebases that need to communicate to cloud services.

If this excites you, I must say that is not all. The September edition, due shortly, will show how to integrate C++REST SDK in Windows Store applications.

I am currently exploring options to build a Linux based application and will write an article once I am done with it.

So, what is the big deal in all of this? Well, all of the client code that talks to Dropbox in my samples is written using standard C++ and remains exactly as-is across my samples, barring minor changes. Now, is that not exciting enough to dip your toes in C++REST SDK?

Stay tuned for more!

-Sridhar

Continuing on Modern C++ and building connected apps

Hi,

In my book, “Modern C++ and Windows Store apps”, I attempted to provide an overview of how a developer could consume various native technologies and build differentiated application experiences in Windows Store apps. As the work on the book was completed, I began contemplating how to take the story further. One area that I could not cover in depth was building applications that either connect to web services using standard C++ code. In this regard, I have put together a small survey to solicit interest and feedback on focusing more about the C++REST SDK from Microsoft. I would appreciate if folks can take sometime and answer a few questions for me. It would be super helpful for me to spend my limited amount of time on maximizing the interest of the audience here.

Disclaimer: I am not promising anything here, just gauging developer interest here 🙂

http://www.rationalsurvey.com/s/9293

-Sridhar

It’s time to move away from Turbo C++

You might be surprised to hear that a good number of colleges (at least in India) still rely on using the ages old Turbo C++ package to teach aspiring students C++. With a new language standard and great library support, it is now time to bid goodbye to Turbo C++. I answered a few questions about Turbo C++ and Modern C++ in this month’s edition of PCQuest (Thank you Hiren Mehta and other good folks from PCQuest). Attaching the Q&A below.

201306-PC Quest-Sridhar

 

While Visual Studio 2012 is a great tool for developing Windows apps using C++, there are also similar utilities for other platforms that support the C++11 standard. These include, but are not limited to, GCC, Clang etc. We owe it to aspiring students and should teach and train them on the latest language standard. In case you have not checked out Modern C++, I urge you all to check out the new language and you will be pleasantly surprised at the changes!!

 

-Sridhar

 

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++.

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:

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 Smile

Before you begin

  1. 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/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MobileServicesApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    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<Platform::String^>(GetValue(TitleProperty_));
			}
			void set(Platform::String^ s)
			{
				SetValue(TitleProperty_, s);
			}
		}

		property Platform::String^ Description
		{
			Platform::String^ get()
			{
				return static_cast<Platform::String^>(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<ToDoItems^>^ 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<IJsonValue^> 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<CheckBox^>(sender);
	ToDoItems^ item = dynamic_cast<ToDoItems^>(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<IJsonValue^> 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<IJsonValue^> 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