Pages

Friday, 14 February 2014

Save WriteableBitmap as StorageFile in WinRT app

WriteableBitmap is quite useful when app requires image processing. It provides a BitmapSource, which can be written & manipulated. Ultimately that bitmap source is supplied to image control of Windows 8 app. Majorly WritableBitmap is more used with WriteableBitmapEx library, which is a collection of extension methods for the WriteableBitmap.

But we won't go for manipulating images using WriteableBitmap or WriteableBitmapEx, but we step forward to the next step, which is saving it as file i.e. StorageFile. It's obvious that end user will definitely wants to share or save the modified image or better say WriteableBitmap. So we will need to convert WriteableBitmap to StorageFile.

Before going to code directly, let me explain API used in that. For image encoding WinRT offers BitmapEncoder class. For image encoding we have to select BitmapEncoderGuid which is basically format of image viz JPEG, PNG, TIFF, etc. It's actually unique identifier for each bitmap encoder.

We will first export WriteableBitmap's pixel buffer into byte array. After that we will initialize the bitmap encoder with Guid & destination file stream. At last we will set the pixel data to bitmap encoder. Bitmap encoder's SetPixelData(...) gets various parameters to write the pixels in various ways. Check out the method metadata given below. At last we will have the file ready. Let's check out the code.

Metadata of method and enum.

// Summary:
//     Specifies the alpha mode of pixel data.
public enum BitmapAlphaMode
{
    // Summary:
    //     The alpha value has been premultiplied. Each color is first scaled by the
    //     alpha value. The alpha value itself is the same in both straight and premultiplied
    //     alpha. Typically, no color channel value is greater than the alpha channel
    //     value. If a color channel value in a premultiplied format is greater than
    //     the alpha channel, the standard source-over blending math results in an additive
    //     blend.
    Premultiplied = 0,
    //
    // Summary:
    //     The alpha value has not been premultiplied. The alpha channel indicates the
    //     transparency of the color.
    Straight = 1,
    //
    // Summary:
    //     The alpha value is ignored.
    Ignore = 2,
}


// Summary:
//     Specifies the pixel format of pixel data. Each enumeration value defines
//     a channel ordering, bit depth, and type.
public enum BitmapPixelFormat
{
    // Summary:
    //     The pixel format is unknown.
    Unknown = 0,
    //
    // Summary:
    //     The pixel format is R16B16G16A16 unsigned integer.
    Rgba16 = 12,
    //
    // Summary:
    //     The pixel format is R8G8B8A8 unsigned integer.
    Rgba8 = 30,
    //
    // Summary:
    //     The pixel format is B8G8R8A8 unsigned integer.
    Bgra8 = 87,
}

// Summary:
//     Sets the frame bitmap pixel data using the parameters specified in the arguments.
//
// Parameters:
//   pixelFormat:
//     The pixel format of the pixel data.
//
//   alphaMode:
//     The alpha mode of the pixel data.
//
//   width:
//     The width, in pixels, of the pixel data.
//
//   height:
//     The height, in pixels, of the pixel data.
//
//   dpiX:
//     The horizontal resolution, in dots per inch, of the pixel data.
//
//   dpiY:
//     The vertical resolution, in dots per inch, of the pixel data.
//
//   pixels:
//     The pixel data.
public void SetPixelData(BitmapPixelFormat pixelFormat, BitmapAlphaMode alphaMode, uint width, uint height, double dpiX, double dpiY, byte[] pixels);

The code to convert WriteableBitmap object to StorageFile in WinRT app

using System.Runtime.InteropServices.WindowsRuntime;

private async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat)
{
    string FileName = "MyFile.";
    Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
    switch (fileFormat)
    {
        case FileFormat.Jpeg:
            FileName += "jpeg";
            BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            break;

        case FileFormat.Png:
            FileName += "png";
            BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
            break;

        case FileFormat.Bmp:
            FileName += "bmp";
            BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
            break;

        case FileFormat.Tiff:
            FileName += "tiff";
            BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
            break;

        case FileFormat.Gif:
            FileName += "gif";
            BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
            break;
    }

    var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
        Stream pixelStream = WB.PixelBuffer.AsStream();
        byte[] pixels = new byte[pixelStream.Length];
        await pixelStream.ReadAsync(pixels, 0, pixels.Length);

        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                            (uint)WB.PixelWidth,
                            (uint)WB.PixelHeight,
                            96.0,
                            96.0,
                            pixels);
        await encoder.FlushAsync();
    }
    return file;
}

private enum FileFormat
{
    Jpeg,
    Png,
    Bmp,
    Tiff,
    Gif
}

Don't forget to add System.Runtime.InteropServices.WindowsRuntime namespace.

I hope this blog post would be helpful to you. I request you to share it as much as you can. If you need any help shout out me on Twitter & Facebook or comment below. I will catch you ASAP. Cheers!

Wednesday, 5 February 2014

Meet Satya Nadella - Third CEO of Microsoft

It's official that former vice president of Microsoft’s Cloud and Enterprise group Satya Nadella is elected as CEO of Microsoft, succeeding Steve Ballmar.

When Steve Ballmar announced his retirement as CEO of Microsoft, each MS developer was thinking who will be the next? The Nokia-Microsoft deal was referring Stephen Elop could be next CEO but secret is revealed.

Satya has great India connection. He was born in Hyderabad. He is alma mater of Manipal Institute of Technology. He joined Microsoft 22 years ago. #SatyaNadella becomes trending topic on Twitter within few minutes after press release regarding the next CEO. He has worked for many departments in Microsoft, like
  • President of the Server & Tools
  • Senior Vice President of Research and Development for the Online Services Division
  • Vice President of the Microsoft Business Division
  • Corporate Vice President of Microsoft Business Solutions and Search & Advertising Platform Group
  • Vice president of Microsoft’s Cloud and Enterprise group
Steve Ballmar is a more of marketing guy but Satya is more of "techie" guy. He has many challenges to crack. Biggest challenge is to increase market share of Windows 8.1, Windows Phone 8 and Surface tablets. We can now expect Windows Phone 8.1's keynote from himself. Windows Azure is being managed under him so we are seeing Azure has gain awesome momentum. So we are hoping such momentum in the consumer products also.


Don't forget to check out the dedicated CEO pageI wish best of luck to Satya Nadella.

Friday, 31 January 2014

Disable WebView scrolling in Windows Store Apps

WebView is a control which enables developers to host the HTML content. In WinRT framework WebView still lacks some features when we compare it to the WebBrowser of WPF. WebView class inherits from FrameworkElement class, but many properties of base class in not working in WebView.

Recently I was creating an app and I want to disable the horizontal & vertical scrolling of WebView. I tried below given code.

<WebView x:Name="webView" Source="http://myawesomewebsite.com"
    ScrollViewer.VerticalScrollBarVisibility="Disabled"
    ScrollViewer.VerticalScrollMode="Disabled"/>

But it didn't work. I was getting annoyed. I start binging & googling but didn't get any solution. WebView doesn't have its template also. Then I start analyzing the control in microscopic way. Finally I get to know that the scroll bars are due to HTML content, WebView itself doesn't have its own scroll bars. So I decided to go for JavaScript way. I applied some CSS properties in HTML content using JavaScript. It will display only that HTML content which is being displayed in current viewport or say display area. WebView provides InvokeScript method, which executes the specified script function from the currently loaded HTML, with specific arguments. When WebView's LoadCompleted event occurs, I am invoking that JavaScript which disables the scrolling. Check out whole code given below.

string DisableScrollingJs = @"function RemoveScrolling()
                              {
                                  var styleElement = document.createElement('style');
                                  var styleText = 'body, html { overflow: hidden; }'
                                  var headElements = document.getElementsByTagName('head');
                                  styleElement.type = 'text/css';
                                  if (headElements.length == 1)
                                  {
                                      headElements[0].appendChild(styleElement);
                                  }
                                  else if (document.head)
                                  {
                                      document.head.appendChild(styleElement);
                                  }
                                  if (styleElement.styleSheet)
                                  {
                                      styleElement.styleSheet.cssText = styleText;
                                  }
                              }";

void webView_LoadCompleted(object sender, NavigationEventArgs e)
{
    webView.InvokeScript("eval", new[] { DisableScrollingJs });
}

I hope this blog post will help you while developing WebView oriented app if you required such feature to implement.

Saturday, 24 August 2013

Helper class to print the text box content in Windows Store App

Introduction

Microsoft's documentation & sample for printing is too much complex. The sample app for printing shows only how to print RichTextBlock. There's no tutorial to print the TextBox content in Windows Store app. Moreover to print single line of string, one has to write too much code rather than maximum 10 lines in WinForm. So this helper class provides simplest method to print the text box content. It has only one static method. It prints the text box content with its formatting. It's majorly based on MSDN print sample.

I got idea to write a library from the following Stack Overflow questions.

How to print the contents of a TextBox ?

How do you print contents of a RichTextBox ?

How do I print a TextFile OR contents of a TextBox in Metro apps ?

How to use it ?

You have to call just one static method ShowPrintUIAsync of class Printer, it will do print job on your behalf.

await Printer.ShowPrintUIAsync(PrintPreview, MyTextBox, Guid.NewGuid().ToString());

  • PrintPreview is a canvas, which is mandatory to show print preview in device charm. You have to declare in your XAML. 
  • MyTextBox is a text box object, whose text content is going to be printed. 
  • Guid.NewGuid().ToString() is a file name for printing the document. (It will be applied if you are creating PDF or XPS file via printing.)
To install WinRT.TextboxPrintHelper as NuGet package, run the following command in the Package Manager Console.

PM> Install-Package WinRT.TextboxPrintHelper

I would be glad to have issues or suggestions from you, so I can improve this. If you want to fork the repository or post issues, find this helper class on GitHub.

Tuesday, 23 October 2012

Ten Things You Need to Know About WebView

  1. WebView is not a general-purpose browser
  2. WebView always renders on top of XAML
  3. WebView doesn’t do Flash.  Or Silverlight.  Or PDF.  Or any other ActiveX control or plugin.
  4. How to invoke Javascript inside the displayed webpage of a Webview
  5. How to receive information from the WebView
  6. How to inject javascript into a WebView page
  7. How to clear the WebView cache
  8. How to embed a font into your app to be used by WebView
  9. Launching other apps from a link inside WebView
  10. How to get rid of those annoying JavaScript exceptions when debugging

Click here to know more

Testing in-app puchasing in Windows 8

One of the many new features with upcoming Windows 8 is the Windows Store distribution and monetization channel. Developers can now add in-app purchasing to their apps. The prizes are the same as application prizes in store, e.g. starting from 1,49 USD (1,19 EUR) and gradually growing up in 50 cent increments. Because it seems testing in-app purchasing system isn’t trivial to everybody, here’s a quick sample to get you started. This is only a basic example to get you started, so I don’t cover different in-app types.

Read More

Microsoft DevRadio: Your Top Windows Store Questions Answered


Jerry Nixon welcomes Principal Program Manager Arik Cohen to the show as they discuss the recently launched Windows Store and a wide variety of topics developers ask most.

Read More

Shortcut Key Handling in Windows Store Apps

I wanted to create a simple ALT+S shortcut in my app to jump to a TextBox in my Windows Store App (no this is not the Win+Q search charm shortcut). However, this is not that obvious to get working app-wide, so I’ll share it here:

The obvious way to do this is assign a KeyDown event to your page using the typical “this.KeyDown += MyKeyDownHandler”, or override OnKeyDown. However this has one problem: If any control that has focus currently handles key down events (like TextBox), this event won’t be raised due to how event bubbling works. However there is another way to create an event handler that overrides the bubbling: UIElement.AddHandler. In the 3rd parameter of that, you can specify that you want to be notified even if the event has been handled.

Read More

Top 10 features of the Microsoft Surface

Top 10 features of the Microsoft Surface
Microsoft Surface is the new tablet device made by Microsoft, running Windows RT and Windows 8. InformationWeek, today, released their top 10 for the coolest features of Microsoft Surface. I have listed them below with a little more information next to each.

Surface: Where work meets play. The power of Windows, the productivity of Office Home & Student 2013 RT Preview, and the joy of Xbox – not to mention apps, social media, music, and more. Surface is also cloud-connected with SkyDrive, so you can access your content from anywhere, at any time.

Read More

Preparing your Windows 8 Applications for the store

Preparing your Windows 8 Applications for the storeIf you are a student in the US, you have the ability to get access to the Windows 8 store for no cost through DreamSpark.  You will need an email account that has the EDU extension.

Once you have access to the Windows 8 Store then you can upload your app to the windows 8 store, but it can be confusing when you see all of the squares that you have to click.

First thing you need to do in the Windows Store: Click on Submit App and then Reserve a name.  Why? If you do not reserve a name then you can’t upload your package (the file with the appxupload extension).  Once you have that done, then you can upload your app.

Read More

Data Template Selector in Windows 8 Metro XAML App

Data Template Selector in Windows 8 Metro XAML App
It has been work around to have more than one data template in a list to display the data. In Windows 8 it has been eased, WinRT introduces the DataTemplateSelector class, where we could have more than one template to display in an items source control in Windows 8. In this article we would discover that.

To explore the sample, you definitely need Windows 8 Consumer Preview and Visual Studio 2012 RC.

Read More

How to Test Your Windows 8 App Before Submitting to the Store

How to Test Your Windows 8 App Before Submitting to the Store
It’s always a good idea to test your application before submitting it to the store. The Windows Application Certification Kit (WACK) tool can save you from failing the early automated tests.

The first thing you’ll want to do is uninstall any existing build of your application. This is important because the WACK tool may fail if a previous debug build is still installed on the system. To uninstall your app, find it on the Start experience, right-click and choose ‘Uninstall’.

Read More

Saturday, 20 October 2012

Controlling caching of BitMapImage under WinRT

By default Bitmap Images are cached by WinRT with no intervention required by the developer.  Often times this is a good thing but there are some occasions where this is undesirable.  Although there doesn’t appear to be any obvious control in the API reference I have found that adding a dummy querystring to the BitMapImage source filename reference does the trick and also can offer precise control over the length of caching required (if any) .

Read More

Walkthrough: using Windows 8 Custom Protocol Activation

Protocol activation, what is it? Well, when you run “http:{something}” you expect a browser to launch, right? When you type “mailto:{something}” you expect a mail client to launch, right? What if you could create “custom:{something}” that launched your app? That’s custom protocol activation!

Read More

Creating your own file format to import .FBX, .OBJ and .X in your Windows 8 modern UI game (or 3D engine)


There is a lot of different file format when it comes to 3D objects. One of the most used is the FBX from Autodesk. This file format can be exported by all major DCC but the key point is that it can be complex for a game or 3D developer to open such file format.

I would like to propose here a solution that can allows you to easily offline files importation. The idea is to simulate a MSBuild execution to reuse the importation process of the XNA pipeline.

Read More

The Windows Store App Lifecycle

The Windows Store App Lifecycle
Windows 8 is changing how and when applications run, and you’ll want to understand the nuances of the new application lifecycle so you can build apps that respond as they should at every point. Apps that conform to the Microsoft lifecycle management guidelines offer a better experience for the user, especially on small devices where memory and battery conservation are warranted.

Read More

Using the MVVM Pattern in Windows 8

Expression Blend for Windows Store Apps with Design-Time Data Using the MVVM Pattern in Windows 8
Any programmer with previous experience in any of the XAML-based frameworks has probably at least heard of the Model-View-ViewModel (MVVM) pattern. Some have been using it extensively in all of their Windows Presentation Foundation (WPF), Silverlight or Windows Phone applications. Others have avoided it, either because they misunderstand what the pattern does, exactly, or because they don’t want to add what they see as a new level of complexity to their application.

Read More
Download the Code Sample

Asynchronous Programming with Async and Await (C# and Visual Basic)


You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.

Visual Studio 2012 introduces a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and the Windows Runtime. The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code. As a result, you get all the advantages of asynchronous programming with a fraction of the effort.

Read More

Tuesday, 16 October 2012

Pizza Ordering Made Easy with Telerik RadControls for Metro - HTML

We all love pizza. I know that I do and several have speculated how it will be ordered in the future. Don’t take my word for it, check out the video above.

While it may seem strange that in the year 2015 people are using Windows 98 to order pizza, it may be more realistic to say they will be using Windows 8 instead. So, let’s build a Windows 8 HTML app using several new controls that are part of Telerik’s Windows 8 UI Controls that we have not seen yet. They include: RadDropDownList, RadSlider and RadGauge.

Read More

Callisto Dialog Helpers for Caliburn.Micro WinRT

Callisto Dialog Helpers for Caliburn.Micro WinRT
Callisto is excellent open source UI Control library for the Windows 8 Store apps. Caliburn.Micro is a powerful framework for building Windows Phone, Silverlight and Windows 8 Store apps. These helpers make it easies to combine Caliburn.Micro with the Callisto's dialogs.

Content
  • Helper for displaying settings dialogs on the Settings charm
  • Helper for displaying normal dialogs all around the screen
Read More
Get Library on CodePlex
Web Informer Button