Quest for a Range control

For nearly two weeks I was on a quest to find a Range control, ie a slider with two thumbs. After going several rounds through all the resources available online and offline I figured, there isn’t a ‘free’ range control.

And I really was in need of one. Found Jerry Nixon’s answer to someone’s post on StackOverFlow which served me as a base for the control. I have no clue how to make a custom control. So have uploaded the whole project to GitHub. Feel free to contribute or file issues.

Here’s your range control! 🙂

https://github.com/alfah-plackal/CustomSlider

May the code be with you! 😀

Quick Tip #4 – Creating Row and Column Definitions through code

Xaml is a piece of cake for Grid related adjustments. But a little work needs to be done if yyou are trying to achieve the same through the code-behind.

 
</pre>
<pre>Grid parentGrid = new Grid();
RowDefinition rd = new RowDefinition();
RowDefinition rd2 = new RowDefinition();</pre>
<pre>ColumnDefinition col1 = new ColumnDefinition();
ColumnDefinition col2 = new ColumnDefinition();
ColumnDefinition col3 = new ColumnDefinition();

col1.Width = new GridLength(1, GridUnitType.Auto);
col2.Width = new GridLength(1, GridUnitType.Star);
col3.Width = new GridLength(1, GridUnitType.Auto);

parentGrid.ColumnDefinitions.Add(col1);
parentGrid.ColumnDefinitions.Add(col2);
parentGrid.ColumnDefinitions.Add(col3);

parentGrid.RowDefinitions.Add(rd);
parentGrid.RowDefinitions.Add(rd2);

Grid.SetColumn(dotBorder, 0); // Setting a Border element to (0,0)
Grid.SetRow(dotBorder, 0);

Grid.SetColumn(dateText, 1); // Setting a textblock element to (0,1)
Grid.SetRow(dateText, 0);

Grid.SetColumn(delButton, 2); // Setting a button to (0,2)
Grid.SetRow(delButton, 0);

Grid.SetColumn(SympStack, 0);// Setting a Stack panel to row 0 and columnspan of 3
Grid.SetColumnSpan(SympStack, 3);
Grid.SetRow(SympStack, 1);

parentGrid.Children.Add(dotBorder); // Adding all the elements to the grid
parentGrid.Children.Add(dateText);
parentGrid.Children.Add(delButton);

parentGrid.Children.Add(SympStack);

May the code be with you! 😀
logosmall

Quick Tip #1

Content wrap is by default not available for Buttons and Hyperlink button for both Windows Phone and Windows RT. But modifying the Content Template allows you to add Text Wrap 🙂


 <HyperlinkButton>
          <HyperlinkButton.ContentTemplate>
                <DataTemplate>
                       <TextBlock Text="{Binding}" TextWrapping="Wrap"/>
                </DataTemplate>
           </HyperlinkButton.ContentTemplate>
 </HyperlinkButton>

 

May the code be with you! 😀

chops-logo2 small

 

The Deadly Access Denied Error!

I could hear the unmistakable whooooooshhh sound of app submission deadline approaching. The app was going through rigorous  and meticulous testing. And finally, we reached a point where no more bugs could be pulled out (*relief) 😀 Although rare occurrence of some garbage value was noted, since it looked liked one of the type, I was a little complacent…

And in the 11th hour, as expected, when everything is bound to go wrong, that ugly pile of garbage values started started popping up, like daisies!

So lemme describe the scenario here.

The apps writes a series of values into files at different points of its execution. The values, be it of type integer, Datetime, bool, would be converted to strings and written to different files. This is how I wrote the values into files

public async Task<bool> WriteHistoryToFile()
{
try
 {
 StorageFile sampleFile = await localfolder.CreateFileAsync("HistoryFile", CreationCollisionOption.ReplaceExisting);
 var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
using (var outputStream = stream.GetOutputStreamAt(0))
{
DataWriter dataWriter = new DataWriter(outputStream);
for (int i = 0; i < m_iHistCount; i++)
dataWriter.WriteString(m_dtHistory[i].ToString("d", CultureInfo.InvariantCulture) + "`~");
  await dataWriter.StoreAsync();
  await dataWriter.FlushAsync();
dataWriter.Dispose();
await outputStream.FlushAsync();
fileWrite = true;
}
}
catch (Exception e)
{
 string str = e.Message;
 fileWrite = false;
}
}

On closer examination of the code, I found that, the first call of the function WriteHistoryToFile happens perfectly alright, but if a subsequent call is made to the same function, it would directly go to the catch block! The error message was the a one liner. “ACCESS DENIED”. How very convenient and frustrating!. Clearly I was missing something.

As per msdn docs, you need to open file, create a stream for writing, use a data writer to write into the stream , call StoreAsync and flush the stream. Somehow this seems to be not working.

Frantic searching in the web gave me several instances of the same error thrown, and some had narrated the same scenario. The explanation everyone said was, the stream needs to be freed of the resources, but hey! im flushing the stream. I looked for a close function for the stream which is nonexistent. But I found a Dispose() for the output stream who happened to be my saviour for the day!

So everybody, who has over looked that teensy Dispose(), do not forget this function if you don’t want to be slapped with a Access Denied Exception!

try
 {
 StorageFile sampleFile = await localfolder.CreateFileAsync("HistoryFile", CreationCollisionOption.ReplaceExisting);
var stream = await sampleFile.OpenStreamForWriteAsync();
using (var outputStream = stream)
 {
 DataWriter dataWriter = new DataWriter(outputStream.AsOutputStream());
 for (int i = 0; i < m_iHistCount; i++)
   dataWriter.WriteString(m_dtHistory[i].ToString("d", CultureInfo.InvariantCulture) + "`~");
 await dataWriter.StoreAsync();
 await outputStream.FlushAsync();
 outputStream.Dispose(); // HE is the guy you need! 😀
 fileWrite = true;
 }
}
 catch (Exception e)
 {
 string str = e.Message;
 fileWrite = false;
 }

Note: If you have wrapped the code. with out dispose function, in try catch block, the app would not crash. Execution will move to the catch block and graciously move on. The exception would go unnoticed if you have not set break points. 🙂

May the code be with you!! 🙂

logosmall

References :-
MSDN – Files – This does not mention of the Dispose function! 

Toast notifications for Windows 8

Toast notifications are notifications sent from the app to the user. Nevertheless which app you are in, the notifications appear from top right corner, notifying you of an event or a reminder. Toasts can have images and texts but no secondary actions such as buttons. Clicking on a toasts will take the user to the respective app and is the only method by which one app can interrupt the other.

To make things easier, Microsoft provides us with 8 templates from which we can choose the one which fits our needs.

Now lets take a look at creating ToastImageAndText02

First we create a string ‘toastXmlString‘ which basically the string from which xml will be created. Here ‘alarmHeader’ will hold the heading of the toast. and ‘alarmDescription‘ will be the text following the heading.

alarmHeader = "My alarm";
alarmDescription = "The alarm will be displayed as a toast";

string toastXmlString =
“<toast duration=\”long\”>\n” +
“<visual>\n” +
“<binding template=\”ToastText02\”>\n” +
“<text id=\”1\”>” + alarmHeader+ “</text>\n” +
“<text id=\”2\”>” + alarmDescription + “</text>\n” +
“</binding>\n” +
“</visual>\n” +
“<commands scenario=\”alarm\”>\n” +
“<command id=\”snooze\”/>\n” +
“<command id=\”dismiss\”/>\n” +
“</commands>\n” +
“<audio src=\”ms-winsoundevent:Notification.Looping.Alarm2\” loop=\”true\” />\n” +
“</toast>\n”;

<text id> 1 and 2 are the text we provide, while <command id> is the action which can be performed when an toast pops up, and in this alarm scenario, it is snooze and dismiss. <audio src> is the source of the audio file which needs to be played when the alarm pops up.

Our string is ready and now we need to create an xml from it.

var toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
toastDOM.LoadXml(toastXmlString);

We need an object that will raise the toast for the application.

var toastNotifier = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();

We are all set to schedule this toast to appear at a particular time. Here ‘date’ is a DateTime variable which has been set to particular date and time.

var customAlarmScheduledToast = new Windows.UI.Notifications.ScheduledToastNotification(toastDOM, date);
toastNotifier.AddToSchedule(customAlarmScheduledToast);

Its not finished yet. You need to go to the manifest file either from the solution explorer or click
Store ->Edit Manifest

In the application tab, under Notifications heading, Make the Toast capable option to ‘Yes‘. And you are good to go!

The toast is out of the toaster 😀

You can also create the toast through  standard DOM functions:. I have provided MSDN links describing the same

May the code be with you! 😀

chops-logo2 small

References


			

Integrating Google Analytics in WP/WinRT

How we had wished there was a Google Analytics SDK for windows phone and windows 8! The ease of a Google dashboard, the amount of info that it gives, the integration,  is way superior as compared to the other analytics tools available in the market.

and here is a GoogleAnalyticsSDK available in Codeplex. Works perfect and well documented! (An unusual combination :P)

Integration is a piece of cake!

Google Analytics SDK

May the code be with you! 😀

Saving a Canvas into a PNG file – WP8

This is a familiar situation that most developers run into. The need to save a canvas element to a png file.

Scenario

  • You have few strokes drawn on a canvas and you want to save it as a png .
  • You want to save the just the strokes on a transparent background.
  • You want to save the strokes along with the canvas background.
  • You want to save it with your specified sizes

I too ran into this ditch lately. And had a tough time finding a solution. A random google search will give you numerous methods, most of which is applicable only to traditional C#/.NET application.

Then I found this MSDN link. I still have’nt figured out how to use a PNGEncoder and DeCoder. If anyone finds a good blog about it, feel free to post it here. Many of the solutions I found never worked. The searches how ever led me to the WriteableBitmapEx hosted at codeplex. It had several useful functions but none to save a canvas to an image.

A week’s search, frustration, irritation,  trial & error of several broken classes finally led me to ToolStack. It is mentioned that it works for Windows Phone 7.1 but I have implemented in WP8 project. There 3 classes which will do the job neatly, although compression is not yet implemented.

  1. ToolStackPNGWriterWBext.cs – Implementation of WriteableBitmapExtensions
  2. ToolStackPNGWriterLib.cs – Core Class and implementation of saving to PNG
  3. ToolStackCRCLib.cs – Additional classes needed for ToolStackPNGWriterLib.

Getting it working on your project.

  1.  Download all necessary files from ToolStack. Download the example too and run it first so that you can understand how it works.
  2.  Add the Classes mentioned to your project.
  3. Create a Writeablebitmap of your canvas and then use the WritePNG function to save
    </pre>
    WriteableBitmap wb = new WriteableBitmap(MyCanvas, null);
    wb.WritePNG(MyStreamforWriteAsync);
    <pre>

And there your image lies in the specified location, in the size of your canvas! 🙂  Remember to add the necessary using statements in your file. Any canvas element can be captured into a WritableBitmap, even an InkPresenter can be captured.

NOTE TO WIN8 DEVELOPERS

If you try to implement the same functionality in a metro app, you’re in for trouble mate. Because the very simple function which allows to capture a canvas onto a WriteableBitmap does not exist! There is a method to save the inkstrokes though, but only the portion containing the stroke will be saved. You cannot save it along with its transparent/colored background. I consulted few developers and they seem to have no answer too. It seems this is possible in JavaScript.

Lets see if Windows 8.1 contains something for us developers in this direction.

Happy Coding!! 😀