Where am I?

It has been one long journey from 2011 all the way to 2021. Most of all, I have survived 10 years of coding and still got life for some more of it. I consider that an achievement in this ever evolving industry!

My career started with coding for Samsung Bada and Nokia Symbian. It was a such a short stint that i don’t remember much of it now, to be honest. It was in 2012 I started my love affair with C# and Windows Phone. Although Windows Phone took off with much fanfare, it came to a sorrow end. Microsoft made some major goof ups here and there. That said, C# and me has had a mature adult relationship. I fiddled with Java and Android before leaving my first job.

Phase 2 of the career was major change. From a start-up , I moved on to an MNC. Retail solution became my new domain. From being involved in all phases of product development, I shifted attention to writing more code. It has its merits and demerits but that’s for another time. As for domain. I entered into the world of RFID readers and other hand held devices. Though I got back to C#, it was a minor set back in terms of technology stack. After working on the latest versions of .NET and C#, I had to roll back to WinCE(Windows Compact edition). The handheld devices ran on Windows CE which is almost a dinosaur in this age. A lot of the latest feature of C# could not be used as the framework support was old. It was still a new journey for me, as I had to get deep into device related coding and fundamental concepts of design. RFID world is a fascinating new domain or me. After 3 years, development for WinCE devices ceased giving me some sort of deja-vu. May be small portable devices isnt really a Microsoft thing.

So I started dabbling with Android once again. Coming from windows phone, it was as if i got a power booster. There were fundamental differences between how the platform worked, but language wise, it was a smooth transition. Now comes in 2020 along with pandemic and skillset upgrade. Xamarin – the new boy in town.

The app we had was an on-prem based model. Decision was to move the whole app to cloud and micro services.

All of the mobile clients(ios, android) would be reworked in Xamarin.Android and Xamarin.iOS. I had a new ramp up on a lot of new things. I was pretty much cut off from the latest C# and .NET version. So here I’m, trying to find out how to get things done in Xamarin.

More for later!

May the code be with you!

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 #3 – Checking for Internet Connectivity

How do we get to know whether the app has internet connectivity? This is important when you want to check for connectivity before doing a server sync.

 public static bool IsInternetAvailable
 {
   get
    {
     var profiles = NetworkInformation.GetConnectionProfiles();
     var internetProfile = NetworkInformation.GetInternetConnectionProfile();
     return profiles.Any(s => s.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess) || (internetProfile != null && internetProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
    }
 }

May the code be with you! 😀

logosmall

 

Quick Tip #2 – Stretching the ItemContainter of ListView

Suppose you have a data template for a Listview. It so happens that the Grid does not fill the whole list view. Your content seems to be left aligned.

Solution: You  need to set the ItemContainerStyle for the ListView


<ListView x:Name="InviteLV" ItemsSource="{Binding}" HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid MinHeight="60" HorizontalAlignment="Stretch" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel HorizontalAlignment="Stretch" Margin="10,0,20,0">
<TextBlock Text="{Binding InviteName}" Foreground="Black" FontSize="26"/>
<TextBlock Text="{Binding InviteEmail}" Foreground="Black" FontSize="26"/>
</StackPanel>
<Button Grid.Column="1" BorderThickness="0" Width="50" Height="50" Margin="0">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="Assets/Images/theme1_but_cancel_normal.png"/>
</Button.Background>
</Button>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>

<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>

</ListView>
<pre>

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! 😀

How to add multiple versions of the assembly without causing conflicts! -WP

An unusual sticky situation it is!

You have a external class, say Class Saviour , in your project. Class Saviour  uses another class, Class MostSoughtAfter from codeplex. Class Saviour has implemented Class MostSoughtAfter to suit its needs. So where ever you create an instance of Class MostSoughtAfter,  it will refer the Class MostSoughtAfter defined by Class Saviour . Suppose you need to use a function in the original Class MostSoughtAfter, and you add the dll . Visual Studio will throw a warning saying there is an ambiguity and that Class MostSoughtAfter implemented in Class Saviour is used to instantiate.

Bingo! You have multiple versions of the same class in your project and you need to reference them separately. I found a similar question in StackOverflow

Now in C# we have an “extern alias” keyword which will allow us to do the same. MSDN says

By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, which enables them to be used in the same file.

  1. In the solution explorer of your project, click the properties of the dll you want to reference,
  2. The Aliases field is set to ‘global’ by default. Change the global to name of your choice, say MyDLL.
  3. In the class you want to use the dll, first declare the alias right above the using statements
    extern alias MyDLL;
    
  4. To use a method in the assembly we make use of :: qualifier
    MyDLL:: System.Windows.Media.Imaging.MyClass.Resize();
    
  5. Thus a simple creation of an instance of MyClass will use the class implemented in the project. And if you want to use the original dll reference using the alias .

‘extern’  and an MSDN blog saves my day!!

References

Happy coding !! 😀