At home, I have a cool Raspberry Pi 2 and an USB LifeCam VX-6000 webcam that, for now, I don’t use for nothing. So I thought I could probably use both to create a little application that will allow me to spy anyone from it (and view the results from a simple Website).

As it’s now possible to use Windows 10 IoT Core on Raspberry, the best way for me to create that application would be to use a UWP application, developped in C#.

Basically, the code of this app will be simple: I’ll first look for the webcam and configure it:

var videodevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

var camera = videodevices.FirstOrDefault(d => d.EnclosureLocation != null);
if (camera != null)
{
    await InitializeCameraAsync(camera);
    await InitializeAzureStuffAsync();
}

Unfortunately, after trying this code on my device, it does not work. Indeed, I was unable to get a reference to the camera After some research, the reason is simple: for now, the drivers for my Webcam are not supported (check here for the hardware compatibility list: http://ms-iot.github.io/content/en-US/win10/SupportedInterfaces.htm)

Well, I could have forgive my project but why? It’s a cool idea and we have the Universal Windows Platform: my app running on the Raspberry can also be used on any Windows 10 devices!

So I just changed the target (using my laptop instead of the PI) and, well, the code works fine: the camera is found and is correctly initialized:

private async Task InitializeCameraAsync(DeviceInformation camera)
{
    await Task.Factory.StartNew(async () =>
    {
        _mediaCapture = new MediaCapture();

        await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
        {
            PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
            StreamingCaptureMode = StreamingCaptureMode.Video,
            VideoDeviceId = camera.Id
        });

        // Find the highest resolution available
        VideoEncodingProperties maxResolution = null;
        var max = 0;
        var resolutions = _mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);
        foreach (var props in resolutions)
        {
            var properties = props as VideoEncodingProperties;
            var res = properties;

            if (res?.Width * res?.Height > max)
            {
                max = (int)(res.Width * res.Height);

                maxResolution = res;
            }
        }

        await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);

        await Dispatcher.RunIdleAsync(async args =>
        {
            // Display camera preview
            CaptureElement.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();
        });

        _imageEncodingProperties = ImageEncodingProperties.CreateJpeg();
    });
}

The goal of the application is to take a photo from the Webcam and upload it to an Azure blob storage so we have some Azure stuff to initialize too:

private async Task InitializeAzureStuffAsync()
{
    await Task.Factory.StartNew(async () =>
    {
        var storageCredentials = new StorageCredentials(BLOB_ACCOUNT_NAME, BLOB_ACCOUNT_KEY);
        var storageAccount = new CloudStorageAccount(storageCredentials, true);

        var blobClient = storageAccount.CreateCloudBlobClient();
        _imagesContainer = blobClient.GetContainerReference("images");
        if (!await _imagesContainer.ExistsAsync())
        {
            await _imagesContainer.CreateIfNotExistsAsync();
        }

        var serviceProperties = await blobClient.GetServicePropertiesAsync();
        serviceProperties.Cors.CorsRules.Clear();
        serviceProperties.Cors.CorsRules.Add(new CorsRule
        {
            AllowedHeaders = new List<string> { "*" },
            AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Head,
            AllowedOrigins = new List<string> { "*" },
            ExposedHeaders = new List<string> { "*" }
        });

        await blobClient.SetServicePropertiesAsync(serviceProperties);
    });
}

The code itself is pretty simple: we check if the blob container “images” exists and, if not, we create it. Then, we change the properties of the container to allow any origins to access it (otherwise, we’ll have a cross domain origin exception).

Once this part is done, we just need to take the pic from the Webcam. As we want to create a spy system, we need to take more than one pic so we’ll use a timer to take our pics:

private void OnStartWatchingButtonClick(object sender, RoutedEventArgs e)
{
    if (_timer == null)
    {
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, 1);
_timer.Tick += OnTimerTick;
_timer.Start();
    }

    StartWatchingButton.IsEnabled = false;
    StopWatchingButton.IsEnabled = true;
}

private async void OnTimerTick(object sender, object e)
{
    if (_mediaCapture == null)
        return;

    using (var memoryStream = new InMemoryRandomAccessStream())
    {
        try
        {
            await _mediaCapture.CapturePhotoToStreamAsync(_imageEncodingProperties, memoryStream);
            await memoryStream.FlushAsync();

            memoryStream.Seek(0);

            var array = new byte[memoryStream.Size];
            await memoryStream.ReadAsync(array.AsBuffer(), (uint)memoryStream.Size, InputStreamOptions.None);

            if (array.Length <= 0)
                return;

            var blockBlob = _imagesContainer.GetBlockBlobReference("Image.jpg");
            await blockBlob.UploadFromByteArrayAsync(array, 0, array.Length);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Exception: " + ex.Message);
        }
    }
}

Every second, the Tick event of the timer is raised and, using the CapturePhotoToStreamAsync method, we get a pic from the Webcam and we use the method from WindowsAzure.Storage to upload it to the blob storage.

So our application is up and running, pushing a pic to the blob storage every second. So we now need a way to view that pic. Let’s go for a simple AngularJS application that perform a GET request to… the URL of our image in the blog container:

"use strict";

app.controller("indexCtrl", ["$scope", function ($scope) {

    var watchIntervalId;

    $scope.isRunning = false;

    $scope.startWatching = function () {

        $scope.isRunning = true;

        watchIntervalId = setInterval(function () {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    var url = window.URL || window.webkitURL;
                    $scope.ImagePath = url.createObjectURL(this.response);
                    $scope.$apply();
                }
            }
            xhr.open("GET", "http://XXXXX.blob.core.windows.net/images/Image.jpg");
            xhr.responseType = "blob";
            xhr.send();

        }, 1000);
    }

    $scope.stopWatching = function () {

        $scope.isRunning = false;

        clearInterval(watchIntervalId);
    }
}]);

Let’s add some user interface component to get a nice app:

<!DOCTYPE html>
<html ng-app="CameraWatcherApp">
<head>
    <title>Camera Watcher</title>
    <meta charset="utf-8"/>

    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="pragma" content="no-cache">

    <link rel="stylesheet" type="text/css" href="Content/bootstrap.css" />

    <script src="js/vendors/jquery/jquery-2.1.4.min.js"></script>
    <script src="js/vendors/angular/angular.min.js"></script>
    <script src="js/vendors/angular/angular-route.js"></script>

    <script src="js/app.js"></script>
    <script src="js/controllers/indexCtrl.js"></script>
</head>
<body>

<div class="container" ng-controller="indexCtrl">
    <h1>Camera Watcher <small>Your personal spy</small></h1>
    <div class="row">
        <div class="col-md-12">
            <div class="center-block">
                <img ng-hide="!isRunning" src="{{ImagePath}}" class="img-rounded" style="width: 800px; height: 600px; display: block; margin: 0 auto;" alt="Camera Watcher"/>
                <br/>
                <div class="text-center">
                    <div class="btn-group">
                        <button class="btn btn-default btn-lg" ng-click="startWatching()" ng-disabled="isRunning"><span class="glyphicon glyphicon-play" aria-hidden="true"></span> Start Watching</button>
                        <button class="btn btn-default btn-lg" ng-click="stopWatching()" ng-disabled="!isRunning"><span class="glyphicon glyphicon-stop" aria-hidden="true"></span> Stop Watching</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

And you’re done! Now, if you run the application, a pic will be send every second and, to view it, just launch the website:

Here is the direct link to the video: https://www.youtube.com/watch?v=XyMMdov-BGk

As you can see, it’s pretty straightforward to implement your own spy system. Of course, when the Windows 10 IoT version will support more devices, you’ll be able to use this code on the Raspberry. But, for now, you need to find another way to access to your webcam and upload the pic from it. For that, I suggest that you take a look at the great article from Laurent, which explain how to do the same upload to a blob storage from a Node JS app: http://blogs.msdn.com/b/laurelle/archive/2015/11/13/azure-iot-hub-uploading-a-webcam-picture-in-an-azure-blob-with-node-js-on-windows-and-linux.aspx?utm_content=buffercdfc0&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer

 

Happy coding!

For a small side project I’m working on, I wanted to easily send push notifications to my UWP application. So I’ve decided to use the Notifications Hub (which is, in fact, a wrapper around the Microsoft Service Bus) to send the notifications.

Basically, you first need to create an application in the Store so you can access to its notifications settings:

image

With the “Package SID” and “Client Secret” settings copied, you can go to the Azure Portal to create/edit your Notification Hub (under the Service Bus section) and set the properties:

image

Now, associate your UWP application with the Store application, so the manifest file can be correctly updated with the correct values:

image

Your Notification Hub is up and running, you app is correctly associated so now, it’s time to add some code!

First step is to register your application so it can receive the notifications. For that, we need to get a push notification channel for the application and use it to register the app to the Notification Hub (after adding the WindowsAzure.Messaging.Managed Nuget package)

var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

var hub = new NotificationHub(Constants.NOTIFICATION_HUB_PATH, Constants.NOTIFICATION_HUB_LISTEN_ENDPOINT);

await hub.RegisterNativeAsync(channel.Uri);

The notification hub path is, basically, your hub name. For the endpoint, you need to go to the Azure portal to get, from the “Dashboard” tab, the connection information:

image

By default, a notification hub has 2 different endpoints configured, each of them with different permissions:

image

As the application will only received notification, the “Listen” permission is the only one needed. So, it’s the DefaultListenSharedAccessSignature that we need to use as endpoint with the hub path.

The application is now configured, it’s time to see how to send the notifications (in my case, I’m using an Azure WebJob executing a Console app). Add the Nuget package Microsoft.Azure.NotificationHubs and you’re ready to create the NotificationHubClient object used to send the notifications:

var hub = NotificationHubClient.CreateClientFromConnectionString(Constants.NOTIFICATION_HUB_FULL_ENDPOINT, Constants.NOTIFICATION_HUB_PATH);

var windowToastTemplate = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>" +
                            "<toast launch=\"fromNotification\">" +
                                "<visual>" +
                                    "<binding template=\"ToastText01\">" +
                                        "<text id = \"1\">My super notification</text>" +
                                    "</binding>" +
                                "</visual>" +
                            "</toast>";

await hub.SendWindowsNativeNotificationAsync(windowToastTemplate);

Here, you can see that I’m using SendWindowsNativeNotificationASync to send the notification to my PC (running Windows 10) but, as you can see, you can send a lot of different notifications (if you have correctly configured their settings in the Azure portal):

image  image

Also, the XML payload used for the notification is the specific part of the project: feel free to use another template and, even more, to use the new template of Windows 10 if needed : https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Notifications

Now, you just need to schedule your Azure WebJob (thanks to Visual Studio, it’s just a right-clic on your project) and define the schedule parameters: name, frequency, etc.:

image

Now, just wait for your WebJob to run and you should receive a nice notification (toast, tile, etc.) on your device, depending of the notification type you’ve decided to use.

Bonus tip: on your Notification Hub, you can use the “DEBUG” tab to send test notifications to your devices!

image

image

As you can see, using a Notification Hub is really easy and can be implemented in a few minutes in any kind of applications!

 

Happy coding!

Since Windows 8, it’s possible to share uris, files, images, etc. using the Share contract:

var dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += this.ShareStorageItemsTextHandler;

private async void ShareStorageItemsTextHandler(DataTransferManager sender, DataRequestedEventArgs args)
{
    DataRequest request = args.Request;

    request.Data.Properties.Title = "Sample";
    request.Data.Properties.Description = "Description";
}

Thanks to the unification of Windows 8.1 and Windows Phone 8.1, we can now do the same to share items on Windows Phone.

While I was testing that on an Windows Phone 8.1 (WinRT) application, I found that if you want to share an image, you’ll need to share the StorageFile instead. Indeed, the following will not work:

private async void ShareStorageItemsTextHandler(DataTransferManager sender, DataRequestedEventArgs args)
{
    DataRequest request = args.Request;

    request.Data.Properties.Title = "Sample";
    request.Data.Properties.Description = "Description";

    var deferral = request.GetDeferral();

    try
    {
        var fileToShare = await this.GetImageFileAsync("Sample.jpg");

        request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromStream(fileToShare);
        request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(fileToShare));
    }
    finally
    {
        deferral.Complete();
    }
}

Well, in fact, if you try to share, you’ll see that it’s working except that the image is not displayed/used. This is due to the fact that when an application implement the Share contract (in receive mode), it needs to indicate which file format it’s able to manage: uris, bitmap, file, text, etc. The native Windows Phone’s apps does not seems to manage the Bitmap format of the Share contract so you’ll need to used the following version:

private async void ShareStorageItemsTextHandler(DataTransferManager sender, DataRequestedEventArgs args)
{
    DataRequest request = args.Request;

    request.Data.Properties.Title = "Sample";
    request.Data.Properties.Description = "Description";

    var deferral = request.GetDeferral();

    try
    {
        var fileToShare = await this.GetImageFileAsync("Sample.jpg");
        var storageFileToshare = await this.GetStorageFileForImageAsync("Sample.jpg");

        request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromStream(fileToShare);
        request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(fileToShare));

        // On Windows Phone, share StorageFile instead of Bitmaps
        request.Data.SetStorageItems(new List<StorageFile> { storageFileToshare });
    }
    finally
    {
        deferral.Complete();
    }
}

With that code, I’m able to share the image, either as an image or as a file: the OS will choose the available targets according to the format I decided to use.

 

Happy coding!

I’m proud to announce that my second MSDN article has been finally published in the August issue of MSDN Magazine!

Entitled “Build MVVM Apps with Xamarin and MvvmCross”, the article will let you know all you need to start developping MVVM apps with Xamarin and MvvmCross.

I hope you’ll like it!

 

Happy coding!

In my previous article about Xamarin, I’ve explained a way to access user’s contact by using the ManagedQuery API. Even if the code is working fine, you may think that it can be a bit “hard” to understand, when the only goal is to query the contacts.

Today, I’ll talk about Xamarin.Mobile, a library that exposes some APIs to access user’s contacts, user’s position and to allow you to, easily, take a picture in your application. The interesting point here is the fact that the API is available for iOS, Android and Windows Phone.

To use Xamarin.Mobile, you need to download the binaries. Thanks to the Components Store available (something that’s a bit similar to Nuget), you can get them easily:

image image

After you hit the “Add to App” button, the component is downloaded and the reference is added to your project:

image image

Once the reference is added, the first step is to add the following “using”:

using Xamarin.Contacts;

Now, by using the AddressBook class, we are able to access to the user’s contacts and we can use LINQ, which provides a more easier and comfortable syntax:

var addressBook = new AddressBook(this);
if (!await addressBook.RequestPermission())
{
    // We don't have the permission to access user's contacts: check if the READ_CONTACTS has been set
}
else
{
    var companyContacts = addressBook.Where(c => c.Organizations.Any(o => o.Name == "Infinite Square"));
    if (companyContacts.Any())
    {
        foreach (var contact in companyContacts)
        {
            var lastName = contact.LastName;
            var firstName = contact.FirstName;
            var thumbnailBitmap = contact.GetThumbnail();
        }
    }
}

As you can see, the code is really easy to understand and maintainable!

 

If you want to know more about Xamarin.Mobile (or just check how does it work), feel free to go to Github, where you’ll be able to find the sources: https://github.com/xamarin/Xamarin.Mobile

 

Happy (Xamarin) coding!

Ok, I admit the title is a bit long and you may wonder what I’m talking about so let me explain.

On the application I’m working, I use a Listbox to display items and I wanted to start an animation when an item is selected. Of course, I could have simply edit the ListBoxItem style and modify the “Selected” visual state (as explained here) but, in my case, I wanted to be notified when the animation was finished (to redirect the user on another page).

So here is the solution I’ve found. On the SelectionChanged event handler, retrieve the current ListBoxItem:

private async void OnCategoriesSelected(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems != null && e.AddedItems.Count > 0 && e.AddedItems[0] != null)
    {
        // The Listbox is bound to a List<Category> so when I get the AddedItems, I know they are of type Category.
        var selectedCategory = e.AddedItems[0] as Category;
        if (selectedCategory != null)
        {
            var listBoxItem = this.CategoriesListBox.ItemContainerGenerator.ContainerFromItem(selectedCategory) as ListBoxItem;
            if (listBoxItem != null)
            {
            }
        }
    }
}

Now that I have the ListBoxItem object, I simply create a Storyboard and begin it:

listBoxItem.RenderTransform = new CompositeTransform();

var swipeAnimation = new DoubleAnimationUsingKeyFrames();
swipeAnimation.KeyFrames.Add(new EasingDoubleKeyFrame
{
    Value = App.RootFrame.ActualWidth,
    KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 250))
});

Storyboard.SetTarget(swipeAnimation, listBoxItem);
Storyboard.SetTargetProperty(swipeAnimation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));

var sb = new Storyboard();
sb.Children.Add(swipeAnimation);

await sb.BeginAsync();

Of course, feel free to create your custom animation here. Also, the extension method BeginAsync is defined as below:

public static Task BeginAsync(this Storyboard storyboard)
{
    var tcs = new TaskCompletionSource<bool>();

    EventHandler completedEventHandler = null;
    completedEventHandler = (sender, o) =>
    {
        storyboard.Completed -= completedEventHandler;
        tcs.TrySetResult(true);
    };
    storyboard.Completed += completedEventHandler;
    storyboard.Begin();

    return tcs.Task;
}

Now, after the call to the BeginAsync method, I can redirect my user to another page:

await sb.BeginAsync();

this.NavigationService.GoToQuestionsPage(selectedCategory.Id);

Here is a small video of the result:

 

Happy coding!

On Silverlight/Windows Phone, the FluidMoveBehavior can be used to animate the items of a ListBox when user adds or removes an item. But the behavior has no effect when the items are loaded and bound to the Listbox.

Imagine the following C# code corresponding to our ViewModel:

private ObservableCollection<Category> _categories;

public ObservableCollection<Category> Categories
{
    get
    {
        return this._categories;
    }
    set
    {
        this.Set(() => this.Categories, ref this._categories, value);
    }
}

public override async Task OnNavigatedTo(NavigationEventArgs navigationEventArgs, NavigationContext navigationContext)
{
    this.IsBusy = true;

    if (App.Categories == null)
    {
        App.Categories = await ClientServices.ClientServicesLocator.CategoriesService.GetAllCategoriesAsync();
    }

    this.Categories = new ObservableCollection<Category>(App.Categories);

    this.IsBusy = false;
}

And the associated XAML code:

<ListBox x:Name="CategoriesListBox" ItemsSource="{Binding Categories}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       FontSize="40"
                       controls:TiltEffect.IsTiltEnabled="True"
                       x:Name="CategoryNameTextBlock" />
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

If you apply the FluidMoveBehavior to the StackPanel of the ListBox and go to the page, you’ll see that the items are all loaded on the same time, with no effect.

To change this, we can replace the ViewModel code with this one:

public Action RefreshCategories { get; set; }

public override async Task OnNavigatedTo(NavigationEventArgs navigationEventArgs, NavigationContext navigationContext)
{
    this.IsBusy = true;

    if (App.Categories == null)
    {
        App.Categories = await ClientServices.ClientServicesLocator.CategoriesService.GetAllCategoriesAsync();
    }

    this.RefreshCategories();
}

As you can see, we no longer use a property of the ViewModel to bind it to the view: we just have an Action property that is raised once the data are loaded. In the code-behind of the page, here is how we use the Action property:

public CategoriesPage()
{
    InitializeComponent();

    this._viewModel = this.DataContext as CategoriesPageViewModel;
    if (this._viewModel != null)
    {
        this._viewModel.RefreshCategories = async () =>
        {
            this.CategoriesListBox.Items.Clear();

            foreach (var category in App.Categories)
            {
                this.CategoriesListBox.Items.Add(category);

                await Task.Delay(100);
            }

            this._viewModel.IsBusy = false;
        };
    }
}

So once the action is raised, we first starts by clearing the items on the ListBox then, for each items we want to add, we add it to the Items property of the control. Then, we make a small pause using Task.Delay, to give some time to the UI to be refreshed!

To get a more clean result, it’s also possible to modify the DataTemplate:

<DataTemplate>
    <TextBlock Text="{Binding Name}"
               Style="{StaticResource PhoneTextTitle2Style}"
               FontSize="40"
               controls:TiltEffect.IsTiltEnabled="True"
               x:Name="CategoryNameTextBlock">
        <TextBlock.Resources>
            <EventTrigger x:Name="LoadEventTrigger"
                          RoutedEvent="Canvas.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Name="FadeIn">
                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                                       Storyboard.TargetName="CategoryNameTextBlock">
                            <EasingDoubleKeyFrame KeyTime="0" Value="0.01"/>
                            <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="1"/>
                        </DoubleAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </TextBlock.Resources>
    </TextBlock>
</DataTemplate>

When the item is loaded, an animation is raised to change its opacity from 0 to 1. The result of the code can be seen on the first page of the following video (the animation on the second page will be covered in another post):

 

Happy coding!

Recently, I started to work on a Windows Phone application with all the data available through a Website (thanks to HtmlAgilityPack for helping me to parse the webpages).

All the parsing was quite easy but when I wanted to implement the search feature, I wondered how I could do this without any API ? Then, I discovered that the website was using a search form to propose the feature to its users so that was the way !

Here is the HTML code corresponding to the search form on the website:

<form method="post" action="http://www.mysyperwebsite.com/results.html">
    <input type="text" name="keyword" size="25" value="Enter some text..." onfocus="if (this.value=='Enter some text...') {this.value=''}" class="champs">&nbsp;
    <input type="button" onclick="ValidateSearch(this.form)" value="Search" alt="Search">
</form>

As we can see, the form send its data to the URL http://www.mysuperwebsite.com/results.html using the POST method. And that’s all we need to know! Indeed, we’ll do the same thing in our application: we’ll send a POST request to the indicated URL.

For that, we’ll use the HttpClient API and its PostAsync method (you can use the portable version of the HttpClient if you want). The PostAsync method takes in parameters the URI where to post the data and the content to send/post:

image

 

As we mimic the behavior of the form which post content, we’ll use the FormUrlEncodedContent object. This one takes in parameters a list of KeyValuePair, corresponding to the parameters sent by the search form:

var searchParameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("keyword", searchText) };

Here is the complete code:

var searchUri = "http://www.mysuperwebsite.com/results.html";
var searchParameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("keyword", searchText) };

using (var httpclient = new HttpClient())
{
    using (var content = new FormUrlEncodedContent(searchParameters))
    {
        using (var responseMessages = await httpclient.PostAsync(new Uri(searchUri, UriKind.Absolute), content))
        {
            return await responseMessages.Content.ReadAsStringAsync();
        }
    }
}

And voilà! Now, if you execute this code, it will be the same as if user use the search form.

 

Happy coding (and new year) ! :)

During my last holidays, I’ve started to work on a new Windows 8 project (more details on that later) that use Windows Azure Mobile Services as a backend.

During the development, I’ve encountered the following issue which, I suppose, is a bug that will be fixed later.

On my application, I used the following code:

var allItems = await ServiceClient.GetTable<Items>().Where(i => i.IsPublished).ToListAsync();

return allItems;

Unfortunately, this code thrown, every time, the following error:

image

After taking a look in Fiddler, I found the problem:

image

As you may know, Mobile Services use REST to access data on the server and the following REST query does not seem to be valid because there is no query operator (like eq for equal, etc.) and no value. So, I’ve tried to modify my code like this:

var allItems = await ServiceClient.GetTable<Items>().Where(i => i.IsPublished == true).ToListAsync();

return allItems;

As you can see, I’ve just append “== true” to the Where clause and all seems to work like a charm. Indeed, no exception was rise and, looking at the REST query, we can see that all is OK:

image

 

Happy coding!

ASP.NET SignalR is a project developed by Microsoft to allow developers to add real-time web functionality to your applications. Here is the official description of the project:

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is “real-time web” functionality? It’s the ability to have your server-side code push content to the connected clients as it happens, in real-time.

You may have heard of WebSockets, a new HTML5 API that enables bi-directional communication between the browser and server. SignalR will use WebSockets under the covers when it’s available, and gracefully fallback to other techniques and technologies when it isn’t, while your application code stays the same.

SignalR also provides a very simple, high-level API for doing server to client RPC (call JavaScript functions in your clients’ browsers from server-side .NET code) in your ASP.NET application, as well as adding useful hooks for connection management, e.g. connect/disconnect events, grouping connections, authorization.

So as soon as you plan to push content from your server to one (of more) of clients, you might take a look at SignalR. I’ve started to play with it this week (a good way to start the new year) and so, here is a brief introduction to this (and powerful) framework!

First, on the server side, you have to add a reference to the correct Nuget package (be careful, the project is not in the stable branch yet):

image

Then, you have to create a Hub, in other words a kind of endpoint that will expose the methods to all the clients. Defining a hub just mean create a class that derive from the Hub class:

public class DemoHub : Hub
{
    public void Send(string message)
    {
        Clients.All.getMessage(message);
    }

    public string SayHello(string name)
    {
        return "Hello" + name;
    }
}

Deriving from the Hub class allows you to access to the Clients property which can be used to access:

  1. To all the clients connected (through the All property),
  2. To the caller of the method (through the Caller property),
  3. Etc

image

Once that you get access to the list of clients you want, you can call the methods that you want on that clients (here, on our code, we call the getMessage of each clients, passing in parameter needed):

public void Send(string message)
{
    Clients.All.getMessage(message);
}

Of course, you can also defined some methods that will be called by the clients:

public string SayHello(string name)
{
    return "Hello" + name;
}

Now that the server part is done, we can start the client part. SignalR have Nuget packages for most of the client API: .NET, Windows Phone, WinRT, Silverlight and even Javascript: this is very powerful !

First, we need to create a connection to the Web Server:

var connection = new HubConnection("http://localhost:49449/");

Once this is done, we can create a proxy that will allow us to invoke methods on the server (and being notified when the server call a method on the clients): it’s the same job as the WCF proxy created when you add a service reference (except that this new one is not strongly typed):

var proxy = connection.CreateHubProxy("DemoHub");

You can see that the CreateHubProxy method takes in parameter the class name of the Hub you’ve created on the Web Server. If you want, you can use the HubName attribute (on the Hub class) to get a kind of alias for your hub:

[HubName("MyHubTest")]
public class DemoHub : Hub

In that case, the method CreateHubProxy will look like:

// Create a proxy to the service
var proxy = connection.CreateHubProxy("MyHubTest");

Next, you have to perform 2 things:

  1. Add a kid of event handler to all the methods that will be called by the server of the clients
  2. Start the connection

If the second one is really simple (just call the Start method of the HubConnection type), the first one is simple too. Indeed, on the proxy you’ve created, you can use the extension method On, that takes in parameters:

  1. The name of the “event” you want to be notified
  2. An Action (and its parameters) corresponding to the parameters sent from the server

image

So, in our case, if we want to be notified when the method getMessage is called from the server, we just need to use the following code:

proxy.On("getMessage", message =>
{
    this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => lb.Items.Add(message));
});

// Start the connection
await connection.Start();

Pretty simple!

Lastly, we need to be able to invoke the methods defined on the Hub so we’ll use the method Invoke of the proxy:

// Call the method on the server
await proxy.Invoke("Send", "My name is WinRT");

// Call the method on the server and get the result
var s = await proxy.Invoke<string>("SayHello", "Tom");

Now, let’s use the same code from an application console:

// Connect to the service
var connection = new HubConnection("http://localhost:49449/");

// Create a proxy to the service
var proxy = connection.CreateHubProxy("DemoHub");

// Start the connection
await connection.Start();

// Call the method on the server
await proxy.Invoke("Send", "My name is Console");

(As you can see, the code is strictly the same !)

If we launch the application from the Windows 8 side (the one where the handler to getMessage has been set), we can see that all the messages has been sent to the server and broadcast to the clients:

image

So, as you can see, getting push system in any kind of applications is pretty easy using SignalR. If you want to get more info, you can take a look at the Wiki. Also, don’t hesitate to go to David Fowler’s blog, the main developer of the project.

 

Happy coding!