Windows Phones For Newbies – Tracking location in Windows Phone 8.1

Windows Phone 8.1 comes with a lot of prospects in the geo location end and usually the next thing after detecting your very own location, people tends to look for one another thing and that is tracking the location as it should update itself. So, if you’re wondering about how you should instantiate a map and track your location, you really should check out my previous post .

And if you have already done that (I hope you liked it). Then you’d probably know how to do the following:

  1. Please go ahead to your visual studio (Im using a Visual Studio 2013 Community Edition)  and open a new project on Blank App on Windows Phone 8.1
  2. Go over your project properties and go over Capabilities. Enable Location for your app (If you are from Windows Phone 8, you’d be pretty amazed that you don’t see ID_CAP_MAP anymore.

 

A Basic UI:

Let’s set up a basic UI and yes It’s kind of a rip off from MSDN but as long as it helps people, it’s cool. Our little UI has two Buttons and a number of textblocks and it looks like below in XAML (I’m only posting the main grid):


<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>

<Grid>
<TextBlock Text="Location Tracker" Margin=" 15" FontSize="45"></TextBlock>
</Grid>

<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="Track Location" Click="TrackLocationButton_Click"
HorizontalAlignment="Center" x:Name="TrackLocationButton"
VerticalAlignment="Bottom" />

<Button IsEnabled="False" Grid.Column="1" Content="Stop Tracking" Click="StoptrackingButton_Click"
HorizontalAlignment="Center"  x:Name="StoptrackingButton"
VerticalAlignment="Bottom" />
</Grid>

<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3.5*"></ColumnDefinition>
<ColumnDefinition Width="7*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel Margin="10">
<TextBlock Text="Latitude"  FontSize="23" />
<TextBlock  Text="Longitude"  FontSize="23" />
<TextBlock  Text="Accuracy"  FontSize="23" />
</StackPanel>
<StackPanel Margin="10" Grid.Column="1">
<TextBlock  Name="LatitudeText" FontSize="23" />
<TextBlock   Name="LongitudeText" FontSize="23" />
<TextBlock   Name="AccuracyText" FontSize="23" />
</StackPanel>
</Grid>

</Grid>

If that seems a bit too much xaml for you then calm down because It looks extremely basic too:

Tracking - 1

Now, let’s move towards the MainPage.xaml.cs part. As the previous article suggests, the first thing you need is definitely a Geolocator . So please go ahead and define a Geolocator instance.


private Geolocator locator = null;

Now that we have a geo locator we can move ahead and go over the Properties of TrackLocationButton and create the method stub for Click event. And the event handler looks like below:


private void TrackLocationButton_Click(object sender, RoutedEventArgs e)
        {
            if (locator == null)
            {
                locator = new Geolocator();
            }
            if (locator != null)
            {
                locator.MovementThreshold = 3;

                locator.PositionChanged +=
                    new TypedEventHandler<Geolocator,
                        PositionChangedEventArgs>(locator_PositionChanged);

                
            }

            TrackLocationButton.IsEnabled = false;
            StoptrackingButton.IsEnabled = true;

        }

Now, if you dive a little bit into that, you will see that if the locator is instantiated then the first property we do change is the MovementThreshold property. It is the property that defines the movement threshold for the geo tracking to notify you. It’s defined in meters and thus we have defined it to 3 meters. Now next question that comes along is how would I know that I have moved my MovementThreshold amount of distance. The common answer would be actually invoking a PositionChanged event and attach a handler to it. And the handler locator_PositionChanged looks like below:


async private void locator_PositionChanged(Geolocator sender, PositionChangedEventArgs e)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Geoposition geoPosition = e.Position;
LatitudeText.Text = geoPosition.Coordinate.Point.Position.Latitude.ToString();
LongitudeText.Text = geoPosition.Coordinate.Point.Position.Longitude.ToString();
AccuracyText.Text = geoPosition.Coordinate.Accuracy.ToString();
});
}

Now even before describing whats being done here you might wonder where the dispatcher comes from, truth is it has been declared before as:


private Geolocator locator = null;
private CoreDispatcher dispatcher;

public MainPage()
{
this.InitializeComponent();
dispatcher = Window.Current.CoreWindow.Dispatcher;
}

The reason we are using that would be pretty clear if we look at what are we doing. We are constantly updating our LatitudeText, LongitudeText, AccuracyText and as we are accessing a UI thread frequently from a event handler, we do need to make it sure it doesn’t block the regular UI interactions. Thus we used a CoreDispatcher here, much like it was in Windows Phone 8 as Dispatcher. You’d also be able to notice that the event handler is async and thus dispatcher.RunAsync invocation was awaited. We used CoreDispatcherPriority.Normal and you can even try a higher priority if you like. All this event handler is doing is it is actually updating the UI and the textblocks.

Now all you need is a StoptrackingButton to get things to stop and all you have to do is unhook the locator_PositionChanged event handler.


private void StoptrackingButton_Click(object sender, RoutedEventArgs e)
{
if (locator != null)
{
locator.PositionChanged -= new TypedEventHandler<Geolocator, PositionChangedEventArgs>(locator_PositionChanged);
}

StoptrackingButton.IsEnabled = false;
TrackLocationButton.IsEnabled = true;
}

Debugging it on the emulator:

As this sample has geolocator usage, this is always better to be tested in a device but you can definitely try it on an emulator too. To test it load the app on the emulator first by invoking build.

Tracking - 2

When the emulator hooks up open up the emulator tools and go to the location tab and click on the map to give you a primary location first. You can have a look at the gif below for an idea

Tracking - 3

Now after you pointed a primary location in the map. Now you can try clicking the track location button. After you do that Latitude, Longitude and Accuracy would pop up for the place you clicked on the map. Now click some more around it. And you will see the data changes on the textblocks.  You can do one thing more too. You can change the interaction mode from Live to Pin and play all the pins. That would even allow to emulate place changes in your emulator.  The following gif would definitely help you.

Tracking - 4

And the code sample is here.

Stay Frosty!

 

 

Different Operators in C#

In this article we will discuss about common operators that used in C#. Like any other programming languages C# has also some common operators. We can divide those as the following –
• Assignment Operator (=)
• Arithmetic Operators (+,-,*,/,%)
• Comparison Operators (==,!=,>,>=,<,<=)
• Conditional Operators (&&,||)
• Ternary Operator (?:)
• Null Coalescing Operator (??)
Now we will discuss about each of this operator in details.

Assignment Operator (=)

This is a very common operator in every programming language. It is used to assign a value in a variable. We can give a variable a value by this operator. Suppose we declare a variable by the following instruction-

Int variable_name;

Then this variable reserve some memory in RAM but no value is saved in those memory. We can assign value to those memory by using assignment operator as follows-

Int variable_name=5;

Now the value 5 is reserved in those memory blocks. So assignment operator is used to assign values.

Arithmetic Operators (+,-,*,/,%)

These operators are used to perform arithmetic operation. In many places of a program we need to perform many arithmetic operation. So it is important to understand these operators closely.
The “+” operator performs addition operation. Suppose we want to add two values. Then we can do that by the following-

Int a = 5+4;
Or,
Int a=5;
Int b=6;
Int result= a+b;

The “+” operator takes two operands and return the result of addition between those operands. Similarly “-” operator performs the subtraction operation between two operands. It will subtract its right side operand from left side operand and return the result. The multiplication operator is “*”. It will perform multiplication operation.
Now the two operator / and % is related to division operation. The forward slash (/) operator returns the quotient of the division operation and “%” (read as MOD) operator returns the reminder. To understand the difference we consider a division operation. Suppose we want to divide 10 by 2. So here the Quotient will be 5 and reminder will be 0. If we use / operator then it will return 5 and if we use % then it will return 0. Consider the following program-

using System;
class Program
{
   static void Main()
    {
        int Numerator = 10;
        int Denominator = 2;

        int result = Numerator / Denominator;

        Console.WriteLine("{0}", result);
    }
}

The above program will print 5 because here we use / operator and it will return quotient. If we used % in place of / then it will print the reminder that is 0 here.

Comparison Operators (==,!=,>,>=,<,<=)

Comparison operators are used to compare to value and always return true or false. Every comparison operator has a meaning and performs a specific compare operation. The best example of this operator is in conditional statement. The statement in which we compare something in respect with some condition is called conditional statement. There are some keywords that used in conditional statement, one of this is “if” keyword. It is very common in almost all programming languages.
The double equal sign is used to compare equality. Consider the following example-

using System;
class Program
{
   static void Main()
    {
        int a = 10;
       if(a==10)
       {
           Console.WriteLine("{0}", a);
       }
        
    }
} 

In the above example we compare the value of variable with 10. If the value of variable a is equal to 10 then the next instruction will execute. The next instruction is to print the value of ‘a’ that is 10 here. So the program will print 10.
The “!=” operator is used to check inequality. For example in the above example we can check the variable ‘a’ is not equal or not. If we want to execute another instruction if the variable is not equal to 10 then code should be as follows-

using System;
class Program
{
   static void Main()
    {
        int a = 5;
       if(a==10)
       {
           Console.WriteLine("{0}", a);
       }
       if(a!=10)
       {
           Console.WriteLine("a is not equal to 10");
       }
    }
}

The above program will print “a is not equal to 10” because the value of a is 5 here. The != operator used here to execute the meaningful string that user can understand specifically that a is not equal to 10.
Similarly we can check greater than relation by the “>” operator. It will return true if the right side operand is greater than the left side operand. If we want to check greater or equal relation then we can use >= operator. It will return true if the left side operand is greater than right side operand and also if the operands are equal to each other.
Like greater than relation we can check less than relation by “<” operator and less than or equal relation by “<=” operator.

Conditional Operators (&&,||)

There are two operators that used in conditional statements named as AND (&&) and OR (||). If there is any situation where we need to execute a statement if and only if some of conditions are true then we can use && operator. This operator takes two condition and execute next instructions if all of those conditions are true. Suppose we have to check if a number is less than 5 and greater than 1 or not then we can check it by && operator as following-

using System;
class Program
{
   static void Main()
    {
        int a=2;
        
       if(a1 )
       {
           Console.WriteLine("a is less than 5 and greater than 1");
       }
        
    }
}

In the above example two conditions is checked, one is a is less than 5 and the other is a is greater than 1. So the print instruction will be executed if each of these instruction are true. Another operator is || (OR) this operator used as the same of && operator but if any one of the condition is true between two then the next instruction will execute. The OR operator return true if any one of the condition is true. In the above example if we used OR operator then weather the value of a is less than 5 or greater than 1 the print instruction will execute.

 
using System;
class Program
{
   static void Main()
    {
        int a=10;
        
       if(a1 )
       {
           Console.WriteLine("a is less than 5 OR greater than 1");
       }
        
    }
}

In the above example the condition a is less than 5 is false but a is greater than 1 true, so one of the condition is true. That’s why the print instruction will execute.

Ternary Operator (?:)

The ternary operator is a very interesting operator. It gives us two options if any condition is true than do something otherwise do something. The syntax of ternary operator can be written as follows-
Any Condition ? do if the condition is true : do if condition is false
We can see it by the following code-

using System;
class Program
{
   static void Main()
    {
        int a=10;
        bool ISValue10 = a == 10 ? true : false;

        Console.WriteLine("{0}", ISValue10);
        
    }
}

In the above example the condition is if the variable “a” is equal to 10 or not. If it is true then the bool type variable “ISValue10” will be assigned by true otherwise false. Here the example will print true because here the value of variable is 10. We can do the same by if statement but it will take more instruction that we have done here with one instruction. That is the benefit of using ternary operator.

Null Coalescing Operator (??)

To understand null coalescing operator first we have to understand nullable types in C#. Actually we can divide the types in C# in two broad categories-
• Value types
• Reference types
In the previous article we have already seen the value types and those are- integer, double, float, decimal etc. We have also seen a reference type that is string type. String is actually a class. We will discuss about reference types and value types in details in the later session. What we need to understand at this point is types in C# can be divided in two broad categories that is value type and reference type. Example of value type is integer, float, double, structs, enums and example of reference type is interface, delegates, arrays, class etc. And another point we need to keep in mind at this point is the default value of a reference type is null and the default value for value type is some form of zero. For example the default value of type integer is zero and it cannot hold the value null. To assign null in a variable we use the keyword null in C#. If we try to assign null to a integer type variable then we will get an error. So value type cannot hold null value. But as I told before that string is a class that is reference type so we can assign a string variable with null. For an example we can write-

 
string s = null;

but we cannot write-

int a = null; 

If we try to assign null to a integer type variable then it will return an immediate error. Sometimes it is necessary to assign a value types variable with the value null. Generally it is necessary if we use C# to communicate with a database. Since nullable types and non-nullable types is not a concept of database it is a concept of C#, any of the field in a database can be null. Sometimes for making decision it is necessary to assign null to value type variable. Again we get here two types, one is nullable and the other is non-nullable. We can assign null to non-nullable types by using the ? operator.
Suppose we have a form that ask the user a question “Are you a teacher?” and this field is optional. User can say yes or no and the user can also keep the field empty. If we have a bool type variable to store the answer then we can assign true or false in this variable nothing else. But if the user keep the field empty we need to assign null to bool type variable. We can do it by using ? operator as follows.

bool? ISUserTeacher = null;

So we can make a non-nullable type a nullable type by using ? operator. Now consider an example to understand null coalescing operator. Suppose a have 10 mangoes in a tree and we store the result in a integer type variable as follows-

int MangoesInTree = 10; 

Now it is possible that there is no mangoes in the tree. So we have to make the integer variable a nullable variable that we can assign null value to it. We can do it as follows-

int? MangoesInTree = null; 

Suppose we have another variable named availablemangoes and we will assign the value of MangoesInTree in it if MangoesInTree is not null. If MangoesInTree is null then we will assign 0 to availablemangoes variable. We can do it as follows-

using System;
class Program
{
   static void Main()
    {
        int? MangoesInTree = null;

        int availablemangoes;

       if(MangoesInTree==null)
       {
           availablemangoes = 0;
       }
       else
       {
           availablemangoes = MangoesInTree;
       }
	Console.WriteLine(“{0}”,availablemangoes);
    }
}

Unfortunately we will get an error here that “cannot imlicitly convert type int? to int”. Here MangoesInTree variable is a nullable variable but availablemangoes is not a nullable variable so it cannot be assigned by the nullable types. Here we can use a way to do it. It is called type casting. We will discuss about type casting and implicit, explicit type conversion in the very next article. So just for now note it, we can do the above program as follows-

using System;
class Program
{
   static void Main()
    {
        int? MangoesInTree = null;

        int availablemangoes;

       if(MangoesInTree==null)
       {
           availablemangoes = 0;
       }
       else
       {
           availablemangoes = (int)MangoesInTree;
       }
Console.WriteLine(“{0}”,availablemangoes);

    }
} 

Now it will print the value of availablemangoes as we wanted. But we can do the same program with just one line and this is what the null coalescing operator is. We can do the same program with null coalescing operator. The above program with null coalescing operator can be written as follows-

using System;
class Program
{
   static void Main()
    {
        int? MangoesInTree = 10;

        int availablemangoes;

        availablemangoes = MangoesInTree ?? 0;

       Console.WriteLine("{0}", availablemangoes);
    }
}

Look closely to the above program here we do the same thing with just one line of code. Here the default value what we want to assign in non-nullable variable is given after the null coalescing operator (??) and before the operator we supply the value that we want to assign if the MangoesInTree variable is not null that is the variable itself. That is the purpose of null coalescing operator. It helps to assign a non-nullable types with nullable types in C#.

Reading and Writing to the Console

In the previous article we discussed about the basic structure of a C# program. Today we will see reading and writing operation to the console. We will see a little more interactive sample program than the previous today. Our program will ask the user his/her name and then print a welcome message with the name of the user which he/she just enter.

To write something to the console we have two methods under System namespace, one is Write and the other is WriteLine. Only the difference between these two is, if we use WriteLine then after writing something to the console it will print a new line also but in Write method it will just print something. No new line will be printed here.

For an example if we write in the main method Console.Write(“Hello World ”); then the output should be as follows-

Hello World press any key to continue

The line “press any key to continue” indicates that the program is terminated. Instead of this method if we use Console.WriteLine(“Hello World ”); then the output should be as follows-

Hello World

press any key to continue

Here we can see that the line “press any key to continue” is in a new line. So the method Writeline prints a new line after writing something to the console.

Similarly there are to methods for reading something in the console, one is Read and the other is ReadLine. The Read method read integer type from the console and the Readline method read string type from the console. So if we write Console.ReadLine() then we have to store the returned result in a string type variable so that we can use it later in the program.

Now let’s see the code our sample program. It is as follows-

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome "+ name);
    }
}

Here we can see in the MAIN method first we are printing a message asking the user’s name. Then when our next line of code executed it waits for the user input that is our read operation from the console. When the user enters something and press the Enter button then Console.Readline methos reads what is entered in the console and return it as a string type. Here we store the returned string in a string type variable named name. So what user entered in the console now stored in the variable. Then in the next line we write in the console “Welcome “concatenated with the name of the user. Here we are concatenating two string- One is “Welcome ” and the other is string type variable called name with the “+” sign in the WriteLine method.
There are actually two ways of writing something in the console. They are-
• Concatenation
• Place holder syntax
We already have seen the concatenation method of writing something to the console. Now we will see the place holder syntax in the same program. If we want to use place holder syntax in the same program then the code should be as follows-

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome {0}",name);
    }
}

Here we can see in case of “+” operator we use “{0}” in the string with Welcome. This is called the place holder. When we run the program, the value of the variables that we pass after comma in the WriteLine method replaces the place holder. So if we run this piece of code we will see the same result here.
The place holder syntax is more preferable than the Concatenation process. To see how place holder syntax gives more capability let’s modify the above program. Now we will ask the user to enter his/her first name then after reading the first name we will ask for last name and after reading that we will print the first name and last name separated by a comma with the welcome message. To do that the program should be as follows –

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your first name?");
        string firstname = Console.ReadLine();
        Console.WriteLine("What is your last name?");
        string lastname = Console.ReadLine();
        Console.WriteLine("Welcome {0},{1}",firstname,lastname);
    }
}

Here in the code we can see there are two place holders and there are two string type variable as well to store the first name and last name of user. When we write the welcome message in WriteLine method we use two placeholder and two variable to replace the place holder. In the same way we can use as many as place holders we required. We just have to surround the number of that place holder with curly braces. That’s why place holder syntax is more preferable than the concatenation method.

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. 🙂

Introduction(Understand the basic structure of a c# program)

Hello Everyone!! In this series of tutorial we are going to discuss about the basic elements of C#. Like all others OOP (Object Oriented Programming) languages C# is also an OOP language that means the three qualities that make a programming language object oriented can be found in C# also. The qualities are-

  • Encapsulation
  • Polymorphism
  • Inheritance

We will understand each of this qualities in the later session of this series. In this article we will understand the basic structure of a C# program. All the sample programs of this series is going to be a Console Application and we are using Visual Studio as the IDE. So first we will learn how to open a console application in Visual Studio.

A console application is nothing but a program that can be executed in the command prompt of our Computer. To open a console application first we have to open visual studio then from the menu choose File-> New-> Project. Then another windows will pop up then in the popup window choose Visual C# in the left and you can see console application there. Choose Console Application template and give it a suitable name, you can choose the location where to save this program in your pc from here also. When you choose everything click the OK button to create the program.

OpenNewProject

When you click the OK button the program will be created and you will see the following code –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace introduction
{
    class Program
    {
        static void Main()
        {
        }
    }
}

Now for simplicity we will remove some code from the above and make it a very basic structure of a C# program. After removing those code the above program will looks like the following-

using System;

class Program
{
    static void Main()
    {

    }
}

The above program can be said as a very basic structure of C# program. Now we will describe each line of the above program.
The first line is-
using System;

This is called the namespace declaration. A namespace is nothing but a collection of some classes, enums, structs, interfaces and delegates. What are all these we will discuss later. A namespace can hold another namespace also. For now to understand the above line we can say there are some built-in methods in this namespace called System and to use those methods and classes we have to declare the namespace by using keyword at the top. Just for an example if we want to print something in the console then we can write the following code-

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello world");
    }
}

To run the above code press Ctrl+F5. Then the command prompt should appear with the message “Hello world”.
The definition of this Writeline method is written in the namespace called System. Now if we remove the using System; line from our code then we will get an error in the line Console.WriteLine(“Hello world”);
Because now the definition of WRITELINE method is missing from our program. If we want to remove the namespace declaration then we have to write the name in the line when we use a method belongs to that namespace as follows-

class Program
{
    static void Main()
    {
        System.Console.WriteLine("Hello world");
    }
}

Namespace is used to organize our code more effectively. If you don’t use the namespace declaration at the top then each time when you use a method you have to write its namespace which is more time consuming. So the use of namespace declaration is important.
Now the next thing in our basic structure is a Class declaration. We assume that you are familiar with OOP and if you are so then you are already known to class. Like other OOP language the class declaration in C# is exactly same. Anything you write in C# is belongs to a class. There are different types of class in C#. We will discuss it later in this series. Just for now we can say any piece of code should be inside of a class. Here the name of our class is Program.
Then there is also a method named Main and it is a static method. What is static method and class we will discuss it later. Now what we have to understand is the Main method is the starting point of our program. When we run our code it start to execute each line from the beginning of Main method and end when the Main method ends. To prove this, we can declare another same method named Main2 and in this method we print another message to differentiate the two method. We can consider the following piece of code-

using System;
class Program
{
    static void Main2()
    {
        Console.WriteLine("Another Message");
    }
    static void Main()
    {
        Console.WriteLine("Hello world");
    }
}

Here if we run the program we will see that only the message “Hello world” is printed. Another method named MAIN2 is not executed. So it’s proved that our program start from Main method and terminate when the MAIN method terminates. If we want to print the 2nd message then we have to call the MAIN2 method from MAIN method before it terminates. We can do it by the following-

using System;
class Program
{
    static void Main2()
    {
        Console.WriteLine("Another Message");
    }
    static void Main()
    {
        Console.WriteLine("Hello world");
        Main2();
    }
}

Now we should be able to see both messages.
In this article we see the basic structure of a C# programming and we can sum up with the following decisions from the above discussion-
• The namespace declaration using System; indicates that you are using System namespace
• A namespace is a collection of Classes, Structs, Delegates, Enums, Interfaces and used to organize the code more effectively.
• Our program starts with the Main method and terminates when the Main method terminates.

 

Recording Audio in Windows Phone 8.1

First Words

This article points to a simple, fast way to record audio in Windows Phone 8.1. As the old Microphone class is no longer available, Windows Phone 8.1 came with new MediaCapture class to consolidate the media recording part for audio and video together. So, why waiting, let’s see how to do it!

Let’s get busy

I jotted a very simple GUI for this that has three simple buttons named “Capture Audio”, “Stop Capture” and “Play Capture”.  And it looks as follows:

CaptureAudio1

If you guys want to have a closer look at the XAML behind, peek a look:

<Page
    x:Class="CaptureSoundTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CaptureSoundTest"
    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>
        <MediaElement x:Name="playbackElement1" ></MediaElement>
        <Button x:Name="CaptureButton" Content="Capture Audio" HorizontalAlignment="Center" Margin="0,184,0,0" VerticalAlignment="Top" Click="CaptureButton_Click" Width="145"/>
        <Button x:Name="StopCaptureButton" Content="Stop Capture" HorizontalAlignment="Center" Margin="0,284,0,0" VerticalAlignment="Top" Click="StopCaptureButton_Click" Width="145"/>
        <Button x:Name="PlayRecordButton" Content="Play Capture" HorizontalAlignment="Center" Margin="0,380,0,0" VerticalAlignment="Top" Click="PlayRecordButton_Click" Width="145"/>

    </Grid>
</Page>

It’s pretty basic, I didn’t do much here without keeping the buttons in place. There’s a MediaElement named playbackElement1 to play back the recorded video.

Now, it’s time to populate the button events here named CaptureButton_Click, StopCaptureButton_Click and PlayRecordButton_Click

Initializing and Capturing audio

To capture audio, first we need to initialize the recording. Before digging into that, let’s just initialize some variables that we might need on the journey.

private MediaCapture _mediaCaptureManager;
private StorageFile _recordStorageFile;
private bool _recording;
private bool _userRequestedRaw;
private bool _rawAudioSupported;

The MediaCapture class here is the one responsible here to capture audio and video both here. And StorageFile instance will help us store, locate and play the recorded media on our device.

So, let’s have a look how our recording initialization method looks like:

private async void InitializeAudioRecording()
{

   _mediaCaptureManager = new MediaCapture();
   var settings = new MediaCaptureInitializationSettings();
   settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
   settings.MediaCategory = MediaCategory.Other;
   settings.AudioProcessing = (_rawAudioSupported &amp;&amp; _userRequestedRaw) ? AudioProcessing.Raw : AudioProcessing.Default;

   await _mediaCaptureManager.InitializeAsync(settings);

   Debug.WriteLine("Device initialised successfully");

   _mediaCaptureManager.RecordLimitationExceeded += new RecordLimitationExceededEventHandler(RecordLimitationExceeded);
    _mediaCaptureManager.Failed += new MediaCaptureFailedEventHandler(Failed);
}

So, the very first thing done here is the initialization of the MediaCapture class. Every media capture is associated with a MediaCaptureInitializationSettings instance. We’ve set the StreamingCaptureMode to Audio to make sure this is only audio recording rather than video. There were two bool variables declared before named _rawAudioSupported and _userRequestedRaw. Although I didn’t hook them up from GUI, you guys can defintiely try hooking them up from GUI and thus you can give the app a choice to record raw or pointing it to default audio processing.

The next thing to do is initializing the _mediaCaptureManager with the settings provided. I have included two event handlers for RecordingLimitExceeded and Failed. You guys can write your own handlers of course in these cases.

Now, usually you can put the InitializeAudioRecording method where your app initializes. I put it here on MainPage constructor.

Now, let’s capture audio, MediaCapture class made it really easy indeed.

private async void CaptureAudio()
{
   try
   {
     Debug.WriteLine("Starting record");
     String fileName = "record.m4a";

     _recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

     Debug.WriteLine("Create record file successfully");

     MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto);
     await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);

     Debug.WriteLine("Start Record successful");

     _recording = true;
    }
    catch (Exception e)
    {
      Debug.WriteLine("Failed to capture audio");
    }
}

If you have a good look on the code you will see we declared a filename first. And then we created a file in our VideosLibrary using KnownFolders.VideosLibrary.CreateFileAsync that actually points to the media and video library of windows phone 8.1 with a given filename and we also gave a CreationCollisionOption.GenerateUniqueName that says it will create a unique name in case of collision. The next thing to do is creating a recording profile using MediaEncodingProfile class and you can get all possible recording profiles for videos and audios from here. I created a M4a audio profile using MediaEncodingProfile.CreateM4a(recordProfile, this._recordStorageFile) method.

All we have left to do is now start the recording, so  let’s go ahead and start the recording. And it’s easy as pie with _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile)

Stopping Recording

Stopping the recording is quiet easy too. All you have to do is call _mediaCaptureManager.StopRecordAsync()

private async void StopCapture()
{

     if (_recording)
     {
          Debug.WriteLine("Stopping recording");
          await _mediaCaptureManager.StopRecordAsync();
          Debug.WriteLine("Stop recording successful");
          _recording = false;
     }

}

Playing Recording

Playing a recording kind of consists of two tasks. First we have to open the recorded file and then play it. If you guys remember we used StorageFile _recordStorageFile to define our file that will hold the recording.

private async void PlayRecordedCapture()
{
     if (!_recording)
     {
         var stream = await _recordStorageFile.OpenAsync(FileAccessMode.Read);
         Debug.WriteLine(&quot;Recording file opened&quot;);
         playbackElement1.AutoPlay = true;
         playbackElement1.SetSource(stream, _recordStorageFile.FileType);
         playbackElement1.Play();
     }
}

So, let’s open up the file and assign the resultant stream to a source of a MediaElement on XAML. In this case that one is playBackElement1

 

Voila! You’re done, now you can play your recording. All you have to do now is assign these three methods to proper button events. For the full source please download the demo project above.

A little bit of fun with face detection in Windows Phone 8

To start off

If anybody is actually looking for Face Detection Libraries for Windows Phone and haven’t tried this one, this is for them. It’s a neat library popping off facedetecionwp7 library by Julia Schwarz. And you can do pretty cool stuffs with it with pretty less hassle.

Let’s have a little fun

Let’s go ahead and get ourselves started with a Windows Phone 8 Project. Our job would be try this library and detect faces in a picture and have some fun with it, say overlay the face with the classic troll face with the laugh. 😛

Troll

Now, no matter what that sounds, let’s give it a shot. I’ve jotted down a very simple GUI to do this one. And it’s as following:

FaceDetection1

If you want to have a closer look at the XAML it will look the following:

<Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

       
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="Face Detection in Windows Phone" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button x:Name="CaptureImageButton" Content="Capture Image" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Top" Width="267" Click="CaptureImageButton_Click"/>
            <Image Name="facesPic" HorizontalAlignment="Center" Height="388" Margin="0,170,0,0" VerticalAlignment="Top" Width="427"/>
        </Grid>

        
    </Grid>

Now, you can definitely see that this is a very basic UI. We have a Button with a click event CaptureImageButton_Click and a Image named facesPic.

Now, before we get our hands dirty, let’s go ahead and add reference to a library we will need. We will need WritableBitmapEx from here. This lib is already available on Nuget too, so you can get it from there too.

After you added that in your project reference, you will need a bunch of libraries from FaceDetectionWP8 to make this things work. You can get the classes on there from the following link too.

After you download the .zip , unzip it and include all the classes inside in your project. I added them under a separate folder named FaceDetector.

Let’s move to our MainPage.xaml.cs

Now, the first thing to do is to pick a picture and the best thing to use for that is PhotoChooserTask . Let’s hook up the following snippet in CaptureImageButton_Click event.

private void CaptureImageButton_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask photo = new PhotoChooserTask();
            photo.Completed += new EventHandler&lt;PhotoResult&gt;(photoChooserTask_Completed);
            photo.ShowCamera = true;
            photo.Show();
        }

Now, the next thing to write is definitely photoChooserTask_Completed event handler. Let’s go ahead and write it. First thing to do would be get the chosen photo into a  WritableBitmap as we are going to do some changes on it.

if(e.TaskResult==TaskResult.OK)
{
    BitmapImage SourceBitmap = new BitmapImage();
    SourceBitmap.SetSource(e.ChosenPhoto);
    WriteableBitmap SourceWritableBitmap = new WriteableBitmap(SourceBitmap);

}

Now, the next thing we need to do is downsample the image a bit as most of the Windows Phone devices pack a pretty powerful camera and often the pictures are oversampled. I personally suggest you downsize the image a bit too. I din’t do it in this demo but if you want a faster performance, you really should try that too. I added the following code segment inside the if block.

byte[] downsampledImage = new byte[SourceWritableBitmap.PixelWidth / _downsampleFactor * SourceWritableBitmap.PixelHeight / _downsampleFactor];

Utils.DownSample(SourceWritableBitmap.ToByteArray(), SourceWritableBitmap.PixelWidth, SourceWritableBitmap.PixelHeight, ref downsampledImage, _downsampleFactor);

SourceWritableBitmap = SourceWritableBitmap.FromByteArray(downsampledImage);

The code segment is pretty straight forward here now. The Utils class here is from the FaceDetectionWP8 library. The first argument for Utils.DownSample used here is a Byte Array of the SourceWritableBitmap and it used the WritableBitmapEx we added here before. The second one is the width of the source bitmap and the third one is the height. The last argument passed here is the downsample factor. This was defined as the following in the MainPage class.

int _downsampleFactor = 2;

And then the SourceWritableBitmap is reinitiazed with a downsampled version of it’s own.

The next thing to do would be getting the faces detected of course. 😀 So, why wait? I added the following sinppet for that.

List<FaceDetector.Rectangle> faces = new List<FaceDetector.Rectangle>();
faces = _detector.getFaces(SourceWritableBitmap, 2f, 1.25f, 0.1f, 1, false, true);

I used the defaults here except the last argument that determines whether it should detect multiple faces and I kept it true.  You can have fun with the other params if you want to tweak your haar cascade detection parameters here.

here comes the fun part, now we are going to replace the face/faces in the picture with the troll laugh picture. :P. We can see it returns the faces as a List<FaceDetector.Rectangle>. All we have to do now is paint the Troll laugh in the rectangles returned by the method. fun, huh?

Now, before replacing the Source Image with the Troll Laugh, we need to load it in another WritableBitmap so we can blend the both of them.

StreamResourceInfo MaskImageSri = Application.GetResourceStream(new Uri("Images/Troll.png", UriKind.Relative));
BitmapImage MaskImageBitmap = new BitmapImage();
MaskImageBitmap.SetSource(MaskImageSri.Stream);

WriteableBitmap MaskWritableBitmap = new WriteableBitmap(MaskImageBitmap);

As we got our Troll.png, why don’t we paste it on the source bitmap?

foreach (var r in faces)
{
   int x = Convert.ToInt32(r.X);
   int y = Convert.ToInt32(r.Y);
   int width = Convert.ToInt32(r.Width);
   int height = Convert.ToInt32(r.Height);                    

   System.Windows.Rect destRect = new Rect(x, y, width, height);
   System.Windows.Rect srcRect = new Rect(0, 0, MaskWritableBitmap.PixelWidth, MaskWritableBitmap.PixelHeight);

   SourceWritableBitmap.Blit(destRect, MaskWritableBitmap, srcRect);

}
   SourceWritableBitmap.Invalidate();
   facesPic.Source = SourceWritableBitmap;

Now, this is pretty straight forward too. All we need is we iterated over the faces and we created to separate rect structs. One is from the MaskWritableBitmap so we can get the rect of the portion of the image we are pasting, in this case, the full one and the destination rect is the face rectangle on the source image we are pasting this troll laugh on.

The next thing to do is invoke Blit() method as this one is responsible to blend these two WritableBitmaps. It comes with the WritableBitmapEx library we added before. The first parameter is the destination rectangle where the source rectangle will be pasted. In this case the face rectangle that will be replaced by the troll laughter image. The second parameter would be the WritableBitmap where the rect that would be posted in the source is found. Here this one is the Troll Image and the last one is the rect in the Troll Image that would be transferred to the main bitmap.

We called it on SourceWritableBitmap as we want to paste the troll Laugh on it. And when all is said and done we set facesPic source to the SourceWritableBitmap.

Now all we have to do is build and test the app. And the result is as following:

FaceDetectionScreenshot

So, what are waiting for? Test the demo project here of the article and have fun!

Windows Phone For Newbies: Episode 1 – Introduction

আপনি যদি আগে কখনোই উইন্ডোজ ফোনে কাজ না করে থাকেন তাহলে এই ভিডিও সিরিজ টি আপনার জন্যে। এটি উইন্ডোজ ফোন ৮.১ এর একটি বাংলা টিউটোরিয়াল সিরিজ যা আপনাকে একদম শুরু থেকে উইন্ডোজ ফোনে কাজ করার জন্য সম্যক সকল কিছু জানিয়ে দেবে।

এটি সিরিজটির প্রথম পর্ব

ইউটিউব প্লেলিস্টটি পাচ্ছেন এইখানে

প্রোজেক্ট সোর্স কোড পাচ্ছেন এইখানে

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