Friday, May 27, 2011

Mango : DeviceNetworkInformation in Windows Phone 7.1

Hope you already downloaded Windows Phone 7.1 Mango Beta Tools as I mentioned in my last post here

Today I am going to talk about DeviceNetworkInformation API with small demo. This API is exposed with the new toolset and very useful especially when you need to check various things related to Mobile Operator. Let’s have a look in more depth about this API.

What this API does ? :

This API helps you to identify and know more about Network capabilities by which one can identify Availability of Network, Availability of Roaming Data and WiFi Network etc. How to make use of this in your Windows Phone 7.1 app its totally your call and it is dependent on your Application Requirement. So I will leave this “Where to use” part to you.

Structure of DeviceNetworkInformation API :

DeviceNetworkInformation is a static class insider Microsoft.Phone.Net.NetworkInformation namespace having few boolean properties and ResolveHostNameAsync method and NetworkAvailabilityChanged. Since all the properties are static you don’t need to create instance. Properties are

  • CellularMobileOperator
  • IsCellularDataEnabled
  • IsCellularDataRoamingEnabled
  • IsNetworkAvailable
  • IsWiFiEnabled

It resides in Microsoft.Phone.dll(v2.0.50727) which you can find in WindowsPhone71 directory.

General Structure is like this :

namespace Microsoft.Phone.Net.NetworkInformation
{   
    [SecuritySafeCritical]
    public static class DeviceNetworkInformation
    {
        public static string CellularMobileOperator { get; }
        public static bool IsCellularDataEnabled { get; }    
        public static bool IsCellularDataRoamingEnabled { get; }     
        public static bool IsNetworkAvailable { get; }      
        public static bool IsWiFiEnabled { get; }

        public static event EventHandler<NetworkNotificationEventArgs> NetworkAvailabilityChanged;

        public static void ResolveHostNameAsync(DnsEndPoint endPoint, NameResolutionCallback callback, object context);
        public static void ResolveHostNameAsync(DnsEndPoint endPoint, NetworkInterfaceInfo networkInterface, NameResolutionCallback callback, object context);
    }
}
Now Let’s build one small App on top of this API, So here are steps :

How it will look like :

NetworkInfo

*Please note that Images used in this post are from Internet found during regular search, Images have their respective copyrights and they are part of this post just for demo purpose.

XAML :

<!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Explore .NET With Vikram Pendse" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Network Info" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Image Source="GSMNetwork.jpg" Opacity="0.3" Height="607" HorizontalAlignment="Left" Margin="-2,-6,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="458" />
            <TextBlock FontWeight="Bold" x:Name="txtMobileOptr" Height="30" HorizontalAlignment="Left" Margin="0,104,0,0" VerticalAlignment="Top" Width="450" />
            <TextBlock FontWeight="Bold" x:Name="txtNetworkAvail" Height="30" HorizontalAlignment="Left" Margin="0,158,0,0" VerticalAlignment="Top" Width="450" />
            <TextBlock FontWeight="Bold" x:Name="txtCDEnable" Height="30" HorizontalAlignment="Left" Margin="0,212,0,0" VerticalAlignment="Top" Width="450" />
            <TextBlock FontWeight="Bold" x:Name="txtRoaming" Height="30" HorizontalAlignment="Left" Margin="2,269,0,0" VerticalAlignment="Top" Width="448" />
            <TextBlock FontWeight="Bold" x:Name="txtWiFi" Height="56" TextWrapping="Wrap" HorizontalAlignment="Left" Margin="0,325,0,0" VerticalAlignment="Top" Width="450" />
            <Image x:Name="imgWiFi" Height="150" HorizontalAlignment="Left" Margin="228,431,0,0" Stretch="Fill" VerticalAlignment="Top" Width="200" />
        </Grid>

So on designer layout in Visual Studio it will look like this :

NetworkDesign

C# Code :

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
     GetDeviceNetworkInformation();
}

public void GetDeviceNetworkInformation()
{
     txtMobileOptr.Text = "Your Mobile Operator is : " + DeviceNetworkInformation.CellularMobileOperator.ToString();
            
     if (DeviceNetworkInformation.IsNetworkAvailable)
        txtNetworkAvail.Text = "Network is Available";
     else
        txtNetworkAvail.Text = "Network is Not Available";

// Similarly you can get and set other properties to Textblocks

}

Output :

NetworkInfo

NetworkZoom

Now if you need to make it more Jazzy you can put icons and make it more attractive and friendly. For example, I have done for Wi Fi, I am showing Wi Fi enable – disable by displaying PNG file like this :

NetworkWiFiEnable          NetworkWiFiDisable

I know the images used here are bit dull,but idea is to show how you can enhance the app by such ideas and code for this is very simple like this :

if (DeviceNetworkInformation.IsWiFiEnabled)
{
    txtWiFi.Text = "You are connected to WiFi Network";
    Uri uri = new Uri(@"wificon.png", UriKind.Relative);
    ImageSource imgSource = new BitmapImage(uri);
    imgWiFi.Source = imgSource;
}
else
{
    txtWiFi.Text = "You are not connected to WiFi Network,Check your WiFi Settings and Retry";
    Uri uri = new Uri(@"wifidiscon.png", UriKind.Relative);
    ImageSource imgSource = new BitmapImage(uri);
    imgWiFi.Source = imgSource;
}

So this is how you can make use of DeviceNetworkInformation in your Windows Phone 7.1 Application, As I mentioned earlier that how you will use this is totally your choice and depends on business scenario, But next time when you need all Network related information inside your app, you don’t need to search, The solution is already with you with this API. See you then with more good stuff on Mango aka Windows Phone 7.1 in coming posts.Keep buzzing over emails and in comment section as usual.

Vikram.

Thursday, May 26, 2011

Mango : What’s new in Windows Phone 7.1

Just back from lovely Microsoft MVP Open Day 2011 at Hyderabad,Andhra Pradesh in India conducted at Microsoft India Development Center (Microsoft’s next biggest center after Redmond and some amazing people work here !) We always see and talk about success stories of Redmond people, but take a time and see and check out what an amazing contribution Indian folks doing at Microsoft IDC. Hats off ! and hearties congratulations to them and Microsoft Windows Phone 7 Team.

Group Photo @ MS IDC

[Mighty Indian MVPs at Microsoft India Development Center,India]

Whatsoever ! Mango is King of all fruits and India is the only best place in universe to get it ! Hope you can read between the lines !

Mango :

Codename “Mango” is a revolutionary and major update of Windows Phone 7 Platform.

The Windows Phone team announced the release of the Windows Phone Developer Tools for Mango yesterday. We all eagerly waiting for Mango and finally it comes to us as Beta Tools in first step.

Download Tools :

From Web :

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=77586864-ab15-40e1-bc38-713a95a56a05&displaylang=en

ISO :

http://go.microsoft.com/fwlink/?LinkID=219401

Few very important points to remember :

  • As per installation notes:Windows Server®,Windows® XP and Virtual machines are not supported.
  • Visual Basic is now fully integrated into Windows Phone Developer Tools 7.1 Beta so you must uninstall Visual Basic for Windows Phone Developer Tools 7.0 if you have installed already.
  • Windows Phone 7.1 Tools will allow you to create Windows Phone 7.0 Apps, Target platform feature like we have in Silverlight, Check this :

Platform

  • Application created with Windows Phone 7.1 will not run on NoDo Device, so hold your breath till the actual update hits the phone,Emulator is so powerful so keep your pain points aside.
  • It is not so recommended to use Windows Phone 7.1 Tools to create Windows Phone 7.0 apps for Marketplace.It may break badly.
  • Installed bits might hit Expression Blend 4, I am personally investigating this issue so not much I can share at the moment.See this what happened to my Blend 4 :

Blend4_Mess_Mango

I am running Windows 7 x64 Ultimate with Visual Studio 2010 Ultimate along with SP1, I did not uninstalled anything and seems that my Silverlight 5 Beta bits are working well, I will share more to you if I find something is breaking up. But with this info I think you are good to go.

What’s New in Mango :

Some of the top features :

  • Silverlight 4 as core platform
  • IE9 web browser control
  • Networking / sockets for communications
  • Local SQL database for structured storage
  • Live Tile enhancements: use of back of tiles and ability to
  • update Live Tiles locally
  • Deep linking into apps from notifications and Live Tiles
  • Background processing
  • New profiler and emulator for testing
  • Use of Silverlight + XNA together
  • Additional sensors; direct camera access, compass & gyro
  • Fast application switching
  • Access to calendar and contacts

There is actually a big list and instead of giving you more neck pain to scroll and read, I will suggest you to visit following link of MSDN where all new information about Windows Phone 7.1 is available.

http://msdn.microsoft.com/en-us/library/ff637516.aspx

Already downloaded tools and want to check stuff ? :

This is my first post on Mango so I will be dropping few good examples here from next post, till the time if you want you can check few cool Code samples on Windows Phone 7.1 here :

http://msdn.microsoft.com/en-us/library/ff431744%28v=VS.92%29.aspx

Some New Project Templates with Windows Phone 7.1 :

Check this out new templates as :

  • Windows Phone 3D Graphics Application
  • Windows Phone Audio Playback Agent
  • Windows Phone Audio Streaming Agent
  • Windows Phone Task Scheduler Agent

Mango_For_FB

I will soon take a stab at each one and explain it to you what each one does and when to use what template.

New Look of Windows Phone 7.1 Emulator :

The new emulator is amazing and gives feel of Mango Update on Phone, In coming days I will be surely giving more insights on that but to start with take a look how it helps you to test your location based apps and Acceleronometer apps :

1. Acceleronometer Support :

Emulator1

2. Location Support :

Emulator2

So that's all I have to say in this quick post on Mango aka Windows Phone 7.1 Beta Tools, Hope you got the glimpse of what coming in big way ahead, I will be posting few good stuff in coming days, Till the time you guys download bits and get ready,I’ll be back !

Vikram.

Sunday, May 15, 2011

Multiple Window Support in Silverlight 5

So much talks about Multiple Window support in Silverlight 5 which made available in beta version around various Silverlight blogs and forums.I am putting my few thoughts here on this feature.

The basic idea behind this feature is host stuff across multiple windows,remember the good old days of MDI forms in Visual Basic 6 days? well its not I will say replica of but its of similar kinds.

The bookish meaning of Multiple Window support is :

The ability to create an application that can have additional top level windows other than the single window that's opened for a Silverlight Out of Browser application

Game starts with namespace System.Windows.Window and it looks like following :

#region Assembly System.Windows.dll, v4.0.30319
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v5.0\System.Windows.dll
#endregion

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;

namespace System.Windows
{
    // Summary:
    //     Represents an out-of-browser application window.
    public sealed class Window : DependencyObject
    {

        //… some code

     }

}

It’s a sealed class inherited from Dependency Object and as class level xml comment shouts, its an OOB and Work only in Elevated Trust Applications.

elevtrust

You can achieve Multiple Window like this :

Window tearOffWindow = new Window();
//Once a Window has been instantied, one can
//set its initial property values    

tearOffWindow.Height = 300;
tearOffWindow.Width = 400;
tearOffWindow.Top = 24;
tearOffWindow.Left = 30;
tearOffWindow.Title = "Tear Off Stack Panel";
tearOffWindow.Content = mnp.movUIElement; /*Set Content to someFrameworkElement Obj*/;

//Once all the initial properties have
//been set, set the Visibility property
//to 'Visible' to display the Window
tearOffWindow.Visibility = Visibility.Visible;

It will look something like this :

TearCapture

Like this you can create instance of window and put stuff on that whatever you feel appropriate to your application or per requirement. Note that once you close main window another window instance will be closed as well. Its very ideal feature for many Line of Business applications as well. So you should give try to this one today. I know there will be lot more can be done with this,but for the moment I am restricting myself,In upcoming posts I will share more with some demo apps and how you can use this feature at best.

Issues I observed with Multiple Window :

1. Background color/Background property Mystery :

While working I came across that there does not exists any Background property via code which I find strange personally.

TearOff_Error

2. “Black” Background color :

If you do not set any background color to your UIElement which you are going to tear off,It applies Black color automatically. Some videos and blogs says this is “By default” or “Automatic” but I don’t believe on this,how it can be “by default” since if I don’t apply any background color it should be whitish as usual.This I personally find very strange.

BugTearCapture

3. Setting WindowStyle as “BorderlessRoundCornersWindow” :

Though it works for parent window well,I will not say this as bug or limitation but if its not expected then they should have thrown compile time error to prompt that it cannot be mixed with Multiple Window support feature but it throws exception here  :

TearOff_Border_Error

Well, despite of these small issues which I think either might be resolve in coming bits or can be carry ahead ignoring but I feel that I should share this with you so that while designing app based on this Multiple Window feature you will be in good position with possible problems and solution.

I will soon post more deep dive article with some more good examples and features but now my mind is in Hyderabad city where 100+ South Asian MVPs are coming together for Microsoft MVP Open Day 2011 .. I will be traveling there for few days..So see you soon with more good stuff from May end onwards.

Vikram.

Friday, April 22, 2011

Silverlight 5 : Multiple Click Support aka ClickCount

In the last article I spend some time with you in discussing some Text related enhancements for Developers in Silverlight 5. Today I am going to discuss one more feature of Silverlight 5 in this short post.

Requirement : We need a mechanism to identify count of multiple mouse clicks made by user.

Scenario : Some over enthusiast end users,if the transaction/process is not happening then they always hit button/any other UI control with high enthusiasm (or sometimes anger) several amount of time, Some time these unnecessary clicks becomes headache and sometimes it is useful to trigger some business function as well. So there is good side and bad side of this.

What Silverlight 5 is offering to us? : Silverlight 5 bits are now giving support/mechanism to identify Multiple Clicks made by user.

How it does that? : Inside your class MouseButtonEventArgs which is sealed,exposes one public property of type Integer like this :

ClickFunda

This ClickCount property gives us number of hits made by user via Mouse.

Cool..any sample ? : Here you go !

XAML :

<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="MouseCount" FontSize="20" Margin="5,5,5,5" MouseLeftButtonDown="MouseCount_MouseLeftButtonDown" />   </Grid>

C# :

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
     MouseCount.Text = "This Place will show how many times you play with Mouse !";
}

private void MouseCount_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
           // Checks the number of clicks.
           if (e.ClickCount == 1)
           {
               // Single Click occurred.
               MouseCount.Text = String.Empty;
               MouseCount.Text = "You clicked Mouse Once !";
           }

           if (e.ClickCount == 2)
           {
               // Double Click occurred.
               MouseCount.Text = String.Empty;
               MouseCount.Text = "You clicked Mouse Twice !";
           }

           if (e.ClickCount >= 3)
           {
               // Triple Click occurred.
               MouseCount.Text = String.Empty;
               MouseCount.Text = "You clicked Mouse more than 2 times !";
}}
Remember e.ClickCount is a key ! it will give you number of clicks.

Will it work? : Yes ! Here is the output starting from no click to more than 2 clicks …

ItemClick

ItemClick1

ItemClick2

ItemClick3

Wait ! All that glitters is not Gold !! :

My dear friend and fellow Silverlight MVP Kunal Chowdhury written a quick article on “Issues with Multiple Clicks in Silverlight 5”, so read that here and get to know how this e.ClickCounts make life bit difficult for Developers like you and me.

What’s the Problem ? – Debugging ! :

If you observe the code snippet above and article by Kunal which I shared above,you will find that there is a great trouble to your brain while debugging since despite of e.ClickCount > 1 still it always hits e.ClickCount = 1 condition and comes out of the game and Game is over for us since we really can’t debug and see the stuff for e.ClickCount > 1 and here we see the sad story !

Is it a Bug? what can be done to avoid this ? :

Well, As a MVP I see it as functional issue rather than calling it as Bug since functionality is working but issue is coming only while debugging so I feel little awkward to call it as Bug !

Condition to your Breakpoint is the only option I find it suitable at this particular moment unless someone from Microsoft don’t come up with something better to avoid this debug issue. So if I want to check / debug and see some stuff for e.ClickCount then how will I achieve this? .. well all you need to do is just right click and click on Condition like this :

ItemCondition1

ItemCondition2

ItemCondition3

Above screen shows how easy is our life ! So now be ready to debug all that e.ClickCount > 1 stuff which was giving you trouble earlier. Remember that even for Switch..Case it’s the same issue so don’t be under impression that problem will not occur with Switch..Case.

One you done with adding condition, it will be hitting your breakpoint and executing appropriate condition on basis of e.ClickCount value and you can see that output like this :

ItemCondition4

So this is bit schoolish solution but it works in such tricky conditions and we can survive for the time being.

Well,Take the positive part of this wonderful feature and how it is helpful in real business scenario, I personally still have no clue if this is officially marked as “Bug” or not,but this is what came to my observation when I was playing with the bits, I hope in coming RTW bits something will come up for this, Well enough for today and some more such nice features and funny tricky solutions and scenarios are coming up in my upcoming posts,So stay tuned !

Vikram.

Wednesday, April 20, 2011

Silverlight 5 : Improvements in Text

I hope you must have installed Silverlight 5 Beta bits on your machine and wondering what’s new you got in those bits.Well, there are lots of new things hidden inside which are worth exploring.I am doing the same with equal passion and enthusiasm.

Today in this little blog post I am going to talk about some smart improvements for Text.

Character Spacing :

CharacterSpacing is a property of type Integer (System.Int32),If you refer official Silverlight 5 documentation,you will find the definition of CharacterSpacing as :

Gets or sets the distance between characters of text in the control measured in 1000ths of the font size

Let me add some more information here as well since we are talking about stuff from Document. For those who are new to Silverlight 5 documentation you will see following icon :

txticon

In front of many properties you will see such icons, well left side of the icon represents the property as Public property and right side of the icon represents that the property is supported by Silverlight on Windows Phone. Well,coming back to the topic, I hope you got the idea what CharacterSpacing does for you. Its basically help you to manage and have full control over character space of your text in your Silverlight application. Here is how it looks like :

TextImprove1

You can see how the Text gets compressed and expand on varying the CharacterSpacing. Here is a piece of XAML which you can play and checkout how exactly it will look in your application when you implement CharacterSpacing.

XAML :

<Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
</Grid.RowDefinitions>
<TextBlock FontSize="12" x:Name="myTxt" Grid.Row="0" >
            Silverlight हे सर्व वेब-ब्राउजर वर चालणारे Plug-in आहे, तसेच हे विविध Operating Systems वर ही वापरता येते.
</TextBlock>
<Slider x:Name="mySlide" Grid.Row="1" Maximum="400" Minimum="-400" SmallChange="50" ValueChanged="mySlide_ValueChanged" />

C# Code :

private void mySlide_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    myTxt.CharacterSpacing = Convert.ToInt32(mySlide.Value);
}

Note : CharacterSpacing property can be set from XAML as well.

..and here is the output :

txt1

txt2

txt3

In each of the output shot you can see how the character spacing varies and thus gives you full control over text in your Silverlight 5 Application.Well how you are going to use in your business scenario it upto you only.

RichTextBoxOverflow,Multi-column and Linked text :

Many times we see that inside application for TextBoxes or RichTextBoxes we have massive scrollers since the content is big and there is no facility to handle overflow of the content in the given Text container. So if you see our normal Multicolumn magzines, its sometimes becomes difficult to put Text in that Multicolumn magazine kind of fashion since its difficult to manage flow of text.

With Silverlight 5 you can create wonders, All you need is to set OverflowContentTarget Property and you will be able to handle all linked,multicolumn text without any much heavy efforts.The official Silverlight 5 documentation describes OverflowContentTarge as :

Gets or sets the RichTextBoxOverflow that will consume the overflow content of this RichTextBox.

Let me show you this via piece of XAML here :

<StackPanel Width="400">
        <RichTextBox x:Name="MasterRTB" Width="300" Height="50" OverflowContentTarget="{Binding ElementName='overflowContainer'}">
            <Paragraph>
                    Silverlight हे सर्व वेब-ब्राउजर वर चालणारे Plug-in आहे, तसेच हे विविध Operating Systems वर ही वापरता येते, गेली अनेक वर्षे Microsoft ASP.NET च्या मदतीने आपण अनेक प्रकारचे प्रकल्प कार्यान्वित करत आलो आहोत, काही वर्षांपूर्वी त्याला AJAX ने ही चांगलाच हातभार लावला आहे, आता त्याच धर्तीवर Microsoft आपल्याला Silverlight बरोबर एक पाउल पुढे नेत आहे.
             </Paragraph>
        </RichTextBox>
<RichTextBoxOverflow x:Name="overflowContainer"/>
</StackPanel>

As you can see that I have big chunk of data in <Paragraph> tag and if I look at Dimensions of RichTextBox, there is a fear that either I will loose some of my Text just because it will not fit in or I need to put scrollbar and other stuff. Instead of that now what we can do in this particular example is to add one more control <RichTextBoxOverflow> (You can have multiple RichTextBoxOverflow Controls or even you might want to form chain of those controls which is possible) and set OverflowContentTarget of the base Rich Text box. This will point at where your extra overflow Text should go and then it will flow freely in another text container. Hence with such implementations you can achieve Multicolumn text requirements as well. Here is a small output of above XAML where you can clearly see how text is flowing smoothly across those Rich Text containers.

RTFM

Well, I hope you got these two small features introduced in Silverlight 5 Beta. With this you can move ahead and create PoCs where you can test the capability and power of these features with high design quality keeping in mind. With this I end this post here and by the time you finish exploring this feature I will be back with more new features of Silverlight 5. In coming articles we will also discuss the pain points of each features and how we can address those issues. So see you very soon !

Vikram.

Thursday, April 14, 2011

Silverlight 5 : A step ahead from Microsoft

Hello folks, Hope you all had fun at Mix 11 keynote online/offline. Well almost 10+ hours back Scott Gu announced availability of Silverlight 5 Bits for Public which was formally announced earlier. I have composed few post last night, Just giving final touches, till the time I want you people to get sync with me by downloading Silverlight 5 bits so that we can enjoy it together !

silverlight

What Should be your First Step ? :

Download Silverlight Bits,Videos and necessary documentation from here :

http://www.silverlight.net/getstarted/silverlight-5-beta/

Should I migrate my Silverlight 3/4 Apps to Silverlight 5 ? :

I personally will not recommend that. Silverlight 5 is in Beta right now,so its better to create some smart PoCs and test it out inside out then you can have migration plan in place.

Will these bits will cause trouble to my current Silverlight/WP7/Expression setup ? :

You can run these new bits can parallel without tampering anything from earlier installations. Installations are smooth and straight forward, No complex steps involved.There is a Runtime for Mac OS is made available, check on the link I mentioned above.

What should I have as pre-requisite to go ahead with Silverlight 5 ? :

From tooling perspective, You need to have Visual Studio 2010 SP1,If you don’t have that, please get it today from Microsoft site. Beside that if you know XAML and C# fair enough, it will be smooth learning for those who are going to learn Silverlight 5,I mean to say fresh people to Silverlight Technology.

Silverlight is Core platform for Windows Phone 7, So with this Silverlight 5 anything got added to Windows Phone 7 toolkit ? :

What Microsoft released yesterday was totally to do with Web and OOB Silverlight, There were several announcements made by Microsoft for Windows Phone 7 including Mango update,but this bits have nothing directly to do with that. I will let you know about that in a separate post later.

What am I going to see here on this Blog in coming days ? :

Tons of good stuff including Silverlight 5,Windows Phone 7 and Silverlight 5 + Some third party stuff (Remember my Balder post for Windows Phone 7,Some more coming on the same line).

I will initially going to take a stab at new Silverlight 5 features and then I will take them each one deep dive like I try to do always.

So download bits today from :

http://www.silverlight.net/getstarted/silverlight-5-beta/

..and stay tune for my next post coming up.

Future is Bright .. Future is Silverlight !

Vikram.

Monday, March 21, 2011

3D on Windows Phone 7 using Balder

This is not my first time to talk on 3D on Silverlight or Phone platform,In past I wrote decent amount of stuff including Kit3D,3D in Silverlight and recently I wrote 3D on Windows Phone 7 using capabilities of Silverlight framework sitting inside phone.

While surfing I came across this wonderful 3D engine for Silverlight and amazed to know that it is also available for Windows Phone 7. As usual I went ahead to try this out and as our blog’s tradition, whatever I explore I share with you people,so today I am going to do the same. Note here that,its 3rd Party and I do not have expertise over this 3D engine,so if you plan to use this for your apps in production environment for Silverlight or apps for Marketplace for Windows Phone 7, I advice you to spend more time with the bits and just don’t blindly follow.Most of the source code here what I am sharing is mostly from predefined Balder samples as I told this is very new to me as well.

You can check more on Balder at their Codeplex home :

http://balder.codeplex.com/

Once you download those Balder Bits for Windows Phone 7,you need to refer them like this :

RefBalder

ReferBalder

Note that once you start coding your XAML for Balder, Make sure you exclusively work in Code windows that having mix of design and code,why? Simple answer is with the current bits of Balder, it does not allow you to see/edit for that matter in your designer like this i.e No Design time support :

DesignerBalder

So if you see such screen like above, No need to get panic, this is normal for Balder,So even if designer not working,Code does work.So do not get panic and close project even if you see some design time errors in error list, just ignore them.

Like we have layouts like Grid, Balder provides Render layout with Balder.Execution namespace and we can add various shapes by Balder.Geometrics namespace which by default provides some basic shapes like ring and box which I am going to demonstrate here. Also it supports animation and light effects, Remember the lights from 3D Max? Omnilights etc? well, those are supported here and we can adjust them programmatically as well from code behind, Setting “x:Name” attribute will allow you to play with them via C# code.

You can associate namespace like this :

xmlns:Execution="clr-namespace:Balder.Execution;assembly=Balder"
    xmlns:Geometries="clr-namespace:Balder.Objects.Geometries;assembly=Balder"

You can simply add Ring or Box like this :

<Geometries:Box x:Name="MyBox" Dimension="5,5,5">

<Geometries:Ring x:Name="Ring"
                             Size="8"
                             Segments="30"
                             InnerRadius="6"
                             OuterRadius="8"/>

You can do further Material settings to Box like this :

<Geometries:Box.Material>
                        <Material:Material Ambient="Black" Diffuse="Green" Specular="White" Shade="Gouraud" />                                                   
                    </Geometries:Box.Material>

In Balder’s online demos, they have also added Images on Cube’s surface which you can check with more examples here :

http://www.ingebrigtsen.info/Balder/SampleBrowser/TestPage.html

Once you hit F5 you can see output like this :

BoxBalder          RingBalder

 

You can add your own background to make it more real like this :

finalBalder

With Timer, you can control camera from code behind like this :

void timer_Tick(object sender, EventArgs e)
{

           MyCamera.Position.X = x;
           MyCamera.Position.Z = z;
           MyCamera.Position.Y = y;
}

Here x,y,z you can set with Sin,Cos functions under System.Math so as to achieve various angles across space.In the exact same way you can use all above code base to your Silverlight application however bits for Silverlight (dlls of Balder) are different.But the same approach can be carried out for Silverlight.This is what I like most about Balder.I have uploaded a small video on this like how Balder output looks on Emulator once you have Animation+Objects+Lights in place,check this out :

3D on Windows Phone 7 using Balder

What I have shown I know is very basic,but this will be a good start to you to dig more into Balder. Balder is very much powerful and have lot of potential, I am in process of creating much more interesting stuff with it,but right now I can only share this much with you,I will be back with much more stuff as on when I make progress in the same.

So take out some time and give a try today to Balder :

http://balder.codeplex.com/

I know few of folks use XNA to create all these and may find it friendly but I want you to try this also,its worth exploring for sure.

Following result I get for above example which I am sharing with you,I am not sure about results what I got meet any kind of benchmark or not,nor I am much bother about at the moment,but here are some facts and figures for above Ring and Box 3D example :

Render Thread FPS (Average)

023-025
User Interface Thread FPS (Average) 024
Texture memory usage (Constant) 002656
Surface counter (Constant) 001
Intermediate texture count (Constant) 001
Screen Fill Rate (Constant) 00.8835

I hope you will give a try to Balder today,meanwhile I will finish up some interesting stuff and get back to you,stay tuned,soon I will be start talking on Silverlight.

Vikram.