Metro Style App Main(…)

If you have created a C# or C++ console application, you would be familiar with main(…) method which is the starting point of the console application.

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}

In a metro style app (Metro AG, I hope you don’t mind), the starting point for developer is App.OnLaunched(…).

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

However, if you click show all files button which make the Visual Studio to show all hidden files, you will see a file \obj\Debug\App.g.i.cs.

image

image

Surprisingly, you will see the familiar static class Program and a method Main(string[] args). The main method actually starts the metro style app by initiate App instance. Don’t believe me? Try putting break point in there. Smile

    public static class Program
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        static void Main(string[] args)
        {
            global::Windows.UI.Xaml.Application.Start((p) => new App());
        }
    }

Missing Azure Cloud Project Template in Visual Studio 2012

It’s late at night, and you couldn’t sleep. So you just want to try WindowsAzure. You, a .NET developer, then downloaded and installed the Windows Azure SDK for .NET. Next, you opened Visual Studio 2012 RC and couldn’t find any project template for Windows Azure.

image

What’s wrong? It turned out that you just need to select .NET Framework 4.0 instead (the small sentence did give some hint though).

image

Now you should see the “Windows Azure Cloud Service” template and create any Azure role you want. Get some coffee (soda or beer) and enjoy coding!

image

image

Where is a suspend button in Visual Studio 2012

I might be wrong, but I recall seeing suspended button in VS 2011 (came with Windows 8 CP) which I could press and test the suspended state of my Metro (Modern??) style app while I was debugging my app. However, I couldn’t find it anymore in VS 2012 RC.

image

After doing some research, I found out that I have to have “Debug Location” toolbar activated to be able to see it.

image

image

Hope this helps someone who might have the same problem. Enjoy coding!

Introduction to Telerik RadControls for Metro (Pie Chart)

Following the previous Telerik RadControls Bar Chart post, in this post, I will reuse the StateData and Person data model to create a Pie Chart.

Pie Chart needs pie series with the ValueBinding (similart to Bar Chart). However, PieSeries does not have CategoryBinding which creates labels in Bar Chart. For the PieSeries we will need PieLabelStategy instead.

The code below shows how we put PieChart control in xaml page. Don’t forget to specify telerik namespace like we did in the Bar Chart post.

        <telerik:RadPieChart Grid.Row="1" PaletteName="DefaultDark"
                             x:Name="radPieChart">
        </telerik:RadPieChart>

In the code behind, I create PieSeries and binding. Like the Bar Chart sample, the ValueBinding is binded to StateData.Count (i.e., how many customers in the state). RadiusFactor property controls how big is our pie chart.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var peopleByStates = from p in SamplePeople.People
                                 group p by p.ResidenceState into g
                                 orderby g.Key
                                 select new { State = g.Key, People = g };

            var series = new PieSeries();
            series.RadiusFactor = 0.7;

            series.ValueBinding = new PropertyNameDataPointBinding("Count");
            // Set up label strategy
            var pieLabelStrategy = new PieLabelStrategy();
            pieLabelStrategy.Binding = new PropertyNameDataPointBinding("Name");
            var chartSeriesLabelDefinition = new ChartSeriesLabelDefinition();
            chartSeriesLabelDefinition.Strategy = pieLabelStrategy;

            series.LabelDefinitions.Add(chartSeriesLabelDefinition);

            var itemSources = new List<object>();
            foreach (var state in peopleByStates)
            {
                var item = new StateData { Name = state.State, Count = state.People.Count() };
                itemSources.Add(item);
            }
            series.ItemsSource = itemSources;
            radPieChart.Series.Add(series);
        }

To create a label strategy, we extend an abstact class Telerik.UI.Xaml.Controls.ChartSeriesLabelStrategy and override Options property, CreateDefaultVisual method, and GetLabelContent method. The CreateDefaultVisual method returns FrameworkElement instance that will represent the label while the GetLableContent method returns the label at the specified index.

public class PieLabelStrategy : ChartSeriesLabelStrategy
    {
        private string format = "{0}\n{1} ({2:P2})";

        public PropertyNameDataPointBinding Binding { get; set; }

        public override LabelStrategyOptions Options
        {
            get { return LabelStrategyOptions.Content | LabelStrategyOptions.DefaultVisual; }
        }

        public PieLabelStrategy()
        {
        }

        public override FrameworkElement CreateDefaultVisual(DataPoint point, int labelIndex)
        {
            var textBlock = new TextBlock()
            {
                Foreground = new SolidColorBrush(Colors.White),
                FontSize = 14.667 };
            return textBlock;
        }

        public override object GetLabelContent(DataPoint point, int labelIndex)
        {
            if (point == null || labelIndex < 0)
            {
                return base.GetLabelContent(point, labelIndex);
            }

            return string.Format(this.format, Binding.GetValue(point.DataItem), ((PieDataPoint)point).Value, ((PieDataPoint)point).Percent / 100);
        }
    }

Telerik does provide PieLabelStrategy sample, and I just modified it a little bit to provide my own label and FrameworkElement.

                /// <summary>
		/// Creates a <see cref="T:Windows.UI.Xaml.FrameworkElement"/> instance that will
		/// represent the label for the provided data point.
		/// </summary>
		/// <param name="point">The data point a label is needed for.</param>
		/// <param name="labelIndex">The index of the label. More than one label is supported
		/// per data point.</param>
		public virtual Windows.UI.Xaml.FrameworkElement CreateDefaultVisual(Telerik.Charting.DataPoint point, int labelIndex) {
return null;
}

		/// <summary>
		/// Gets the content for the label at the specified index, associated with the provided
		/// data point.
		/// </summary>
		/// <param name="point">The data point the label is associated with.</param>
		/// <param name="labelIndex"></param>
		public virtual object GetLabelContent(Telerik.Charting.DataPoint point, int labelIndex) {
if (point != null)
{
return point.Label;
}
else
{
return null;
}
}

You can download the full source code here. I include both Pie Chart and Bar Chart samples into one project with the top app bar buttons (which I used Syncfusion Metro Studio to create buttons) to navigate between two sample. Enjoy coding!

image

image

image

Connect your Metro(??) style app to LinkedIn (via OAuth 1.0a)

**NOTE: For new OAuth 2.0, please read this post**

OAuth is a de facto standard for authorization. The protocol enables applications to share their private resources with other applications such as web, desktop, or mobile applications without having to share usernames or passwords. You can learn more about the protocol which has several versions from the following links:

In this post, I wrote a simple metro style app that consumes Linkedin information. (I know that metro is now a bad word, but windows 8 UI style app sounds too verbose).

LinkedIn is using a strict OAuth 1.0a and requires HTTP Header-based Authorization. The best resources that should help are LinkedIn OAuth: Zero to Hero slideshare by Taylor Singletary and simple oAuth C# working sample. Before we start coding, let’s talk briefly what our application (i.e., LinkedIn consumer) has to do to be able to consume LinkedIn information with user authorization.

1. Our application has to have a LinkedIn consumer key and consumer secret key. We can get it by registering your app thru LinkedIn Developer Network.

2. Our application starts talking with LinkedIn by asking LinkedIn for a request token (and request token secret key). In this step, our application has to give Linkedin, the consumer key and other OAuth information like nonce, signature method, version, and so on. The application also needs to provide a signature which is signed with the consumer secret key.

3. Beside the request token and the request token secret key, LinkedIn will also give us an authorize link which allows users to (authenticate himself/herself if necessary) authorize our application.

4. As our application is not a web application (as specified when we register our application), our application has to provide a way for user to enter a PIN code that LinkedIn gives the user in authorization process.

5. Now our application should have the request token, the request token secret key, the PIN code (oauth_verifier). Our application will use above information to request LinkedIn for an access token and an access token secret key. The application also needs to provide a signature which is signed with the consumer secret and request token secret keys.

6. Once our application has the access token and the access token secret key, then our application can make LinkedIn API call and get information from LinkedIn.

If you don’t quite understand the process above, don’t worry. Look at the code should give you better understand of how the process works.

First, let’s create a blank metro style app. I just create a one page app with several TextBox, TextBlock, and Button controls. I also include WebView control to let user authenticates and authorizes our application within our application.

image

In the code-behind page, our application will do the work by assembling messages and communicate with LinkedIn. Below is the sample code for requesting request token from LinkedIn.

        private async void getRequestToken_Click_1(object sender, RoutedEventArgs e)
        {
            string nonce = oAuthUtil.GetNonce();
            string timeStamp = oAuthUtil.GetTimeStamp();

            string sigBaseStringParams = "oauth_consumer_key=" + consumerKey.Text;

            sigBaseStringParams += "&" + "oauth_nonce=" + nonce;
            sigBaseStringParams += "&" + "oauth_signature_method=" + "HMAC-SHA1";
            sigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
            sigBaseStringParams += "&" + "oauth_version=1.0";
            string sigBaseString = "POST&";
            sigBaseString += Uri.EscapeDataString(_linkedInRequestTokenUrl) + "&" + Uri.EscapeDataString(sigBaseStringParams);

            string signature = oAuthUtil.GetSignature(sigBaseString, consumerSecretKey.Text);

            var responseText = await oAuthUtil.PostData(_linkedInRequestTokenUrl, sigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(signature));

            if (!string.IsNullOrEmpty(responseText))
            {
                string oauth_token = null;
                string oauth_token_secret = null;
                string oauth_authorize_url = null;
                string[] keyValPairs = responseText.Split('&');

                for (int i = 0; i < keyValPairs.Length; i++)
                {
                    String[] splits = keyValPairs[i].Split('=');
                    switch (splits[0])
                    {
                        case "oauth_token":
                            oauth_token = splits[1];
                            break;
                        case "oauth_token_secret":
                            oauth_token_secret = splits[1];
                            break;
                        case "xoauth_request_auth_url":
                            oauth_authorize_url = splits[1];
                            break;
                    }
                }

                requestToken.Text = oauth_token;
                requestTokenSecretKey.Text = oauth_token_secret;
                oAuthAuthorizeLink.Content = Uri.UnescapeDataString(oauth_authorize_url + "?oauth_token=" + oauth_token);
            }
        }

Now, let’s see how our application works. First, we provide our consumer and consumer secret keys and click “Get Request Token” button.

image

Next, LinkedIn should give us a request token and a request token secret key as well as an authorize url link.

image

After the link is populated, we can click the link and use the WebView control showing the LinkedIn authentication and authorization pages. After our application has been granted, LinkedIn will give an oauth verifier PIN which we can just put it in oauth_verifier textbox. In the real application, you should open the link automatically and provide some instruction, so users will know what to do.

image

image

Now we have everything that is required to request LinkedIn for an access token and access token secret key.

image

Once we have the access token and access token secret keys, we can use them to access LinkedIn API and get information.

image

Hope this sample application will help anyone who is going to write metro style application that needs to talk with LinkedIn. If you want to talk with other services, you can also look at the Web authentication broker sample which has twitter, facebook, flickr, and google services samples. I did reuse a lot of OAuth code from the above sample as well.

You can download the full source code here. I also have a similar example for Twitter here.

Enjoy coding!