Sending Image Data with parameter using HttpClient Post

I recently needed to send image data to a server for processing and thought I’d share how to do that using System.Net.Http.HttpClient in a UWP (Universal Windows) app. First, let’s start with the API’s requirements, it states:

Parameter: image  The image parameter should be the binary file data for the image you would like analyzed (PNG, GIF, JPG only). Files cannot be larger than 500k.

So that means I have to send image data as binary data with the parameter image. I can use System.Net.Http.ByteArrayContent for the image data. To get the image data from the file as a byte[] the approach I use is the following (there are other ways to do this):


var myImageFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

byte[] fileBytes;
using (var fileStream = await myImageFile.OpenStreamForReadAsync())
{
var binaryReader = new BinaryReader(fileStream);
fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
}

 

Now that I have a byte[], I can create an instance of System.Net.Http.ByteArrayContent to hold the image’s binary data:


var imageBinaryContent= new ByteArrayContent(fileBytes);

 

Normally when sending content, you’d just pass the content as itself to the PostAsync() method directly. However, because I need to send the content with the parameter name image, I’ll need to use System.Net.Http.MultiPartFormDataContent. It allows you to set content with a parameter name. Here’s how I did it:


var multipartContent = new MultipartFormDataContent();
multipartContent.Add(imageBinaryContent, "image");

 

Now that we have the content ready to go, all that’s left to do is to pass it to PostAsync() when the call is made. Here’s the entire snippet:


//get image file
var myImageFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

//convert filestream to byte array
byte[] fileBytes;
using (var fileStream = await myImageFile.OpenStreamForReadAsync())
{
var binaryReader = new BinaryReader(fileStream);
fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
}

//instantiate the client
using(var client = new HttpClient())
{

//api endpoint
var apiUri = new Uri("http://someawesomeapi.com/api/1.0/");

//load the image byte[] into a System.Net.Http.ByteArrayContent
var imageBinaryContent = new ByteArrayContent(fileBytes);

//create a System.Net.Http.MultiPartFormDataContent
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(imageBinaryContent, "image");

//make the POST request using the URI enpoint and the MultiPartFormDataContent
var result = await client.PostAsync(apiUri, multipartContent);
}

 

I hope this makes things easier for you,

Happy coding!

 

As suggested by my buddy Scott Lovegrove, you could also move this into an HttpClient Extension Method. How much functionality you put in it is up to you, but I went with most of it. To use it, simply, pass the StorageFile, API url and the parameter name:


var result = await client.PostImageDataAsync(myImageFile, "http://myapi.com/", "image");

 

HttpClient Extension Method:

 

Advertisements

Reward your users for feedback and bug reports

One of the new features of DevCenter is the ability to generate Promotional Codes for your app. With this new ability, I’ve started rewarding my users for taking the time to make the app better.

Let’s be specific so that you know exactly what ‘m talking about. I have a relatively popular app in the store and get all sorts of feedback, crazy nonsense and helpful alike. For those users whom send in a helpful bug report or would get the following email from me:

Hi [Name],

Thank you very much for taking the time to send in this [error report/feedback]. I care deeply about your experience with [app name] and work hard to ensure there are no [bugs/missing features]. I will [fix this bug\add feature] and include it in the next app update.

To show my appreciation for you sending this to me, please accept my gift of “Ultimate App Unlock” code below. It will unlock all the features in the app after you redeem it (instructions included).

If you have any future suggestions, feature requests or bug reports, please let me know.

Thank you for your support,

Lance

Developer, [app name]

Here’s how to get your Promotional Codes from DevCenter:

  1. Go to your app’s App Overview page from the DevCenter Dashboard
  2. Expand the Monetization node (on the left)
  3. Select Promotional Codes
  4. Click Order Codes

You’ll be presented with the following screen:

2015-10-14_1258

Fill out the form by choosing an IAP, choose the number of codes you want made (up to 250) and click the Order Codes button.

DevCenter will generate the codes and you’ll see a new item on the Promotional Codes page with a “Download” link (you get a .tsv file that can be opened in Excel).

Hopefully, this user experience tip will help you as much as it has helped me,

Lance

Telerik Universal on Raspberry Pi2

Most people think of IoT (Internet of Things) as a collection of tiny brains, without user interfaces, collecting data. Some think it’s a remote controlled animal shelter cat toy or a Grant Imahara style robot to do battle. The truth is that IoT is a very broad term, it covers many types of devices, including remote cat toys!

Here’s a Vine of what Windows IoT means to me… Telerik UI on IoT! This post is a overview tutorial, find the full source code on GitHub. (#bananaForScale)

Windows 10 on IoT

The introduction of Windows 10 IoT brings IoT to a whole new level. You get access to your familiar hardware benefits (GPIOI²C, etc.), but you can now do it with XAML and C#! You can run Windows IoT headless or with a UI (ultimately, this depends on the device you chose to install it on).

I choose the Raspberry PI2 because it has an HDMI video out for display. In my photo and Vine, you’ll see a strange 7″ display, it’s just an HDMI monitor, hardware hacker-style.

Telerik Super Polish

Now that I have access to a UI, one of the very first things I did was attempt to run Telerik UI for Windows Universal on it 🙂 To my delight, it just works. I can actually write an app once and it just works on PC, Tablet, Xbox One, Hololens and IoT. The promise Microsoft gave us WPDEVs two years ago is finally taking shape.

Enough talk, let’s get coding

I’ve posted my source for this project and it’s prerequisites on Github. Please see the README.md so you know what you’ll need to get started.

Step One – File > New

Open Visual Studio 2015 and go to File > New > Project. Drill down to Universal, select Blank App, give it a name and click OK.

1

Step Two – Add Project References 

Normally you may be used to adding actually DLLs to a project. This approach is slightly different. we’re using Extension SDKs. Right click on your project’s references, select Add Reference, drill down to Extensions under Universal Windows (#1) and check off the two items you see in #2.

2

[UPDATE – Telerik for UWP is available as of Q1 2016, get it here. and reference Telerik UI for Universal Windows Platform in the image above]

The first reference, Telerik UI for Windows 8.1, is the Extension SDK name for the Telerik UI for Windows Universal controls. Don’t worry about the asterisk (*), it just means that it wasn’t compiled specifically for UWP yet, but it still works as expected.

The second item, Windows IoT Extensions for the UWP, is what allows your app to deploy to Windows IoT and provides the base classes for things like GPIO.

Your references should now look like this:

3

Step Three – Dev Time

First, let’s switch your designer to show a 10″ IoT device. Its usually a 5″ mobile phone at startup because that’s the first item in the list. Note: Take a step back for a second and see all those device types, your Telerik app will run on all of them!

4

Now let’s add a Telerik Chart to the UI. In my demo app on GitHub, I have some sample Car data that has the following properties: Make, Model Year and Price (model code is here). That sample data is loaded into a collection in the MainViewModel.

Now that I have a collection of cars, I want to show a chart. Let’s use a BarChart that groups by Make and shows the Price (find the UI code here).

  • Begin by adding this to the top of the XAML page: xmlns:chart=”using:Telerik.UI.Xaml.Controls.Chart”, this is so you can instantiate any control in the Chart namespace.
  • Next, declare RadCartesianChart and set the axes accordingly, CategoryAxis for the horizontal and LinearAxis for the vertical (#1).
  • Now, we add a BarSeries and set the ItemsSource via databinding to the Cars collection (#2).
  • Lastly, set the property name Make for the CategoryBinding and Price for the ValueBinding (#3).

6

If you do a Build at this point, and you’ve added sample data to the view model like I did, you’ll see data in the UI designer (very cool that methods written to work at run-time, work at design-time). Like this:

5

Step Four – Deploy to Device

I added a couple more chart examples and a Slider control to change the Price values dynamically, but you don’t need to take it that far to see your progress. Just deploy onto your Windows IoT device at this point to see that it works!

Some tips on Windows 10 IoT

I highly recommend that you put aside a about two hours to prepare your board for the first time. You will use a tool that comes with the Windows 10 IoT build for your device to deploy, it creates the partition and loads the ffu. Its pretty straightforward and much easier than it was before RTM.

Deploying and debugging is pretty easy, the IoT device is treated as any other remote machine. Steps to take are:

  1. Right click on the project and select Properties
  2. In the left column, select Debug
  3. In the Target DropDownList, select Remote Machine
  4. Then click the “Find” button and enter the IP address of the Raspberry Pi 2 (you’ll find this displayed on the Pi’s home screen)
  5. Set the Authentication Mode to None
  6. Save and close the Properties page.

Now when you start debugging, it will look for your Pi 2 on the network, deploy and run the app package. For more Remote Debugging details see this documentation (note that the Remote Debugger tools are already built into Windows 10 Core IoT).

Well, that’s it for now. I will be doing another IoT and Telerik post soon. I’ll do another post on how to use GPIO ports, reading sensor data and showing it in a gorgeous UI

Happy coding,

Lance

Windows 10 IoT

DevCenter Promo Codes Not Working?

One of the great things about the new DevCenter is the ability to generate Promotional codes for your in-app-purchase products, so I generated 100 codes last night for the launch of Windows 10.

I gave out many codes today but I started getting “the promo code didn’t work” emails. After a quick investigation I found that the LicenseInformation for the user wasn’t refreshed automatically or even after the user restarted their phone. I suspect that this is just temporary, but I found a workaround…

The trick is to have the user go through the process to purchase the IAP product. The user’s phone will do a license verify check with the Store server and show this screen:

Already Owned

 

Normally, if they did not own the product there would be a payment method and a “buy” button. However, since they redeemed your code, the button will be labeled “install” as seen in this screenshot:

2015-07-29_1516

Just tell your user to click “Install” and go on experiencing your awesome app!

If you have any questions, feel free to leave a comment below or ping me on twitter

Lance

 

Error : DEP3321 – Can’t deploy to Windows 10 Mobile

With Windows 10 being rolled out as I write this article, there will be updated sample Windows Platform apps available soon (today). It’s also time to update your projects.

However, you may find yourself not able to deploy to Windows 10 Mobile after updating your projects or older samples to Windows 10 (build 10240). This post will show you how to resolve this problem.

The Problem

You’ll see an error something like this when deploying to a physical Windows 10 Mobile device:

Error : DEP3321 : To deploy this application, your deployment target should be running Windows Universal Runtime version 10.0.10240.0 or higher. You currently are running version 10.0.10166.0. Please update your OS, or change your deployment target to a device with the appropriate version.

The error is pretty clear but how do we fix it? The resolution is with the MinTargetVersion setting.

The Fix

We need to drop the lowest version your app targets to the version that your device has running, we can do this in one of two ways; through the project properties UI editor or manually edit the XML of the csproj file. I will show you how to do it manually because in some cases, the UI’s MinTarget dropdown list won’t show the lowest SDK if you do not have it installed. Below are the steps to fix it.

NOTE: Skip to step 3 if your project is already unloaded (it will show (unavailable) next to the name)

1) Right click on your project in Visual Studio

2) Select “Unload Project“, it will now appears as ProjectName (unavailable)

3) Right click on the unloaded project and select “Edit projectName.csproj

4) Locate the <TargetPlatformVersion> and <TargetPlatformMinVersion> items in the first <PropertyGroup>.

Here’s the “Before” screenshot:

2015-07-28_1734

5) Change the TargetPlatformMinVersion to the version that the error stated you are running. In this case, it’s 10166. Here’s the “After” screenshot:

After

6) Now Save and Close the file

7) Right click on the project again and select “Reload Project

8) Rebuild the project and deploy to device. Now you should be up and running!

Summary

I expect this to happen with increasing frequency as we move forward with Windows 10 SDK releases. The new paradigm is that we’ll have a set of installed windows 10 Tools, but multiple SDK versions. We need to be aware of the min version and targeted version of our apps.

If you have any questions, feel free to leave a comment below.

One XAML for UWP, Windows 8.1 and Windows Phone 8.1

I was recently involved in a conversation on how to have the easiest way to maintain a XAML view across a UWP (Universal Windows Project) a Windows 8.1 and Windows Phone 8.1 projects. There are a few options and the most straight forward way to do it with a UserControl residing in a Portable Class Library. However…

What if you wanted to have tailored code for each without littering your code with #ifdef but still share a XAML view?  The XAML View might be what you’re looking for. This is a tutorial on how to do just that. An example project is available for download at the end of the article. Let’s get started:

Step 1:

Create a new 8.1 Universal app

tpx1

Step 2:

Move the Shared, Windows and Windows Phone projects out of the virtual folder and delete the folder (you can cut/paste or just click and drag them). The solution should look like this now

tpx2

(Note: If you’re doing this to a solution that has many other projects, you might want to skip this step and add the UWP project to the virtual folder instead)

Step 3:

Add a new UWP project to the solution and name it the same as the 8.1 app, but with the Universal suffix.

tpx3

(Your solution should look like this now)

tpx4

Step 4:

Add a “Views” folder to each of the projects

tpx5

Step 5:

Within the Universal project, right click and Add > New Item > XAML View

tpx6

Step 6:

Move the new XAML View to the Shared project’s Views folder and change the namespaces in the view to match

tpx7

Step 7:

Delete App.xaml from the Universal project and add a reference to the solution’s Shared project (Note: this is in the new Shared projects references section)

tpx8

Step 8:

Here’s where the magic happens. We’ll be adding a code behind for this view in each of the projects! I’ll break this down into sub-steps:

  1. Add a new class to the Windows 8.1 project’s Views folder (Add > New Item), name it as if it were the code-behind for the view. In this case it would be SharedPage.xaml.cs
  2. Change the namespace of the class to Views
  3. Add the public, sealed and partial modifiers to the class
  4. You’ll next need to inherit from the Page class
  5. Add a page constructor
  6. Now you can copy and paste this new class into each of the platform projects (remember, we do not need it in the Shared project)

This is what it should look like

tpx9

Step 9:

You’ll need to quickly pop into the Build Configuration Manager and check off Build and Deploy for the Universal app (you can find Configuration Manager in the target dropdown or in the Build menu)

tpx10

Step 10:

Lastly, for the purposes of this demo, go to App.xaml.cs and change the initial launch target (MainPage) to be the new shared page (SharedPage). I could have put a button on MainPage for each app, but let’s keep this tutorial as short as possible.

tpx11

Final result!

This is the same XAML View compiled with different code-behind files 🙂

tpx12

(NOTE: I put a TextBlock on the SharedPage and update the text in each constructor to show which platform launched it. Here are the WP8.1 emulator, Windows 10 PC and Windows 10 Mobile Emulator running their apps all showing the same XAML view).

Source Code

Download the Sample App Source Code From Here

Bonus:

The Telerik Universal Control can be used in the shared page as long as each of the projects have a reference to the Telerik UYI for Windows Universal DLLs. Send me a tweet and show me what you’ve done, I’ll RT your awesomeness!

Custom Pivot Header with Animation

I recently wanted to make a header with tabs for my app’s pages that have a Pivot. Something like Office Mobile, but without the drop-down menus. Here’s the result I got in my upcoming app. I decided to post a tutorial and provide a sample app.

CustomPivotHeader

 

Notice the fast fade-in of the background color of the tab, this is important and is where you’ll be able to add your own flavor to the style after you’ve completed this tutorial. Ok, let’s get started!

Step One: Create the base elements

The two main components are a Pivot control and a ListView control. The Pivot has been stripped of it’s title template and pivot header templates. To get started, let’s do a File > New Pivot App (WinRT, not Silverlight) so that we’ll have some sample data and a pre-existing Pivot.

StepOne1

After the project template finishes, open PivotPage.XAML and add RequestedTheme=”Light” to the page’s properties. Next, find the root grid of the page. Add a couple RowDefinitions, with the first row’s height set to auto. Add a Grid containing a ListView to Row 0 and put the Pivot into Row 1.

StepOne2

Now, let’s clean up the pivot. Delete the Pivot’s Title and both the PivotItem’s Header properties. You should be left with only the pivot item’s contents, this is what your page should look like at this point.

StepOne3

Step Two: Create a Control for the Tabs

My demo uses text, however there are other approaches that can use an icon or other element in the tab. Since not all XAML elements have a “Foreground” property that can automatically inherit from the parent ListView’s foreground, we’ll use a  container control to hold the TextBlock. Make this by right clicking on your project and select Add > New Item. Then find Templated Control and give it the name HeaderTab.cs.

StepTwo1

A template control has a backing style where the UI is defined while the control’s logic is in the file named after it. Visual Studio will add a folder named Themes and a ResourceDictionary Generic.xaml.

StepTwo2

First, Open HeaderTab.cs and change the base class from Control to ContentControl. This will allow you to use the control as a ContentControl, which is what the ListViewItem’s template uses.

StepTwo4

Next, open Generic.xaml, ignore the errors for now, they will go away when you do a Build at the end of this step. First, replace the Border control in the style with a TextBlock. Now, use TemplateBindings for the Text and Margin properties (see screenshot). This is how we pass the properties values of the ListView ItemContainerStyle to our custom control when the property types to match. The Margin property is a perfect example, we use the padding of the container style for the margin of the TextBlock, this will make more sense towards the end of the tutorial. Okay, now it’s time to do a Build (F6) so that your style’s TargetType will resolve.

This is what your Style should look like:

StepTwo3

Step Three: Create a horizontal ItemsPanel

In order to tell the ListView to render the items horizontally, we need an ItemsPanel, however since we want the content of the tab to be in the center but also stretch to fill the available space, we can’t use a simple StackPanel. So, let’s make our own. Right click on your project and select Add > New > Class and name it HorizontalStretchPanel.

StepThree1

Explaining the process of calculating the available space and arranging the items is outside the scope of this article, but in a nutshell, we take the full width and divide it by the number of items then arrange to get the most space for each item. Here’s the code to copy/paste:


public class HorizontalStretchPanel : Panel
{
protected override Size ArrangeOverride(Size finalSize)
{
var rect = new Rect(0, 0, finalSize.Width, finalSize.Height);
var width = finalSize.Width / Children.Count;

foreach(var tab in Children)
{
rect.Width = width;
rect.Height = tab.DesiredSize.Height > finalSize.Height ? tab.DesiredSize.Height : finalSize.Height;
tab.Arrange(rect);
rect.X = width + rect.X;
}

return finalSize;
}

protected override Size MeasureOverride(Size availableSize)
{
if(Children.Count == 0)
return base.MeasureOverride(availableSize);

var finalSize = new Size { Width = availableSize.Width };
availableSize.Width = availableSize.Width / Children.Count;

foreach(var tab in Children)
{
tab.Measure(availableSize);
var desiredSize = tab.DesiredSize;
finalSize.Height = desiredSize.Height > finalSize.Height ? desiredSize.Height : finalSize.Height;
}

if(double.IsPositiveInfinity(finalSize.Height) || double.IsPositiveInfinity(finalSize.Width))
return Size.Empty;

return finalSize;
}
}

 

Step Four: Create a ListView Configuration and ItemContainerStyle

Now it’s time to go back to the ListView we added to the top of PivotPage.xaml . Before working on the ListView, Give the parent Grid a height of 50 and a good background that will contrast with white, I went with Blue. Now, onto the ListView. Let’s set the ListView.ItemsPanel to use our new HorizontalStretchPanel. Next, add some ListViewItems containing your new HeaderTab control. You’ll want one ListViewItem for each PivotItem you have. While you’re there, set the FontSize of your HeaderTab to 20.

Now, bind the SelectedIndex of the ListView to the SelectedIndex of the Pivot using an ElementName binding and set VerticalAlignment to bottom.

Here’s what it should look like thus far

StepFour1

Now, it’s time to add some style and animation to the ListViewItemContainer. To begin, extract the ListView’s default ItemContainerStyle, this screenshot shows how:

StepFour2

Give a name, I chose HeaderListViewItemContainerStyle, once you click Ok, the ListView will get a StaticResource reference to the style in the page’s Resources. Scroll up to the top of the page and expand the style. Yeah, it’s pretty long. the part I want you to get to is the Template property. Within here you’ll see some animations, but go past them until you see the ContentControl. This is what shows your HeaderTab control, I like to give my template parts names with strong prefixes, you don’t have to, but it’s easier for identification when it comes to animation.

Now, let’s edit that template to add an extra Grid so we can act on it to get some cool fading animation when the user changes tabs. What we’re going to do is put the new Grid behind the ContentControl so that we don’t block the Text. To make this easier, here is what the XAML looks like after renaming the parts and adding the Grid.

StepFour3

Lastly, I went with White for the Style’s foreground property, this gets inherited by the TextBlock in your HeaderTab control. It will contrast well against the Blue background of the page header Grid.

Step Five: Animating the Container’s Parts

This is something that you’ll want to play with and where Blend can help you get the exact results you’re looking for. What we’re going to do is add some keyframes to the existing States: UnselectedSelected and SelectedFocused. Here’s where the string naming of the template parts comes in handy. First, in the Unselected state we want to style it they way we want it to look when the tab is not in focus. In this state I want my new Grid to have zero height. Here’s what that looks like:

StepFive1

Now let’s go to the Selected and SelectedFocused states (they’re the same in my scenario). In this state I want the new Grid to be the full height of the tab and more importantly to have a white background.

StepFive2

Lastly, the sugar that adds the magic… the transition animation. The cool thing about states is that you don’t have to write long storyboards, just set a Default Transition for a particular state. You can add these right to the VisualStageGroups directly (don’t forget to add some Easing). Here’s what it looks like

StepFive3

 

Almost done! Go through the Pivot and PivotItems and delete all the x:UID properties, these will change your UI at runtime because of localization, best to get them out of the way now. Whew! now it’s time to fire up the emulator and take it for a spin. This is what you should be seeing, if not, download the sample app from here and see what went wrong.

Happy coding!

FinalDemoResult