Tuesday, December 7, 2010

HTC 7 Surround

Yup, I finally decided to get my hands on a Windows Phone 7 device. The reasons why I chose the HTC Surround 7 are pretty simple. I already had a contract with Telus and right now they only offer this one and the LG Optimus 7, secondly, the Surround as the alarm clock feature that the Optimus doesn't have and finally, the three main buttons, at the bottom of the screen are "touch" instead of actual buttons as the Optimus provides. I know that there are other Windows Phone 7 HTC devices, but the Surround is the only one available here for now so I didn't really had the choice, I don't think I will actually use the huge Yamaha speaker unless maybe for the alarm clock.

I'm not here to talk about the phone though, the real subject of this post is the Operating System, Windows Phone 7. After a couple of days using it and configuring it I thought I could let you all now about the small thing that annoyed me. Let me be clear though, all these little complications have nothing to ruin my experience with this OS. After only a couple of days, I'm already addicted.

Mac Address
There is actually no way, from the device itself, to find the Mac Address. So if your WiFi network uses Mac Address filtering, you'll have to disable it, connect the device to your network, use your router to find the newly connected device's address and then re-enable the filtering.

SSID Broadcasting
Windows Phone 7 is actually unable to connect to any WiFi network that does not broadcast its SSID

Tethering
For now you can't share your mobile internet connection with another device. I do hope this feature will be implemented in Windows Phone 7 and that carriers won't have the option to disable it.

Live ID
When you first use your Phone 7 device, you will provide your Live ID, this Email is used for importing contacts and information from your Xbox Live account. Make sure you enter the right one because the only way to change it is to reset your device, thus losing all your settings and anything you already installed or transfered.

Storage
The device can't be used as a simple storage device. To transfer any content you need to use the Zune software, so you can only manage videos, pictures, music and apps.

Edit : My bad, I CAN actually edit a linked contact without unlinking it.
Linked Contacts
When the same contact can be found more than one time, let's say in your Hotmail contacts and Facebook contacts, they are automatically linked, which is not a problem, BUT, if you want to add , let's say a new phone number, to one of those "linked" contact, you have to "unlink" it first. This is a behavior that I simply don't understand. I really hope this to change in a future update.


Importing contacts
Facebook contacts and Window Live contacts or imported to the device automatically. You can set an option in the setting to make sure that your Facebook contacts are not imported automatically but make sure to do it before you set your Facebook account. Also, If you delete a Windows Live contact from the phone, it gets deleted from your Windows Live contacts. I'd like to have more options.

Well that may seem like a lot, but I still think its pretty good for a new mobile OS. One last thing, to sync with an exchange account make sure that ActiveSync is enabled on your account, once it is everything should work fine. I actually have a total of 5 Email accounts and they all work fine on Windows Phone 7.

Thursday, December 2, 2010

Using the ThreadPool - An example as simple as possible

I just posted a code sample using the ThreadPool on a forum so I thought I could also post it here. Who knows, it might prove usefull to someone someday. Basically it simply demonstrate how to create and start new threads with the ThreadPool and how to use delegates with parameters. Here it is :
Imports System.Threading

Public Class Form1

    Delegate Sub UpdateItemValueDelegate(ByVal index As Integer, ByVal value As Integer)
    Public UpdateListItem As UpdateItemValueDelegate = AddressOf UdateItemValue

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Add some values to the listbox for the example
        For i As Integer = 0 To 10
            ListBox1.Items.Add(i.ToString())
        Next
    End Sub

    Private Sub UdateItemValue(ByVal index As Integer, ByVal value As Integer)
        'Set the new item's value
        ListBox1.Items(index) = value
    End Sub

    Private Sub CalculateNewValue(ByVal itemIndex As Integer)
        'Calculate a new value for the given item and call the delegate to set the new item's value
        Dim value As Integer
        value = ListBox1.Items(itemIndex) * 5
        If ListBox1.InvokeRequired Then
            Me.Invoke(UpdateListItem, {itemIndex, value})
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Run a thread for each item in the list
        For i As Integer = 0 To ListBox1.Items.Count - 1
            ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf CalculateNewValue), i)
        Next
    End Sub
End Class

Microsoft Press Books

For those interested in Microsoft Visual Studio 2010 MCTS or MCPD, the following MCTS book is suppose to be available december 16th :
MCTS Self-Paced Training Kit (Exam 70-515): Web Applications Development with Microsoft .NET Framework 4

Monday, November 29, 2010

Use VB on Windows Phone 7

For those of you VB coders who were interested by the new Windows Phone 7 platform, Visual Basic for Windows Phone Developer Tools - RTW is now available for download here.

Sunday, August 22, 2010

.Net FW 4: Data Parallelism

I just started to look at the .NET Framework 4, yeah I know I’m late, and everything new it brings us so I thought I’d do a small post about the Data Paralellism and show a small example of Parallel.For loop and the comparison with a standard for loop. The code bellow is pretty simple, it additions integers from 0 to 2 million (exclusive) and put the result in a long variable and it displays the result and the elapsed time in milliseconds for each loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();

            int[] nums = Enumerable.Range(0, 2000000).ToArray();
            long total = 0;

            watch.Reset();
            watch.Start();
            for (int i = 0; i < nums.Count<int>(); i++ )
            {
                total += nums[i];
            }
            watch.Stop();

            Console.WriteLine("The total is {0}", total);
            Console.WriteLine("'For' loop completed in " + watch.ElapsedMilliseconds.ToString() + " milliseconds.");
            Console.WriteLine();

            total = 0;
            watch.Reset();
            watch.Start();

            Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>
            {
                subtotal += nums[j];
                return subtotal;
            },
                (x) => Interlocked.Add(ref total, x)
            );

            watch.Stop();
            
            Console.WriteLine("The total is {0}", total);
            Console.WriteLine("'Parallel.For' loop completed in " + watch.ElapsedMilliseconds.ToString() + " milliseconds.");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}
As you can see in the following screenshot, The Parallel.For loop is much faster than the standard for loop.


Using Parallelism is usually faster but in case of very simple processing it can in fact be a little bit longer due to the parallelism layer that is added. I also suggest having a look at the other available classes from the System.Threading.Task Namespace as the TaskFactory, which is used to create asynchronous operations and can be a good alternative to the BackGroundWorker.

Saturday, June 12, 2010

BackGroundWorker example

I’ve seen a lot of questions lately on forums about the BackGroundWorker (BGW) Class and how to use it. The BGW’s purpose is to execute an operation on a separate thread. Whenever you have a time-consuming operation that need to be executed you can use a BGW to avoid having your User Interface (UI) stop responding. It is a convenient solution if you only have a single time-consuming operation to execute. If you have multiple time-consuming operations that you would like to execute at the same time, then I suggest you have a look at the ThreadPool Class.

Here’s a small example in VB.NET that shows how to use the BGW to perform an SQL query while the first Form show a progress bar and then displays the second Form once the SQL operation as completed.

Imports System.Data.OleDb

Module Module1
    Public da As New OleDbDataAdapter
    Public ds As New DataSet
End Module

Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Data.OleDb


Public Class Form1
    Dim WithEvents bgw As New BackgroundWorker
    Delegate Sub HideButtonDelegate()
    Public HBD As HideButtonDelegate = AddressOf Me.HideButton

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        bgw.WorkerSupportsCancellation = True
        ProgressBar1.Show()
        bgw.RunWorkerAsync()
    End Sub

    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bgw.DoWork
        'Do your lenghty operations here

        Dim MyConnection As New System.Data.OleDb.OleDbConnection()
        Dim MyCommand As OleDbCommand


        Try
            MyConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & Application.StartupPath & "\Database1.accdb"
            MyConnection.Open()
        Catch ex As Exception
            MessageBox.Show("Cannot connect to the specified database" & ex.Message)
        End Try

        Try
            MyCommand = New OleDbCommand("SELECT * FROM Table1", MyConnection)
            da.SelectCommand = MyCommand
            ds = New DataSet
            da.Fill(ds, "Table1")
        Catch ex As Exception
            MessageBox.Show("Cannot fetch data from the database" & ex.Message)
        End Try
        System.Threading.Thread.Sleep(2000)
        If Button1.InvokeRequired Then
            Me.Invoke(HBD)
        End If

        System.Threading.Thread.Sleep(2000)

    End Sub


    Private Sub bgw_Completed(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) Handles bgw.RunWorkerCompleted
        ProgressBar1.Hide()
        Me.Hide()
        Form2.Show()
    End Sub

    Private Sub HideButton()
        Button1.Visible = False
    End Sub
End Class

Public Class Form2

    Private Sub Form2_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        Form1.Close()
    End Sub

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        DataGridView1.DataSource = ds.Tables(0)
    End Sub
End Class

Sunday, April 18, 2010

String replacement with Regular Expressions

I answered a question last week on a forum about using Regular Expressions for complex string replacements so I thought I might just post a small example. For simple string replacement there’s the String.Replace method, but whenever you need to manipulate the match you want to replace in order to build the replacement string, the RegEx.Replace method does the job. Here’s a small code sample that searches in a string for a parameter named “username” and its value and then builds a HTML link stirng with it.

private void button1_Click(object sender, EventArgs e)
{
 string s = "username=myusername";
 Regex patern = new Regex(@"\[(username=(\W+))\]");
 MatchEvaluator matchEval = new MatchEvaluator(GetReplacement);

 s = patern.Replace(s,GetReplacement);

 MessageBox.Show(s);

}
 
private string GetReplacement(Match m)
{
 return "" + m.Groups[2] + "";
} 

Sunday, April 4, 2010

Using the StringBuilder class

In .NET I often see people use the plus ‘+’ operator in C# or the ampersand ‘&’ operator in VB.NET to concatenate strings. Whenever these operators are use for concatenation the Framework copies all the strings included in the operation into memory and then reads back those value as a new string. This, even if it doesn’t seem to be, is a costly operation. This is where the StringBuilder comes in. This class, as MSDN describes it is “ a string-like object whose value is a mutable sequence of characters. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters.” And the important thing to know is that it is faster than using concatenation operators as you can see in the following example.



using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Concatenation using string class and operators");
            string s = string.Empty;
            Console.WriteLine("Operation start time: " + DateTime.Now.ToLongTimeString());
            for (int i = 0; i < 100000; i++)
            {
                s += i.ToString();
            }
            Console.WriteLine("Operation stop time: " + DateTime.Now.ToLongTimeString());

            Console.WriteLine();

            Console.WriteLine("Concatenation using StringBuilder");
            StringBuilder sb = new StringBuilder(string.Empty);
            Console.WriteLine("Operation start time: " + DateTime.Now.ToLongTimeString());
            for (int i = 0; i < 100000; i++)
            {
                sb.Append(i);
            }
            Console.WriteLine("Operation stop time: " + DateTime.Now.ToLongTimeString());

            Console.WriteLine();
            Console.WriteLine("Press any key to close this window.");
            Console.ReadLine();
        }
    }
}







Sure if you only concatenate a couple of strings you won’t see the difference but still, I think that using the StringBuilder class whenever you need to manipulate a string is a good habit to take.

Monday, March 15, 2010

Running VS2008 on a Netbook

As I am not always home but still want to be able to work on my personal project, at the lowest cost possible, I finally bought myself a brand new ASPIRE ONE 532h from ACER. This one ships with the new Intel Atom N450, 1 GB of Memory, a 160GB HDD and a 3 cell Li-ion battery that last around 4 hours. 

I installed Visual Studio 2008 Professional on it and I have to admit that it runs fine as long as you don't try to open or build a huge solution. The 10.1 inches screen does the job but when writing code into VS I strongly recommend going full screen using the "view" menu or the "Shift + Alt + Enter" shortcut. See for yourselves in the following screenshots.



Monday, March 8, 2010

Tablet PC : ExoPC Slate

After having been particularly disappointed by what the iPad will be, I started searching the web for other tablet PCs and I finally found something that might suit my needs. The ExoPC Slate. I don't think I'll buy the first version, which should be on the shelves pretty soon maybe even before the iPad as it is now suppose to be released in april, but I might give it a try later if reviews are good.

Update on march 14th : I learned last week that the ExoPC slate should finaly come out this summer. It will be assembled in Quebec instead of China to provide a better control on quality. Until then they might work on the battery to get a device that will last longer.

Saturday, March 6, 2010

Regular Expressions

Regular expressions provide a flexible way for matching patterns in text and are commonly used in syntax highlighting systems for example. They can also be used to validate data input like Email addresses format.

Personally I use regular expression as soon as I need to find many different occurrences of a string that have a common pattern. For example I once needed to insert links into diverse technical PDF manuals that were split by chapters and sections, respecting a standard nomenclature i.e. “ManualTitle-CH01” for the chapter 1. Each document referring to the other ones as “Chapter XX” or “Section XX” and containing internal references like “Figure XX”. In cases like that you can have hundreds or thousands different string to search meaning maybe hundreds lines of code while regular expressions could accomplish the task with a few.

In order to use the Regular Expressions in Visual Studio you need :
using System.Text.RegularExpressions;
Here is a small code example for finding multiple pattern matches.
private void findMatches(string text)
{
 Regex pattern = new Regex("Chapter\s(\d+)|Section\s(\d+)|Figure\s(\d+)");
 MatchCollection matches = new MatchCollection();

 matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase);
 foreach(Match m in matches)
 {
  /*Work with the match here, generate and insert link etc.*/
 }
}
Here are a couple of links that might prove usefull :
Regular Expression Syntax
Regular Expression Language Elements
Regular Expression Tester
I hope this first post may help some of you.