Performance of Non-Zero lower bound Single Dimensional Array

Today while returning from office, I had a very good conversation with one of mine friend Sunny Raheja. We were discussing here and there and suddenly he asked to me

“Hey DJ, is there any difference in performance of single dimensional array if I don’t give lower bound as 0 or if lower bound is non-zero“

I thought for a while and replied to him tune in for my next blog post Smile

I was not very sure about the answer at that point of time so as soon as I reached home, I took CLR via C# because I was sure; I would get answer in this book.

So answer of above question goes like this,

clip_image001[4]

Single Dimensional array with Zero based index is having better performance.

clip_image002[4]

Single Dimensional array with Non Zero based index is having slow access of the array values.

To support above statement let us run below code,

clip_image004

In above code

  1. We are creating an Integer Array
  2. Size of Array is 2
  3. Lower bound is 0

On running Output we would get,

clip_image006

Now let us create an array with lower bound 1

clip_image008

In above code

  1. We are creating an Integer Array
  2. Size of Array is 2
  3. Lower bound is 1

On running Output we would get,

clip_image010

If you see the difference in both output; There is * in type of non -Zero based array. So by looking at type (*) complier knows about non-zero index array.

Since we know there is nothing called (*) in c# and CLR does not support declaration or access of variable with *.

So to access elements of non-zero based, Array’s GetValue() and SetValue() method can be used and it would reduce the performance.

I hope Sunny would be satisfied by this answer Smile with tongue out

Program.cs

using System;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {

            Array myArray;
            myArray = new string[0];
            Console.WriteLine(myArray.GetType());
            Console.ReadKey(true);

            myArray = Array.CreateInstance(typeof(string),
                      new Int32[] { 2 },
                      new Int32[] { 0 });
            Console.WriteLine(myArray.GetType());
            Console.ReadKey(true);

            myArray = Array.CreateInstance(typeof(string),
                       new Int32[] { 2 },
                       new Int32[] { 1 });
            Console.WriteLine(myArray.GetType());

            Console.ReadKey(true);
        }
    }
}

Walkthrough on Play Background Audio in Windows 7.1 [Mango] Phone

In this post, I will walkthrough to “Play Background Audio “in Mango or Window 7.1 phone. This post is fully based on Beta version. In this post, I will show how to play local media.

Step1

First let us create Windows Phone Application. To create, Open Visual Studio and select Windows Phone Application from installed template.

clip_image002

Since Background Audio playing is feature of 7.1 versions, so do not forget to select Target Version as Windows Phone 7.1

clip_image003

Step 2

Next step we need to do is to add a project for Audio Playback Agent. So right click to the solution and Add new project and from installed templates select Windows Phone Audio Playback Agent project type.

clip_image005

After adding this project, you would have two projects in solution explorer. One Audio Player Back Agent and another is Phone Application

clip_image006

 

Step 3

Since both the projects have been created, now add few music files to play. To do this right clicks on AudioPlaybackAgent project and new folder. Give desired name to this folder. In this case, I am naming newly created folder as Music.

Right click on Music folder and add existing items. Add music files to this folder.

clip_image007

After adding Music files select all the Music files and right click and open Properties

clip_image008

In Property windows you need to change Copy to Output Directory Properties to Copy if newer

clip_image009

Step 4

By now, music resources are added. Now you need to create a representation class for the songs tracks. Right click on AudioPlaybackAgent project and add a class. Give a desired name .

clip_image011

 

Track.cs


using System;
namespace AudioPlaybackAgent1
{
    public class Track
    {

        public Uri Source { get; set; }
        public string Artist { get; set; }
        public string Title { get; set; }
        public string Album { get; set; }

        public Track(Uri source, string artist, string title, string album)
        {
            Source = source;
            Artist = artist;
            Title = title;
            Album = album;
        }

    }
}


 

Step 5

Let us add required functionalities or modify default functionalities to perform various operations on Audio file.

Returning List of Songs

First you need to return List of songs. To return list of songs GetSongs() in AudioPlayer.cs class

clip_image013

Above function is returning List of Tracks.

To track the record number adds a class level global variable. Let us say we have added

clip_image014

 

Playing Song

Now we need to add a function to play a song. Create a function called Play.

 

clip_image016

  1. As Input parameter pass BackGroundAudioPlayer object
  2. Create a Track to play. As parameter you need to pass Source of the track, title, artist and album name.
  3. After creation of Track call Play () method on object of BackgroundAudioPlayer.

Playing Next Song

To play next song we need to track the current track record and increase it by 1. Once it is equal to total number of songs in list reinitialized it to 0.

clip_image018

Playing Previous Song

To play previous song we need to track the current track record and decrease it by 1. Once it is less than 0 then reinitialized it to maximum number of song in list.

clip_image020

Handling User actions

We need to handle user actions like Play, Stop, and Pause etc. For that you need to modify overridden function onUserAction . Add below switch case in onUserAction method.

clip_image021

 

Handling Play state changes

To handle Play state changes add below switch case in OnPlayStateChanged() overwritten method.

clip_image022

Finally adding all the required functions and modification AudioPlyaer.cs class would look like below

AudioPlayer.cs

 


using System;
using Microsoft.Phone.BackgroundAudio;
using System.Collections.Generic;


namespace AudioPlaybackAgent1
{
    public class AudioPlayer : AudioPlayerAgent
    {
        static int CurrentTrackPlaying = 0;
        /// <summary>
        /// Called when the playstate changes, except for the Error state (see OnError)
        /// </summary>
        /// <param name="player">The BackgroundAudioPlayer</param>
        /// <param name="track">The track playing at the time the playstate changed</param>
        /// <param name="playState">The new playstate of the player</param>
        /// <remarks>
        /// Play State changes cannot be cancelled. They are raised even if the application
        /// caused the state change itself, assuming the application has opted-in to the callback
        /// </remarks>
        protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
        {
            base.OnPlayStateChanged(player, track, playState);

            //TODO: Add code to handle play state changes
            switch (playState)
            {
                case PlayState.TrackEnded:
                    PlayNext(player);
                    break;

            }


            NotifyComplete();
        }


        /// <summary>
        /// Called when the user requests an action using system-provided UI and the application has requesed
        /// notifications of the action
        /// </summary>
        /// <param name="player">The BackgroundAudioPlayer</param>
        /// <param name="track">The track playing at the time of the user action</param>
        /// <param name="action">The action the user has requested</param>
        /// <param name="param">The data associated with the requested action.
        /// In the current version this parameter is only for use with the Seek action,
        /// to indicate the requested position of an audio track</param>
        /// <remarks>
        /// User actions do not automatically make any changes in system state; the agent is responsible
        /// for carrying out the user actions if they are supported
        /// </remarks>
        protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action, object param)
        {
            base.OnUserAction(player, track, action, param);
            switch (action)
            {
                case UserAction.Play:
                    Play(player);
                    break;
                case UserAction.Pause :
                    player.Pause();
                    break;
                case UserAction.Stop:
                    player.Stop();
                    break;
                case UserAction.FastForward:
                    player.FastForward();
                    break;

                case UserAction.Rewind:
                    player.Rewind();
                    break;

                case UserAction.SkipPrevious:
                    PlayBack(player);
                    break;

                case UserAction.SkipNext:
                    PlayNext(player);
                    break;

                case UserAction.Seek:
                    player.Position = (TimeSpan)param;
                    break;

            }

            //TODO: Add code to handle user actions through the application and system-provided UI

            NotifyComplete();
        }

        /// <summary>
        /// Called whenever there is an error with playback, such as an AudioTrack not downloading correctly
        /// </summary>
        /// <param name="player">The BackgroundAudioPlayer</param>
        /// <param name="track">The track that had the error</param>
        /// <param name="error">The error that occured</param>
        /// <param name="isFatal">If true, playback cannot continue and playback of the track will stop</param>
        /// <remarks>
        /// This method is not guaranteed to be called in all cases. For example, if the background agent
        /// itself has an unhandled exception, it won't get called back to handle its own errors.
        /// </remarks>
        protected override void OnError(BackgroundAudioPlayer player, AudioTrack track, Exception error, bool isFatal)
        {
            base.OnError(player, track, error, isFatal);

            //TODO: Add code to handle error conditions

            NotifyComplete();
        }

        /// <summary>
        /// Called when the agent request is getting cancelled
        /// </summary>
        protected override void OnCancel()
        {
            base.OnCancel();
            NotifyComplete();
        }

        private  List<Track> GetSongs()
        {
          List<Track> lstSongs=  new List<Track>()
            {
                new Track(new Uri("TujheBhulaDia.mp3",UriKind.Relative),
                                  "Ranveer Kapoor and Priyanka Chopra",
                                  "Tumhe Bhula Dia",
                                  "Anajana Anjani"),
                new Track(new Uri("AasPassKhuda.mp3",UriKind.Relative),
                                 "Ranveer Kapoor and Priyanka Chopra",
                                 "Aas Paass Khuda",
                                 "Anajana Anjani"),
                new Track(new Uri("AnajanAnajni.mp3",UriKind.Relative),
                                 "Ranveer Kapoor and Priyanka Chopra",
                                 "Anajana Anjani",
                                 "Anajana Anjani")

            };

            return lstSongs ;

        }

        private void Play(BackgroundAudioPlayer player)
        {
            var songs = GetSongs();
            var currentTrack = songs[CurrentTrackPlaying];
            player.Track = new AudioTrack(currentTrack.Source,
                                          currentTrack.Title,
                                          currentTrack.Artist,
                                          currentTrack.Album,
                                           null);
            player.Play();


        }
        private void PlayNext(BackgroundAudioPlayer player)
        {
            var songsCount = GetSongs().Count;

            if(++CurrentTrackPlaying >= songsCount)
            {
                CurrentTrackPlaying =0;
            }

            Play(player);

        }
        private void PlayBack(BackgroundAudioPlayer player)
        {

            var songsCount = GetSongs().Count;

            if (--CurrentTrackPlaying < 0)
            {
                CurrentTrackPlaying = songsCount - 1;
            }

            Play(player);
        }
    }
}

 

Step 5

Add reference of AudioPlaybackAgent1 project in Phone Application project. For that right click on Phone Application project and select Add Reference. In dialog box choose Projects tab and choose AudioPlaybackAgent1

clip_image024

Step 6

To play audio we have done all modification and added codes to AudioPlayBackAgent1 project. Now you need to create a UI in Phone application project

Create UI

  1. Add Three buttons for Play, Previous and Next
  2. Add a Text block to display Track information

MainPage.xaml


<phone:PhoneApplicationPage
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Mango Background Audio Player" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Playing Song" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel Orientation="Horizontal" Width="420" Margin="18,40,18,0" VerticalAlignment="Top">
                <Button Content="prev" x:Name="prevButton" Height="140" Width="140" Click="prevButton_Click"/>
                <Button Content="play" x:Name="playButton" Height="140" Width="140" Click="playButton_Click"/>
                <Button Content="next" x:Name="nextButton" Height="140" Width="140" Click="nextButton_Click"/>
            </StackPanel>
            <TextBlock x:Name="txtCurrentTrack" Height="75" HorizontalAlignment="Left" Margin="12,193,0,0" VerticalAlignment="Top" Width="438" TextWrapping="Wrap" />
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

 

After modifying above code user interface would look like

clip_image025

We need to handle click events. Very first add below namespace

 

clip_image026

 

 

And click event for three buttons would be fairly straight forward.

 

clip_image028

We need only to call SkipNext , SkipPrevious methods on instance of BackgroundAudioPlayer.

Handling Background player Play State changed event

First you need to register an event in the constructor of MainPage class. This event would check if playing track is not null then would display information in the text block.

clip_image030

Handling user Navigation

Since audio would be playing in the background so when user will navigate should be displayed with meaningful information. For that you need to override OnNavigatedTo virtual method.

clip_image032

 

After adding all required events eventually MainPage.xaml.cs be as below ,

MainPage.xaml.cs

 

using System;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.BackgroundAudio;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
         public MainPage()
        {
            InitializeComponent();

            BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
            prevButton.Click += new RoutedEventHandler(prevButton_Click);
            nextButton.Click += new RoutedEventHandler(nextButton_Click);
            playButton.Click += new RoutedEventHandler(playButton_Click);

        }

         void Instance_PlayStateChanged(object sender, EventArgs e)
         {
             AudioTrack  tracks = BackgroundAudioPlayer.Instance.Track;
             if (tracks != null)
             {
                 txtCurrentTrack.Text = tracks.Title + " by " + tracks.Artist;

             }
         }

        void playButton_Click(object sender, RoutedEventArgs e)
        {
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState )
            {
                BackgroundAudioPlayer.Instance.Pause();
                playButton.Content = "play";

            }
            else
            {
                BackgroundAudioPlayer.Instance.Play();
                playButton.Content = "pause";

            }
        }

        void nextButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipNext();
        }

        void prevButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipPrevious();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                playButton.Content = "pause";
                txtCurrentTrack.Text = BackgroundAudioPlayer.Instance.Track.Title +
                                 " by " +
                                 BackgroundAudioPlayer.Instance.Track.Artist;

            }
            else
            {
                playButton.Content = "play";
                txtCurrentTrack.Text = "";
            }
        }
    }
}

 

Step 7

BackGroundAudioPlayer can only play song from remote URL or file in Isolated Storage. For that you need to add a function in App.Xaml.cs

 

Adding music File to Isolated Storage

 

clip_image034

In above function points to be noted

  1. Files name are exactly same as you added in previous steps
  2. Folder name is exactly the same.
  3. Sequence of File names in string array files is exactly the same as you are returning from GetSongs() method.
  4. Call this function in constructor of App class.

App.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Windows.Resources;


namespace PhoneApp1
{
    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disable user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
            CopyToIsolatedStorage();

        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        private void CopyToIsolatedStorage()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string[] files = new string[] { "TujheBhulaDia.mp3", "AasPassKhuda.mp3", "AnajanAnajni.mp3" };

                foreach (var _fileName in files)
                {
                    if (!storage.FileExists(_fileName))
                    {
                        string _filePath = "Music/" + _fileName;
                        StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

                        using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
                        {
                            int chunkSize = 4096;
                            byte[] bytes = new byte[chunkSize];
                            int byteCount;

                            while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                            {
                                file.Write(bytes, 0, byteCount);
                            }
                        }
                    }
                }
            }
        }


        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}

 

Step 8

Now you have created a background music player. Press F5 to run the application.

clip_image035

I hope this post was useful. Thanks for reading  Smile

Billing in SQL Azure

1. Web edition databases are billed at the 1GB rate for databases below 1GB of total data or at 5GB rate for databases between 1GB and 5GB size.

2. Business edition databases are billed at 10GB increments (10GB, 20, 30, 40 and 50GB).

In a particular day billing is done on the pick DB size. To understand billing better let us take an example, suppose there is Web Edition DB with maximum size 5 GB. On a particular day if database usages are 800MB then you will be charged for 1 GB on that day. If next day DB usage increases to 2 GB then you would be charge for 5 GB. In Business edition charging window is of 10 GB.

SQL Azure introduces two dynamic management views database_usage and bandwidth_usage. These views can be used in TSQL for billing and bandwidth information.

image

If you want to calculate pricing for any particular type of Database edition probably you would have to do simple mathematical calculations.

Let us say,

R = Monthly Rate of Data base edition. Monthly rate for both web and business edition is different.

D = Number of Day in Month

N = Number of Databases

U = Unit consumption in a given day

Price for Month = (R /D)*U*N

So if

R = 10 $ per month

D = 30 days

N = 1 number of Database

U = 5 unit

Price for Day = (10/30)*1*4 = 1.34 $

TSQL to get current month prices

image

 


select sku,
    sum (
    case when sys.database_usage.sku = 'web'
            then (quantity*10/31)
        when sys.database_usage.sku = 'business'
            then (quantity*100/31)
    end ) as 'cost'
    from sys.database_usage
    where datepart(yy,time) = datepart(yy, getutcdate()) and
    datepart(mm,time) = datepart(mm, getutcdate())
    group by sku

In above SQL query

1. 100 $ is monthly charge for business edition and 10 $ is for Web Edition [Assumption]

2. Number of Days is 31

3. Query is running against Master Database.

If you want to list out different units with their edition below query can do the task

image

Above query will return time, edition and quantity.

select time,sku,quantity   from sys.database_usage    where datepart(yy,time) = datepart(yy, getutcdate()) and   datepart(mm,time) = datepart(mm, getutcdate())

Different Data Base Editions in SQL Azure

There are two Data Base Editions in SQL Azure.

image

Web Edition Relational Database includes:

  1. · Up to 5 GB of T-SQL based relational database*
  2. · Self-managed DB, auto high availability and fault tolerance
  3. · Support existing tools like Visual Studio, SSMS, SSIS, BCP
  4. · Best suited for Web application, Departmental custom apps

Business Edition DB includes:

  1. · Up to 50 GB of T-SQL based relational database*
  2. · Self-managed DB, auto high availability and fault tolerance
  3. · Additional features in the future like auto-partition, CLR, fanouts etc
  4. · Support existing tools like Visual Studio, SSMS, SSIS, BCP
  5. · Best suited for Saas ISV apps, custom Web application, Departmental apps

While creating Database in SQL Azure, we can choose either of two options

clip_image003

If we choose Web Edition then Maximum size we can choose is 5 GB

clip_image004

If we choose Business Edition then Maximum size we can choose is 50 GB

clip_image005

Billing scheme for both edition is different. 

  1. 1. Web edition databases are billed at the 1GB rate for databases below 1GB of total data or at 5GB rate for databases between 1GB and 5GB size.
  2. 2. Business edition databases are billed at 10GB increments (10GB, 20, 30, 40 and 50GB).

In a particular day billing is done on the pick DB size. To understand billing better let us take an example, suppose there is Web Edition DB with maximum size 5 GB. On a particular day if database usages are 800MB then you will be charged for 1 GB on that day. If next day DB usage increases to 2 GB then you would be charge for 5 GB. Whereas in Business edition charging window is of 10 GB.

Windows Phone 7.1 [Mango] Beta released

clip_image001

I’m pleased to announce that the beta release of the Windows Phone Developer Tools that support Mango will be available for download today: Matt Bencke General Manager, Windows Phone Developer and Marketplace Experiences

Note: I took above image and statement from http://windowsteamblog.com

This was one of the most waited releases. You can download it from here.

On successfully installed Mango on your system, you will get below project templates under Silverlight for Windows Phone tab

clip_image003

You can choose target window version as well. Mango version is 7.1  Smile

clip_image004

New Features are as follows

1. New Back ground processing.

I am going to love this feature most. Now you can download a file in background while other application is running on foreground. It was not the case with WebClient

2. New Profiler and Emulator for testing

clip_image005

3. Location support

clip_image006

4. Silverlight 4.0 and integration of XNA with Silverlight 4.0 for better gaming experience

5. IE 9 as browser

clip_image007

6. Socket for communication

7. Local SQL for Structured  Data structure

8. Fast Application switching etc

If you want to work with demo code sample, You can go here

For learning in detail go here

Presented at Microsoft Mondays

On 16th May 2011, I presented at Microsoft Mondays program.

About Microsoft Monday: This is a program in between Microsoft and Mahindra Satyam. All the participants were from Mahindra Satyam

Topic: WCF REST and DATA Services

Time: 11 am to 1 pm

Date: 16th May 2011

Location: Virtual Training [Taken from Microsoft Pune office]

Demo Covered:

1. Creating first WCF REST Service

2. Exploring various hosting options.

3. Managing different type of Data.

4. Working with JSON type of Data in REST Services

5. Consuming REST in Windows7 Phone , Silverlight , Managed client

6. Working with media type in REST [Images]

7. Performing CRUD operation from Silverlight client using REST Services

8. Creating first WCF Data Services

9. Different URI options in WCF Data Services

10. Consuming in Managed Client.

All PPT can be downloaded from DOWNLOAD Section of my Blog and all the posts on REST can be read here

WCF REST Service with JSON Data

In this post I will show you working with WCF REST Service with JSON type of Data. I will discuss both POST and GET operation on data type JSON .

Creating Service

I have written much post on creating basic WCF REST Service. Please refer them if required.

WebGet Method

Let us create a Get method in WCF REST Service returning JSON type of Data. To return JSON type of data from WCF REST Service, we need to explicitly define message format as JSON in WebGet

clip_image002

In above GetMessageasJSON service

1. RequestFormat is of JSON type

2. ResponseFormat is of JSON type.

3. Above method is returning a string.

WebInvoke Method

Create one more method in WCF REST Service to POST JSON  Data

clip_image004

In above GetMessageasJSON service

1. RequestFormat is of JSON type

2. ResponseFormat is of JSON type.

3. Above method is returning an object of custom class Student.

4. Method is POST

5. Input parameter is an object of custom class Student.

Student is custom class and should be exposed as Data Contract. At client side all the custom classes can be distributed as a separate dll.

Eventually Service and Student class is as below ,

IService1.cs


using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace JQueryWCFREST
{

[ServiceContract]
public interface IService1
{

[OperationContract]
[WebGet(UriTemplate="/GetJOSNMessage",
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
String GetMessageasJSON();

[OperationContract]
[WebInvoke(UriTemplate = "/UplaodData",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Student GetUpdatedStudent(Student s);
}

[DataContract]
public class Student
{
[DataMember]
public string RollNumber { get; set; }
[DataMember]
public string Name { get; set; }
}
}

Service implementation is as below,

Service1.svc.cs


using System;

namespace JQueryWCFREST
{

public class Service1 : IService1
{
public String GetMessageasJSON()
{
return "Hi , I am JOSN DATA ";
}

public Student GetUpdatedStudent(Student s)
{
s.Name = "I have Updated Student Name";
return s;
}
}
}

Hosting Service

Hosting of JSON WCF REST Service can be done in exactly the same way as of default XML WCF REST Service.

Consuming Service

To call above service from ASP.Net or any Managed application, we will have to use below references.

clip_image006

Performing Get Operation

At the client side usual download of data with WebClient will do the work. To De Serialize data, we can use DataContractJSONSerializer

clip_image008

In above method,

1. Data is being downloaded as stream using WebClient

2. De Serialized data using DataContractJSONSerializer

Performing POST Operation

clip_image010

In above method,

1. POST operation is being performed using WebClient

2. Data is being serialized to JSON type using DataContractJsonSeeializer

For reference client side code to perform operation against JSON type WCF REST Service is as below,

Program.cs


using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using JQueryWCFREST;

namespace JSONClient
{
class Program
{
static void Main(string[] args)
{
#region Getting JOSN Data
WebClient proxy = new WebClient();
byte[] data = proxy.DownloadData( "http ://localhost:38395/Service1.svc/GetJosnmessage)
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();
Console.WriteLine(result.ToString());
Console.ReadKey(true);

#endregion

#region Uploading JOSN Data
Student student = new Student{Name ="Dhananjay",RollNumber ="9"};
WebClient Proxy1 = new WebClient();
Proxy1.Headers["Content-type"] = "application/json";
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(Student));
serializerToUplaod.WriteObject(ms, student);
data = Proxy1.UploadData(http://localhost:38395/Service1.svc/UplaodData", "POST", ms.ToArray());
stream = new MemoryStream(data);
obj = new DataContractJsonSerializer(typeof(Student));
var resultStudent = obj.ReadObject(stream) as Student;
Console.WriteLine(resultStudent.RollNumber+" " + resultStudent.Name);
Console.ReadKey(true);

#endregion

}
}
}

On running output expected is,

clip_image012