Everything open-source about NerdCats

If you’re looking for open-source codebases to get your app running, NerdCats may probably has done those for you long ago. ūüėČ

Check out the list below:

  1. 9GAG.tv : A ad-free client for 9GAG.tv. A perfect example how you can use a website to make your app even without scraping HTML.
    source code: https://bitbucket.org/nerdcats/9gagtv/srcstore link: http://www.windowsphone.com/en-us/store/app/9gag-tv/eeb602c9-9b50-4d4d-9cc8-78f162a35720
  2. Bus Map Dhaka: The first and probably only map interactive Bus Route finder for Dhaka in all markets, still runs exclusively on Windows Phone
    source code: https://bitbucket.org/SPrateek/bus-map-dhaka
    store link: http://www.windowsphone.com/en-bd/store/app/bus-map-dhaka/3795f088-028a-4958-bea6-a2d0eb243bd9
  3. Medicine Directory Bangladesh: The only medicine directory available for Windows Phone Market. Simple yet extremely powerful
    source code: https://bitbucket.org/nerdcats/medicine-directory-bangladesh
    store link: http://www.windowsphone.com/en-us/store/app/medicine-directory-bangladesh/8e46cbb9-9ff6-4ac2-bc8d-e1ed198f0c42
  4. NerdCats Template Apps: A easy set of template apps for everyone to start making industry grade MVVM apps
    source code: https://bitbucket.org/nerdcats/nerdcats-template-apps
  5. Windows Phone 8.1 Complete Reference: Probably the first community written, github managed book and code sample for Windows Phone 8.1 WinRT, later may be Windows 10.
    source: https://github.com/thehoneymad/Wp8.1CompleteReference
  6. NerdCats Toolkit: NerdCats toolkit comes with UI controls for Windows Phone 8.1 that are somewhat missing, it contains homebrew controls and ports from previous versions of Windows Phone
    source: https://github.com/thehoneymad/NerdcatsToolkit

Hope these would boost up your journey towards awesomeness. May the “cats” be with you!

 

Advertisements

Saving a SpeechSynthesis Audio in a windows store/phone app

Usually after doing a little speech synthesizing in our phone we usually stumble on one question, can I save this stream?
Luckily you can! All you gotta do is pull this out of your sleeve. ūüôā

 


var synth = Windows.Media.SpeechSynthesis.SpeechSynthesizer();

SpeechSynthesisStream speechstream = await synth.SynthesizeTextToStreamAsync("Hello People");

using(var reader = new DataReader(speechstream))
{

await reader.LoadAsync((uint)stream.Size);

IBuffer buffer = reader.ReadBuffer((uint)stream.Size);

await FileIO.WriteBufferAsync(outputFile, buffer);

}

And, you’re done! Your file would be a .wav file of course.

Making a game controller out of your Windows Phone using VJoy – Part 1.

I know the title sounds really intriguing. Truth to be told it is indeed intriguing. And as it goes the outcome is pretty intriguing too.

The whole tutorial would take a bit time to get inside your head, so Im going to take it step by step.

Step 1: The Bluetooth Server

To have this whole thing going we will need a bluetooth server going. To facilitate a very very simple bluetooth server we are going to use a Windows Store app. So I jotted down a very very simple GUi for the server first.


<Page
    x:Class="BluetoothServer.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BluetoothServer"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel VerticalAlignment="Bottom" Margin="0,0,0,150" >
            <TextBlock Name="StatusText" FontSize="25" Margin="35,0,35,57" TextAlignment="Center"></TextBlock>
            <Button Content="Initiate Server"  Name="ServerToggleButton" HorizontalAlignment="Center" Click="Button_Click" />
            
        </StackPanel>
    </Grid>
</Page>

The only input mechanism I have in here is a textbox and a button. You pick the button to initiate a server and that’s it. All the code that has been used here are actually very very raw and coded in a hurry. So try to get the gist of the idea first so you can get yourself started.

The first method we are going to put in the back is an Initialization method for the server. This would actually Initialize the Bluetooth server we are going to use.


private StreamSocket socket;

private DataWriter writer;
private RfcommServiceProvider rfcommProvider;
private StreamSocketListener socketListener;

public async void InitializeRfCommServer()
{
            try
            {
                rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(RfcommServiceUuid));

                // Create a listener for this service and start listening
                socketListener = new StreamSocketListener();
                socketListener.ConnectionReceived += OnConnectionReceived;

                await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(),
                   SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                 // Set the SDP attributes and start Bluetooth advertising
                InitializeServiceSdpAttributes(rfcommProvider);
                rfcommProvider.StartAdvertising(socketListener);

                StatusText.Text="Listening for incoming connections";
                ServerInitiated = true;

            }
            catch(Exception e)
            {
                StatusText.Text = e.Message;
                
                ServerInitiated = false;
            }
}

Here, Windows.Devices.Bluetooth.Rfcomm comes in extremely handy as RfcommServiceProvider is the prefect class to start a RFComm session. But before all that you are going to need some basic stuff. First you will need a service GUID. You can make a GUID from any place but I suggest to try make an unique one. Here I used something I generated from a site online but you can definitely try your way. Then you are going to need a SdpServiceNameAttributeId and SdpServiceNameAttributeType. SdpServiceNameAttributeType is actually a 8 bit scenario where the least significant 3 bits contains attribute size and the most significant 5 bits contains the attribute type value. And last but not the least you will need a service name too.


        private static readonly Guid RfcommServiceUuid = Guid.Parse("482af5ed-3faf-4a51-9dd0-718c85aa64d0");
        private const UInt16 SdpServiceNameAttributeId = 0x100;
        private const byte SdpServiceNameAttributeType = (4 << 3) | 5;
        private const string SdpServiceName = "Bluetooth Rfcomm Listening Service for VJoy";

Please keep these in mind because we are going to need these in the client too. And you also have to define these in your Package.appxmanifest too to make the server authorized to use the bluetooth in your pc.


<m2:DeviceCapability Name="bluetooth.rfcomm">
      <m2:Device Id="any">
        <m2:Function Type="serviceId:34B1CF4D-1069-4AD6-89B6-E161D79BE4D8"/>
      </m2:Device>
    </m2:DeviceCapability>

After all these are done and dusted, let’s move on with initializing the bluetooth server. The next thing that comes is a StreamSocketListener. And it’s job is kind of explained in it’s name. It will serve as our stream listener that would be recieved from the clients. Thus it has a ConnectionReceived event that has to be populated too.

The next thing to do would be bind the service name. Our StreamSocketListener object has a BindServiceNameAsync method to do so with serviceID and an option to take as a parameter. I defined SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication because I didnt want much security over the communication. You can explore other options if you want to impose some security measures.

Next comes InitializeServiceSdpAttributes(rfcommProvider) and he looks like the following:


        private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider)
        {
            var sdpWriter = new DataWriter();

            // Write the Service Name Attribute.

            sdpWriter.WriteByte(SdpServiceNameAttributeType);

            // The length of the UTF-8 encoded Service Name SDP Attribute.
            sdpWriter.WriteByte((byte)SdpServiceName.Length);

            // The UTF-8 encoded Service Name value.
            sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            sdpWriter.WriteString(SdpServiceName);

            // Set the SDP Attribute on the RFCOMM Service Provider.
            rfcommProvider.SdpRawAttributes.Add(SdpServiceNameAttributeId, sdpWriter.DetachBuffer());   
        }

The purpose of this method is definitely putting the SdpRawAttributes in place by using a DataWriter. Here we put in possibly everything we defined before for our bluetooth device.

The only thing we need to do just before calling StartAdvertising, we need to define our ConnectionReceived event.


private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                socketListener.Dispose();
                socketListener = null;

                socket = args.Socket;

                writer = new DataWriter(socket.OutputStream);

                var reader = new DataReader(socket.InputStream);
                bool remoteDisconnection = false;

                bool res;
                while (true)
                {
                    uint readLength = await reader.LoadAsync(sizeof(uint));
                    if (readLength < sizeof(uint))
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    uint currentLength = reader.ReadUInt32();

                    readLength = await reader.LoadAsync(currentLength);
                    if (readLength < currentLength)
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    string message = reader.ReadString(currentLength);
                }

                reader.DetachStream();
                if (remoteDisconnection)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Disconnect();
                    });
                }

            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

This is where the server keeps looping for message and Im not kidding. You will find a while(true) inside and what it does is it keeps reading data from the socket until someone pulls the trigger or somehow the connection gets jeopardized. You will see even a basic check on buffer length triggers the server to stop. And in any case of an exception an async Disconnect() is due.

And Disconect() is nothing but as simple as the following:


        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            ServerInitiated = false;
        }

Now , we can trigger this one from a toggle button like the following:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (ServerInitiated)
            {
                Disconnect();
                ServerToggleButton.Content = "Initiate Server";
            }
            else
            {
                InitializeRfCommServer();
                ServerToggleButton.Content = "Disconnect Server";
               
            }
        }

But the thing is that’s just a bluetooth server. To test it out you will need a bluetooth client too.

Step 2: The Bluetooth Client

The bluetooth client is essentially a Windows Phone app. I couldve showed the XAML here but that wouldn’t look that simple. In spite of doing that, let’s break down what do we have to do now. We have to:

1. Connect to a paired device. (Yes, you have to have your devices paired)

2. Search the bluetooth service we are looking for and if we find any, we’d give a list to pick

3. Use that selected device and send data to it .

Here, definitely the paired device is a device that has our server running.

Let’s assume we have a run button that starts the search for the paired devices with the desired service. Remember I said that we will need our service GUID and other identifications to make this work even from the client side because it has to know which service it is feeding itself to.

Thus, this definitions first come in place:

private static readonly Guid RfcommChatServiceUuid = Guid.Parse("482af5ed-3faf-4a51-9dd0-718c85aa64d0");

// The Id of the Service Name SDP attribute
private const UInt16 SdpServiceNameAttributeId = 0x100;
private const byte SdpServiceNameAttributeType = (4 << 3) | 5;

private StreamSocket chatSocket;
private DataWriter chatWriter;
private RfcommDeviceService chatService;
private DeviceInformationCollection chatServiceInfoCollection;

and the run method looks like the following:


private StreamSocket chatSocket;
private DataWriter chatWriter;
private RfcommDeviceService chatService;
private DeviceInformationCollection chatServiceInfoCollection;

private async void RunButton_Click(object sender, RoutedEventArgs e)
{
// Find all paired instances of the Rfcomm chat service
chatServiceInfoCollection = await DeviceInformation.FindAllAsync(
RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid)));

if (chatServiceInfoCollection.Count > 0)
{
List<string> items = new List<string>();
foreach (var chatServiceInfo in chatServiceInfoCollection)
{
items.Add(chatServiceInfo.Name);
}
cvs.Source = items;
ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
else
{
Debug.WriteLine("No chat services were found. Please pair with a device that is advertising the chat service.");

}
}

You can definitely understand DeviceInformationCollection does all the hard work here finding the device and the next thing to do would be selecting one and using it. After selecting we will start our chat session and indulge ourselves on a loop so we can keep receiving messages sent from the server, actually in our case thats not necessary, but still it’s nicer to have it on the place.


private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e)
{
try
{
RunButton.IsEnabled = false;
ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex];
chatService = await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id);

if (chatService == null)
{
Debug.WriteLine(
"Access to the device is denied because the application was not granted access",
);
return;
}

var attributes = await chatService.GetSdpRawAttributesAsync();
if (!attributes.ContainsKey(SdpServiceNameAttributeId))
{
Debug.WriteLine(
"The Chat service is not advertising the Service Name attribute (attribute id=0x100). " +
"Please verify that you are running the BluetoothRfcommChat server.",
);
return;
}

var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]);
var attributeType = attributeReader.ReadByte();
if (attributeType != SdpServiceNameAttributeType)
{
Debug.WriteLine(
"The Chat service is using an unexpected format for the Service Name attribute. " +
"Please verify that you are running the BluetoothRfcommChat server.",);
return;
}

var serviceNameLength = attributeReader.ReadByte();

// The Service Name attribute requires UTF-8 encoding.
attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8;
ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\"";

lock (this)
{
chatSocket = new StreamSocket();
}

await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName);

chatWriter = new DataWriter(chatSocket.OutputStream);
ControlBox.Visibility = Visibility.Visible;

DataReader chatReader = new DataReader(chatSocket.InputStream);
ReceiveStringLoop(chatReader);
}
catch (Exception ex)
{
RunButton.IsEnabled = true;
Debug.WriteLine("Error: " + ex.HResult.ToString() + " - " + ex.Message,);
}
}

The very basic thing it does it starts getting device info out and creates a String Loop that listens for a string. I wont go with that details rather I’d show how to send a bluetooth data through it.


private async void SendMessage(string message)
{
try
{
chatWriter.WriteUInt32((uint)message.Length);
chatWriter.WriteString(message);

await chatWriter.StoreAsync();

}
catch (Exception ex)
{
//MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message,
//    NotifyType.StatusMessage);
}
}

For the first part I’d stop here now, in the next two parts we are going to see how we are going to feed this data to vjoy and use our phone as a game controller. ūüôā

Making a quick rating user control for Windows Phone 8.1

First Words

Usually when someone is working on Windows Phone 8.1 and usually if he’s the guy who just came from Windows Phone 8 development, the first thing he misses is all the toolkits lying around like the Windows Phone Toolkit or Coding4Fun Toolkits. Thus, missing a rating control is not new. So, let’s get our hands dirty and make a little 5 starred rating control fast enough to solve our problem at least to a minimum extent.

Design First!

Okay, to do this thing fast, we might need to make at least a little bit of groundwork in design, I’m going to use Microsoft Expression Design for it. You guys can get the free version from here. It’s pretty lightweight and we can practically export stuff straight to Blend for Visual Studio!

So, let’s go over Microsoft Expression Blend and create a new document. Take a size to your preference as you need it. Let’s draw some stars! To get started, look on the left toolbar and select Polygons.

1

After you select polygons, drag your mouse pointer in the artboard to draw anything that pops off. Now, it might be any kind of polygon, starting from a triangle, like the following came up with too much of points.

2

To rectify this, we need to make sure it has 5 points and an inner depth above 40% and close to 50% so it looks like a star, you can modify the existing one you made or set the proper settings and make a new one. To do that, look on the right on Edit Polygon dialog and change the points to 5 and move the innder depth to 47%. If you want to create a new one you will see the dialog name is Create Polygon. You can go for anything in between 45% tp 50%, I used 47% in this case.

3 4

 

 

Now, with the proper settings set with the polygon give it a yellowish shade and no borders please. And copy the stars and set them side by side so you can have 5 stars in a line that resembles a regular rating control. So, in the artboard it might look pretty close to the one following:

5

Now, what we want to do is put these together on a gradient so it resembles more to the rating control. But before we go do that, we need to make the stars act as a compound path together. So, lets go ahead and select all of them and select Object -> Compound Path -> Make so all the stars can work as a compound path.

6

Now, it’s time to put a gradient over it. Select a yellow to white gradient and put it on your rating control from left to right. Now, there comes a trick, at first you will see the color melted down in the middle, in a rating control we need a clear difference of color to make sure that it looks like one.

7

Now, click on the gradient bar in the middle to put a gradient stop in there.

8

Now, drag the midpoints (the dots over the gradient bar) and put them together to make the color difference more prominent.

9

Now, if we move the Gradient Stop now, we will see the color changes are more prominent and the starts look a lot like rating control now.

10

Now let’s go over Visual Studio and create a Windows Phone 8.1 Project. Let’s put a Right Click on the solution name and add a user control.

11

12

Now, lets select the user control and open it on blend. Let’s select all the stars, copy it and just paste it on the grid of the user control. To your surprise, this thing will just get copied to blend just fine. And let’s make the height of the user control to 40 and the width to 200 just to get the user control to appropriate proportion. I copied a set of stars and put the background to a very light gray color and put it behind the ones we copied at first so it looks a bit more prominent even in a white background.

13

Now, the xaml for the usercontrol will look somewhat like the following:

<UserControl
    x:Class="RatingControlTest.usercontrol"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
 
    d:DesignHeight="40"
    d:DesignWidth="200">

    <Grid>
        <Path Stretch="Fill"
              Data="M -1346.6,-259.247L -1358.76,-305.451L -1321.61,-335.489L -1369.31,-338.197L -1386.39,-382.816L -1403.71,-338.285L -1451.43,-335.823L -1414.43,-305.594L -1426.83,-259.454L -1386.65,-285.302L -1346.6,-259.247 Z M -1067.9,-259.247L -1080.07,-305.451L -1042.91,-335.489L -1090.61,-338.197L -1107.7,-382.816L -1125.01,-338.285L -1172.73,-335.823L -1135.73,-305.594L -1148.13,-259.453L -1107.95,-285.301L -1067.9,-259.247 Z M -1207.25,-259.247L -1219.41,-305.451L -1182.26,-335.489L -1229.96,-338.197L -1247.05,-382.816L -1264.36,-338.285L -1312.08,-335.823L -1275.08,-305.594L -1287.48,-259.453L -1247.3,-285.301L -1207.25,-259.247 Z M -928.552,-259.247L -940.718,-305.451L -903.562,-335.489L -951.264,-338.197L -968.35,-382.816L -985.666,-338.285L -1033.38,-335.823L -996.382,-305.594L -1008.79,-259.453L -968.602,-285.301L -928.552,-259.247 Z M -789.204,-259.247L -801.369,-305.451L -764.214,-335.489L -811.916,-338.197L -829.002,-382.816L -846.318,-338.285L -894.034,-335.823L -857.033,-305.594L -869.437,-259.453L -829.254,-285.301L -789.204,-259.247 Z "  
              UseLayoutRounding="False"
              HorizontalAlignment="Left"
              VerticalAlignment="Top"
              Height="Auto" Width="Auto" Fill="#FFDEDEDE"/>
        <Path Stretch="Fill"
              Data="M -1346.6,-259.247L -1358.76,-305.451L -1321.61,-335.489L -1369.31,-338.197L -1386.39,-382.816L -1403.71,-338.285L -1451.43,-335.823L -1414.43,-305.594L -1426.83,-259.454L -1386.65,-285.302L -1346.6,-259.247 Z M -1067.9,-259.247L -1080.07,-305.451L -1042.91,-335.489L -1090.61,-338.197L -1107.7,-382.816L -1125.01,-338.285L -1172.73,-335.823L -1135.73,-305.594L -1148.13,-259.453L -1107.95,-285.301L -1067.9,-259.247 Z M -1207.25,-259.247L -1219.41,-305.451L -1182.26,-335.489L -1229.96,-338.197L -1247.05,-382.816L -1264.36,-338.285L -1312.08,-335.823L -1275.08,-305.594L -1287.48,-259.453L -1247.3,-285.301L -1207.25,-259.247 Z M -928.552,-259.247L -940.718,-305.451L -903.562,-335.489L -951.264,-338.197L -968.35,-382.816L -985.666,-338.285L -1033.38,-335.823L -996.382,-305.594L -1008.79,-259.453L -968.602,-285.301L -928.552,-259.247 Z M -789.204,-259.247L -801.369,-305.451L -764.214,-335.489L -811.916,-338.197L -829.002,-382.816L -846.318,-338.285L -894.034,-335.823L -857.033,-305.594L -869.437,-259.453L -829.254,-285.301L -789.204,-259.247 Z "  
              UseLayoutRounding="False"
              HorizontalAlignment="Left"
              VerticalAlignment="Top"
              Height="Auto" Width="Auto">
            <Path.Fill>
                <LinearGradientBrush StartPoint="3.55262e-007,0.500002" EndPoint="1,0.500001">
                    <GradientStop Color="#FFFFCC00" Offset="0.6"/>
                    <GradientStop Color="#06FCFCFC" Offset="0.6"/>
                </LinearGradientBrush>
            </Path.Fill>
        </Path>

    </Grid>
</UserControl>

Code Comes Along

Now if we remember stuff clearly, when we moved the gradient stop in blend it looked like the rating bar value is changing. We just need to emulate that in code, that’s it. So, all we need to is change the Offset of <GradientStop> ‘s in LinearGradientBrush entry inside <Path.Fill>. So, we have to databind the offset from backend so we can access it from the usercontrol. And please remember this have to be 0.0 to 1 of course as thats the range for the offset value.

I renamed my user control to RatingControl and let’s move back to the code backend of RatingControl.xaml

public partial class RatingControl : UserControl
    {
        public RatingControl()
        {
            this.InitializeComponent();
        }

        DependencyProperty RateValueProperty = DependencyProperty.Register("RateValue", typeof(double), typeof(RatingControl), new PropertyMetadata(0.1, UpdateValue));

        private static void UpdateValue(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            RatingControl control = d as RatingControl;
            control.Value = (double)e.NewValue;
        }

        private double Value
        {
            get { return (double)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        private static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(double), typeof(RatingControl), new PropertyMetadata(0.1));

        public double RateValue
        {
            get
            {
                return (double)GetValue(RateValueProperty);
            }
            set
            {
                SetValue(RateValueProperty, value);
            }
        }

    }

Now, our job was to hook up the Value provided from backend. Now I used two DependencyProperty here instead of one because we are going to attach the value in the xaml using a element binding. The first DependencyProperty RateValueProperty has a PropertyMetadata of 0.1 and a function is attached to update the value in the xaml control (update the offset from the xaml).

And Value is the actual DependencyProperty Attached to the control and as it’s private it’s accessible only from inside. So we are exposing it using the RateValueProperty and update it with the Value Dependency Property. You can only use Value and expose it if you want.

Now all we have to do is hook it up in the xaml:

Let’s add a name to the Rating Control. Lets just add x:Name=”UserControl” in the UserControl Tag. And let’s tag the GradientStop property Offset on the ElementName “UserControl”. So, let’s modify the GradientStop tags as following:

<Path.Fill>
     <LinearGradientBrush StartPoint="3.55262e-007,0.500002" EndPoint="1,0.500001">
          <GradientStop Color="#FFFFCC00" Offset="{Binding Value, ElementName=UserControl}"/>
          <GradientStop Color="#06FCFCFC" Offset="{Binding Value, ElementName=UserControl}"/>
      </LinearGradientBrush>
</Path.Fill>

And voila! We are done!

Using the control

Using the control is pretty easy, add xmlns:local=”using:RatingControlTest” in the page tag and use it just like the following:

<Page
    x:Class="RatingControlTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:RatingControlTest"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <local:RatingControl Width="200" Height="40" RateValue="0.5"></local:RatingControl>
    </Grid>
</Page>

And it will look like the following:

14

Demo Project:

The demo project is here so you can test it yourself. Hope this helps! ūüėČ

Using SQLite as local database with Universal Apps

The First Words

Usually when we are moving our existing Windows Phone 8 / Windows Phone Silverlight projects to Universal Apps, in most of the cases the common question that rises up is what should we use as a local database on it. And SQLite does a perfect job serving the universal apps a perfect local database. So, please keep your eyes posted here if you want to use the same database for both your projects in your universal app. So, why not get started?

Universal Apps

Univeresal Apps are the newest App Models designed for Windows Store to serve Apps in Windows Store and Windows Phone Store from a same project with shared codes as per your liking. To the ones who doesn’t know what an Uinversal App is, kindly visit this link so you can get a full idea how it works. To the ones who already know this, please continue.

SQLite With Universal App

To get SQLite going with your universal app, the first thing we should do is get SQLite for both Windows Phone 8.1 and Windows Runtime 8.1as Universal App points to both of the apps.

To install SQLite for Windows Store please visit:

http://visualstudiogallery.msdn.microsoft.com/1d04f82f-2fe9-4727-a2f9-a2db127ddc9a/view/

And you will stumble upon a screen like the following:
1

So, definitely the next thing to do is download this one, as soon as the VSIX installer is downloaded, install it. As, now we have SQLite for Windows Store here, let’s move so we can have SQLite for Windows Phone.

To install SQLite for Windows Phone 8.1 please visit:

http://visualstudiogallery.msdn.microsoft.com/5d97faf6-39e3-4048-a0bc-adde2af75d1b

This will lead to a similiar page, download the VSIX installer and install it too. The next thing we should check for whether we have installed what we need in our Visual Studio. I’m using a Visual Studio 2013 Ultimate version here and let’s go over Tools -> Extensions and Updates and go to the “SDK” section after under “Installed”. You will stumble upon SQLite for Windows Runtime and SQLite for Windows Phone 8.1 is listed as installed in your pc.

2

As now we are pretty sure that we have SQLite for Windows Phone 8.1 and Windows Store Apps, let’s create a new Universal App Project in Visual Studio.

SQLite With Universal App

Creating Univresal Apps are pretty same like other projects in Visual Studio. Just go over File->New Project and under Store Apps, let’s create a blank Universal App named UniversalSQLite.

3

In the Solution Explorer, you will see your projects divided into Windows Store, Windows Phone and Shared. Our job now is to reference SQLite into both Windows Store and Windows Phone projects so both of the projects has access to SQLite. In Windows 8.1 Solution, go over your references and add reference to the newly added SQLite libraries under extensions.

4

And do the same with Windows Phone 8.1 solution too. Go over references and add reference to the newly installed SQLite for Windows Phone 8.1 Libraries.

5
You will see some yellow excalamtion signs over the newly referenced libraries and the best thing to do right now is to build this. The first problem you are bound to see when you build is this:

6

Actually the problem says the solution itself. As these native libraries are extremely machine dependent the best thing to do here would be just go over configuration manager and set x86 as Platform for both projects.

7 8

Trying out x64 ended up XAML designer not rendering UI. So x86 is the safe choice. Don’t worry,¬† this will not prevent you to create the different platform version to be deployed on the store.

When you are ready just use the ‚ÄúCreate App Packages” command. The best way to get that would be right clicking on the solution name and move over to store menu. But that’s later.

9

Get sqlite-net from Nuget

Well, if you put a build now, you will see everything has smoothed out. Now, what’d left is using SQLite. The first thing we need is a nuget package to cover all the internal¬†intricacies we have on SQLite, thus comes in help sqlite-net¬† . This little nuget package is extremely handy and all you need to do to use this is to go over references and manage nuget packages. Search for sqlite-net and add it when the search results pop up.

10

This has to be done for both the Windows 8.1 and Windows Phone 8.1 projects of course as we intend to use this for both of them. You will see two classes named SQLite.cs and SQLiteAsync.cs is created into both of the projects. Just to remove duplicacies we can move them to shared project under a folder if you like.

11

Let’s get our hands dirty

So, lets get busy with some code, shall we?

Creating/Opening A Database:

To create/open a database all you have to do is someting like the following. This will actually create a database if it’s non existing or open connection to one if it’s existing.

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);

So, before doing that you might want to check whether the database exists or not.

public async Task&amp;lt;bool&amp;gt; DoesDbExist(string DatabaseName)
{
      bool dbexist = true;
      try
      {
         StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(DatabaseName);

      }
      catch
      {
         dbexist = false;
      }

      return dbexist;
}

The reason we are looking at ApplicationData.Current.LocalFolder is sqlite-net creates database by default in that place.

Creating/Opening A Database:

Before creating a table you need to have a model to define a row on that specific table. The model might look like the following:

using SQLite;


namespace UniversalSqlLite.Model
{
    [Table(&quot;Students&quot;)]
    public class Student
    {
        [PrimaryKey, AutoIncrement]
        public int id { get; set; }

        public string Name { get; set; }

        public string EnrolledCourse { get; set; }

    }
}

Now you can just go ahead an create a Table as per your wish.

public async void CreateDatabase()
{
   SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
   await connection.CreateTableAsync&amp;lt;Student&amp;gt;();
}

CreateTableAsync will create the table if it’s not there. And it will update the table description if the Model is changed in any way than the previous one. As far now, it only supports column addition. It will not destroy any existing SQLite Table. So, you don’t have to worry about redoing this with an existing table.

If you look closely, you can see that you can adore the classes and the properties in the model with attributes defined in sqllite-net library. It’s almost the same you might see in Entitiy Framework.

The full list is to be found here:

Class attribute:

  • [Table(Name)]

Property attributes:

  • [AutoIncrement]
  • [PrimaryKey]
  • [Column(Name)]
  • [Indexed] | [Indexed(string name, int order)]
  • [Unique]
  • [Ignore]
  • [MaxLength(int length)]
  • [Collation(string name)]
  • [NotNull]

Dropping a Table:

Dropping table is a piece of cake too:

public async void DropDatabase()
{
    SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
    await connection.DropTableAsync&amp;lt;Student&amp;gt;();
}

Adding Records in the Table:

Inserting into SQLite is easy as the following:

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
var Student=new Student()
{
   Name=&quot;Swagata Prateek&quot;,
   EnrolledCourse=&quot;CSE 4203&quot;
};
await connection.InsertAsync(Student);

And if you feel like inserting a lot of stuff at a time why not using a list?

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);

var StudentList = new List&amp;lt;Student&amp;gt;()
{
    new Student()
    {
        Name=&quot;Swagata Prateek&quot;,
        EnrolledCourse=&quot;CSE 4203&quot;
        },
        new Student()
        {
            Name=&quot;Abidur Rahman&quot;,
            EnrolledCourse=&quot;CSE 4203&quot;
        },
        new Student()
        {
            Name=&quot;Ashiqur Rahman&quot;,
            EnrolledCourse=&quot;CSE 4203&quot;
        }
    };
            
await connection.InsertAllAsync(StudentList);

Pursue a Query

You can go for a Query in SQLite in quiet a number of ways. Let’s check out if we want to do it using LINQ, how would it be:

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
var queryVar=await connection.Table&amp;lt;Student&amp;gt;().Where(x=&amp;gt;x.Name.StartsWith(&quot;Swagata&quot;));

var queryResult = await queryVar.ToListAsync();
foreach (var item in queryResult)
{
    //Do your stuff
}

You can even do a manual SQL query if you feel like that:

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
var result = await connection.QueryAsync&amp;lt;Student&amp;gt;(&quot;Select Name FROM Students WHERE EnrolledCourse = ?&quot;, new object[] { &quot;CSE 4203&quot;});
foreach (var item in result)
{
    //Do your stuff
}

Update and Delete a Record

Any record can be updated as soon as it’s retrieved and updated back into the table.

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
var Student=await connection.Table&amp;lt;Student&amp;gt;().Where(x=&amp;gt;x.Name.StartsWith(&quot;Swagata&quot;)).FirstOrDefaultAsync();

if(Student != null)
{
    Student.EnrolledCourse = &quot;CSE 4503&quot;;
    await connection.UpdateAsync(Student);
}

If you want to delete the same record all you have to do is:

SQLiteAsyncConnection connection = new SQLiteAsyncConnection(&quot;Student.db&quot;);
var Student=await connection.Table&amp;lt;Student&amp;gt;().Where(x=&amp;gt;x.Name.StartsWith(&quot;Swagata&quot;)).FirstOrDefaultAsync();

if(Student != null)
{
    await connection.DeleteAsync(Student);
}

Summing up

We are going to take a little deep dive on the queries and make a sample app out of it in the next post. Meanwhile you can even go through Nicol√≤ Carandini’s blog on SQLite with Universal app on the following links.

  1. Universal App With Sqlite Part -1
  2. Universal App With Sqlite Part -2

Hope you guys had fun!

Bus Map Dhaka – What can be next and how it can be done

Usually I talk about pretty current stuffs, let’s talk future now. And the future is needed to be talked now. Because after some days in this young app industry simple rss readers won’t be considered a quality app anymore. If you look around, Windows Phone in Bangladesh has walked a pretty silent but significant path. And I’m quiet happy that I walked a little too.

I hope the one who is reading this do know Bus Map Dhaka for Windows Phone. If you dont know, the following is the link: http://www.windowsphone.com/en-bd/store/app/bus-map-dhaka/3795f088-028a-4958-bea6-a2d0eb243bd

Now, let’s start talking how this was made. When I started doing this, the first thing that came into my mind is the actual scenario of Dhaka, if you really expect a local bus to come in the very right time exactly every day,¬† I guess you have optimism as your profession. So, along with finding the best route and other basic operations, I had to believe someday I would face the challenge which will “actually” solve the problem.

Traffic jams are usually one of the common phenomena here, very common as in like brushing your teeth everyday. If it’s not there, you get surprised. But it’s not the only thing that can keep you getting on the right bus. There’s bad road situations, there’s bus shortage, possibly anything that you can’t predict or manage.

I thought big big plans, like putting devices on buses and tracking down each one of them. But think once, just once. When nobody is even curious about putting proper fitness checks on a bus, maintaining  a device would be a overkill for them, and of course will lead my dream service to perish.

What I had it mind was a pretty simple one. If you ever heard of Ant Colony Optimization, I believe in case of Dhaka, it would come to a greater use . Because the shortest path is not always the “right path”.

If you want to know about ant colony optimization algorithm do a wiki read here:
http://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms#Ant_Colony_System

I wanted to follow the traditional Ant Colony Optimization trait here. Let’s put a small city like Dhaka with us like below:

1

Pretty simple for Dhaka, eh? ūüėÄ Let’s keep it simple for understanding. You will see Node D is kind of the hub of the city, much like our motijheel, mohakhali or other big bus junctions, right? Now, in this city there can be a number of buses, right? Essentially a Bus Route is nothing but a number of these nodes ordered by bus stops.

Let’s make some bus routes, shall we?
1. A-C-E

2. C-D-E-B-A

3. D-E-C-A

For simplicity lets assume all these bus goes and comes back in the same order. Now, I know what you guys are thinking, if I put “distance metrics” on these paths, it’s easy to find a suitable bus route. Like, if you want to take A trip from A to D you can chose bus number 2 or 3. Question is which one should you pick? What if there is more traffic jam in B-E junction and less in C-E? These data changes over time, even in fraction of ten minutes.¬† You can’t possibly decide every time.

Here ant colony comes so handy. The very basics of Ant Colony Optimization is based on how ants find best paths. In the natural world, ants  wander randomly and after finding food return to their colony while they continuously lay down pheromone trails. If other ants find such a path, they are likely not to keep traveling at random, but to instead follow the trail, returning and reinforcing it if they eventually find food. So, the fact is who knows the best path right now, the bus that just has gone to that path a few minutes ago. Just like the ant. The only deficit we have here is pheromone trail left by ants. Now, remember what we have in hand. We cant put too much on a local bus as they wont take care of it properly.

But what about known bus counters? If we manage to find only time-stamps of a bus arriving at a bus-stoppage somehow, we don’t need to know which one came, just spotting one on a counter, much like spotting an ant on a node. ¬† And based on the frequency of that timestamp, you can actually verify the frequency of buses coming down there. If the adjacent roads are not doing well with traffic jams, you are bound to have a lesser frequency and if it’s smooth sailing you will have a solid frequency. Even if that sounds awkward we can even track ticket sales, although that would be far off, still a usable heuristic metric to understand whether people are actually getting up on a bus or not.

Now, based on that. We want to go to D from A.

We have two bus routes, 2 and 3. Now which to pick? All we have to do is check the pheromone/our very own heuristic cost metric trails and the route that currently has a more favorable reinforcement/feedback. No matter what comes in the road, traffic jams or stuff, within minutes, these would be updated. And as the buses are continuously traveling, the metric will always be updated. And further more, you can even predict a possible next bus time from this too. Or predict a best possible route to go from one place to another on a car. I know, for Dhaka, it might be a bit long shot, still…worth a try.

So, if you believe every bus is a ant running on a direction (although these are defined rather than random). Actually that makes us one step closer to goal. Because logically ant colony optimization finds a best path. As our possible paths are already defined, we don’t have to go through the first state.

There should be usually two steps of ant colony optimization:
1. Edge selection
2. Pheromone Update

As our paths are already defined, edge selection is basically finding eligible bus routes to go from one place to another, it could be a multiple bus journey but I will write about that later.

procedure BMD_Heuristic
    while(not_termination)
       TraverseRoutes()
       RouteActions()
       UpdateMetrics()
    end while
  end procedure

Let me know what you guys think of it and how can you help NerdCats take it to the next level. See ya!

Windows Phone micro UI hacks – simple drop shadows

Well, I was pretty upset when they took off effects support from silverlight, I really was. It was something I really loved thus I could’ve added a little bit of depth in design. I get the idea that it might help improving performance of UI rendering in a device.

So, I was trying out some little hacks, or you might say some faulty impersonations of making a drop shadow, so far I’m not close to that “quality” but I did try.

Let’s assume you want to put a rectangle with a drop shadow. Effectively if you break down a drop shadow you will find a black to grey gradient alpha mask of your rectangle, in easy words, nothing but a blurry grey scale representation of your rectangle lying back. Now, that’s what I tried out here. I took a rectangle, copied it behind it and kept it with a black and grey shades. I could’ve used just one gradient gray shaded rectangle but it doesn’t look that good.

Now, let’s see how that looks.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Rectangle x:Name="tb1" Fill="Black" Opacity="0.2" Margin="1,3,0,0"  Height="{Binding Height, ElementName=tb5}" Width="{Binding Width, ElementName=tb5}"/>
            <Rectangle x:Name="tb2" Fill="Black" Opacity="0.2" Margin="-1,3,0,0"  Height="{Binding Height, ElementName=tb5}" Width="{Binding Width, ElementName=tb5}"/>
            <Rectangle x:Name="tb3" Fill="Black" Opacity="0.4" Margin="0,2,0,0"  Height="{Binding Height, ElementName=tb5}" Width="{Binding Width, ElementName=tb5}"/>
            <Rectangle  x:Name="tb4" Fill="Black" Opacity="0.2" Margin="0,3,0,0" Height="{Binding Height, ElementName=tb5}" Width="{Binding Width, ElementName=tb5}"  />
            <Rectangle Width="250" Height="100" x:Name="tb5" Fill="#FFE63939"  />
</Grid>

This is a very basic try of course. I’m going to make a usercontrol out of it somehow. And if I do, you will find it right here on my blog and looks like somehow I have to fake the blur too.

Well, until next time then. And by the way, it looks like below on the screen:
Rectangle Drop Shadow test