Friday, February 11, 2011

World Cup 2011 WP7 Application

I recently posted an Windows Phone Application on marketplace. Actually, the application is combination of two of things I like – Cricket and windows phone 7!!

Cricket world Cup 2011 is about to start and its going to be full of action. Just that I don’t miss (and you don’t miss) the excitement I decided to build a WP7 app. The app has schedule of all the 49 matches and it provides all important information about each match / venue / group and even team members along with their pics. See below pics for an understanding:

Capture1Capture2Capture3Capture4Capture5

The above pics shows the app in action in both dark and light modes!!!

The application is free to download from market place. Please do share your thoughts / ideas to make it better…

Let the game begin…..

Tuesday, February 01, 2011

Windows Phone 7 Silverlight / XNA development talk

Hi,

I presented on Windows Phone 7 app development using Silverlight. Here are few pics from the event

 

I demonstrated the Visual studio, emulator capabilities/ features. An demo on Wp7 app communication with an OData Service, along with a demo on XNA app.

There was lot of curious questions; I am listing them here because these keep on popping up again and again:

1. What tools does it takes to develop Wp7 app? Are they free?

A typical WP7 app can be developed either using Silverlight or XNA. For developers, Visual Studio 2010 is a good choice as it provides an integrated development environment with lots of useful project templates; which makes the task really easy. For designers, Blend may be used to develop the UI in XAML. Both the tools are FREE (express version) to download and very intuitive to use.

2. What about the learning curve?

If you know C#, (or any other programming language), learning curve is really flat. XAML (used for UI) may be new for you, but trust me; its very intuitive. Also you can use Microsoft Blend to generate the UI (XAML) for you.

3. How can I develop /test app without using actual device? How can I be sure my app runs as expected on actual device?

The WP7 SDK comes along with an excellent emulator; which you can use for development/ testing on a computer. Later you can just change a setting and deploy the application on WP7. You will require Zune software for deploying the application on phone along with Developers key from WP7 marketplace. You can obtain key from marketplace by filling a form. The whole process for registering  is easy; just follow the steps on the site.

4. Which one should I use? Silverlight or XNA?

Use Silverlight for enterprise/ business / utility apps. Use XNA for Games app. While each platform is capable / strong and may be used in conjunction as well; The methodologies used for development in these platforms are very different. XNA works on typical Do..While loop where as Silverlight works on event based methodology.

5. Where are the learning resources? Are they free?

There is lots of stuff on WP7. Most of them are free. There is a excellent free book by Charles Petzold to download and http://www.microsoft.com/windowsphone is full of demos /todos / vidoes.

All the exciting stuff was captured live and you can view it here; in case you were not able to catch it live!! @ http://livestre.am/AUfx. My talk starts from 3:19:00 timeline in the video!!

Is there an app you miss on WP7? Do let me know about it and I may work on it for free !!!

Keep discovering. Keep is Simple. WP7.

Subodh

Monday, November 22, 2010

My VTD talk slide deck and demo code

I presented Windows Phone 7 talk on Microsoft Virtual tech Days (VTD) [22/11/2010] and here are the demo and the slide deck I referred to. Please feel free to download and refer.

It covers:

—Introduction to Windows Phone 7

—Tools for Development on Windows Phone 7

—Using Silverlight for WP7 development

—Navigation among pages of application

—WP 7 application lifecycle

—Launchers and Choosers

— Tombstoning

Fetching data from server using ODATA service (using LinqPad  4)

—Deployment model of WP7 application

—Demos

—Q & A

Here is the slides

Here is the code.

Also, your comments are welcome.

Sunday, November 21, 2010

Out from Hibernation!!

Hi, I took a sabbatical break from blogging because I resolved to spend some time with my new born son Deishen. While I learned a lot from my few month old son, including curiosity and smiling its time to get back to blogging.

Below are few pics of Deishen who inspires me always.

DSC02121 DSC02095 

And here is his video

Deishen

Enjoy!!!

Subodh

Tuesday, May 11, 2010

Enterprise Library Logging / Exception handling and Postsharp

One of my colleagues came-up with a unique situation where it was required to create log files based on the input file which is uploaded. For example if A.xml is uploaded, the corresponding log file should be A_log.txt.

I am a strong believer that Logging / EH / caching are cross-cutting architecture aspects and should be least invasive to the business-logic written in enterprise application.

I have been using Enterprise Library for logging / EH (i use to work with Avanade, so i have affection towards the library!! :D ). I have been also using excellent library called PostSharp for cross cutting aspect. Here i present a solution with and without PostSharp all in a unit test. Please see full source code at end of the this blog post.

But first, we need to tweak the enterprise library so that the log files are created at runtime based on input given. Below is Custom trace listner which writes log into a given file extracted out of Logentry extendedProperties property.

 
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;


using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;


using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;


using Microsoft.Practices.EnterpriseLibrary.Logging;


using System.IO;


using System.Text;


using System;


using System.Diagnostics;


 


namespace Subodh.Framework.Logging


{


    [ConfigurationElementType(typeof(CustomTraceListenerData))]


    public class LogToFileTraceListener : CustomTraceListener


    {


 


        private static object syncRoot = new object();


 


        public override void TraceData(TraceEventCache eventCache, string source, 


TraceEventType eventType, int id, object data)


        {


 


            if ((data is LogEntry) & this.Formatter != null)


            {


                WriteOutToLog(this.Formatter.Format((LogEntry)data), (LogEntry)data);


            }


            else


            {


                WriteOutToLog(data.ToString(), (LogEntry)data);


            }


        }


 


        public override void Write(string message)


        {


            Debug.Print(message.ToString());


        }


 


        public override void WriteLine(string message)


        {


            Debug.Print(message.ToString());


        }


 


        private void WriteOutToLog(string BodyText, LogEntry logentry)


        {


            try


            {


                //Get the filelocation from the extended properties


                if (logentry.ExtendedProperties.ContainsKey("filelocation"))


                {


                    string fullPath = 


Path.GetFullPath(logentry.ExtendedProperties["filelocation"].ToString());


 


                    //Create the directory where the log file is written to if it does not exist.


DirectoryInfo directoryInfo

= new DirectoryInfo(Path.GetDirectoryName(fullPath));



 


                    if (directoryInfo.Exists == false)


                    {


                        directoryInfo.Create();


                    }


 


                    //Lock the file to prevent another process from using this file


                    //as data is being written to it.


 


                    lock (syncRoot)


                    {


using (FileStream fs

= new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.Write, 4096, true))



                        {


                            using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))


                            {


                                Log(BodyText, sw);


                                sw.Close();


                            }


                            fs.Close();


                        }


                    }


                }


            }


            catch (Exception ex)


            {


                throw new LoggingException(ex.Message, ex);


            }


        }


 


        /// <summary>


        /// Write message to named file


        /// </summary>


        public static void Log(string logMessage, TextWriter w)


        {


            w.WriteLine("{0}", logMessage);


        }


    }


}




 



The above can be “plugged into” the code using below configuration




<loggingConfiguration name="Logging Application Block" tracingEnabled="true"


    defaultCategory="Trace" logWarningsWhenNoCategoriesMatch="true">


    <listeners>


       <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, 


Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"


traceOutputOptions="None" filter="All" type="Subodh.Framework.Logging.LogToFileTraceListener,

Subodh.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"



        name="Subodh Custom Trace Listener" initializeData="" formatter="Text Formatter" />


   </listeners>






Similarly we can use PostSharp to expose the above as cross cutting aspects as below




using System;


using System.Collections.Generic;


using System.Linq;


using System.Text;


using System.Reflection;


using PostSharp.Laos;


using System.Diagnostics;


using GC.FrameworkServices.ExceptionHandler;


using Subodh.Framework.Logging;


 


namespace Subodh.Framework.ExceptionHandling


{


    [Serializable]


    public sealed class LogExceptionAttribute : OnExceptionAspect


    {


         private string prefix;


        private MethodFormatStrings formatStrings;


 


        // This field is not serialized. It is used only at compile time.


        [NonSerialized] private readonly Type exceptionType;


        private string fileName;


 


        /// <summary>


        /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute


        /// that logs every exception flowing out of the methods to which


        /// the custom attribute is applied.


        /// </summary>


        public LogExceptionAttribute()


        {


        }


 


        /// <summary>


        /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute


        /// that logs every exception derived from a given <see cref="Type"/>


        /// flowing out of the methods to which


        /// the custom attribute is applied.


        /// </summary>


        /// <param name="exceptionType"></param>


        public LogExceptionAttribute( Type exceptionType )


        {


            this.exceptionType = exceptionType;


        }


 


        public LogExceptionAttribute(Type exceptionType, string fileName)


        {


            this.exceptionType = exceptionType;


            this.fileName = fileName;


        }


 


        /// <summary>


        /// Gets or sets the prefix string, printed before every trace message.


        /// </summary>


        /// <value>


        /// For instance <c>[Exception]</c>.


        /// </value>


        public string Prefix { get { return this.prefix; } set { this.prefix = value; } }


 


        /// <summary>


        /// Initializes the current object. Called at compile time by PostSharp.


        /// </summary>


        /// <param name="method">Method to which the current instance is


        /// associated.</param>


        public override void CompileTimeInitialize( MethodBase method )


        {


            // We just initialize our fields. They will be serialized at compile-time


            // and deserialized at runtime.


            this.formatStrings = Formatter.GetMethodFormatStrings( method );


            this.prefix = Formatter.NormalizePrefix( this.prefix );


        }


 


        public override Type GetExceptionType( MethodBase method )


        {


            return this.exceptionType;


        }


 


        /// <summary>


        /// Method executed when an exception occurs in the methods to which the current


        /// custom attribute has been applied. We just write a record to the tracing


        /// subsystem.


        /// </summary>


        /// <param name="context">Event arguments specifying which method


        /// is being called and with which parameters.</param>


        public override void OnException( MethodExecutionEventArgs context )


        {


           


            string message = String.Format("{0}Exception {1} {{{2}}} in {{{3}}}. \r\n\r\nStack Trace {4}",


                              this.prefix,


                              context.Exception.GetType().Name,


                              context.Exception.Message,


                              this.formatStrings.Format(context.Instance, 


context.Method, context.GetReadOnlyArgumentArray()),


                              context.Exception.StackTrace);


            if(!string.IsNullOrEmpty(fileName))


            {


                ApplicationLogger.LogException(message, fileName);


            }


            else


            {


                ApplicationLogger.LogException(message, Source.UtilityService);


            }


        }


    }


}





To use the above below is the unit test




 [TestMethod]


        [ExpectedException(typeof(NotImplementedException))]


        public void TestMethod1()


        {


            MethodThrowingExceptionForLog();


            try


            {


                MethodThrowingExceptionForLogWithPostSharp();


            }


            catch (NotImplementedException ex)


            {


                throw ex;


            }


        }


 


        private void MethodThrowingExceptionForLog()


        {


            try


            {


                throw new NotImplementedException();


            }


            catch (NotImplementedException ex)


            {


                // create file and then write log


ApplicationLogger.TraceMessage("this is a trace message

which will be logged in Test1MyFile", @"D:\EL\Test1Myfile.txt");



                ApplicationLogger.TraceMessage("this is a trace message 


which will be logged in YetAnotherTest1Myfile", @"D:\EL\YetAnotherTest1Myfile.txt");


            }


        }


 


        // Automatically log details using attributes


        // Log exception using attributes .... A La WCF [FaultContract(typeof(FaultMessage))] style]


        [Log(@"D:\EL\Test1MyfileLogPostsharp.txt")]


        [LogException(typeof(NotImplementedException), @"D:\EL\Test1MyfileExceptionPostsharp.txt")]


        private void MethodThrowingExceptionForLogWithPostSharp()


        {


            throw new NotImplementedException();


        }





The good thing about the approach is that all the logging and EH is done at centralized location controlled by PostSharp. Of Course, if some other library has to be used instead of EL, it can easily be plugged in. Also, the coder ARE ONLY involved in writing business code in methods, which makes code cleaner.



Here is the full source code. The third party assemblies provided are from EL and PostSharp and i presume you will find these useful.



Do let me know your thoughts / ideas on the same.



Monday, July 20, 2009

Silverlight 3.0, RIA services and MVVM

MVVM == Model View ViewModel Pattern is a MUST follow pattern in Silverlight (WPF). here is why…

Problems it solves:

•Tight coupling of layers (ex a query in the UI)

•Unit testing is hard/impossible, only functional testing is possible

•Assures codes still works correct after a change

•ViewModel

•Provides View with data model and behavior

•View will bind to ViewModel

•Wraps data access entirely

In light of new technologies like RIA services (which provides CRUD) operations out of the box it is imperative that users are tempted to overlook MVVM for sake of simplicity!!! However, the goodies MVVM brings along holds good in RIA services well… So what the roadmap to have MVVM , silverlight and RIA services???? I havnt found much on google (& BING!!!) but here is my humble take on that.

I plan to write more in my forthcoming blog but here is one example using nInject.

nInject is lightweight DI framework and is helpful in injecting VIEWMODEL right into XAML code!!! here is how…

   1: Title="Home"



   2:   DataContext="{Binding Path=HomeViewModel, Source={StaticResource serviceLocator}}"



   3:   Style="{StaticResource PageStyle}">




Notice … the datacontext (VIEW MODEL) is injected using ServiceLocator!! the service locater is itself a resource defined in APP.xaml





   1: Application   



   2:   x:Class="SilverlightApp.App"



   3:   xmlns:local="clr-namespace:SilverlightApp.ViewModel"



   4:   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



   5:   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">



   6:  



   7:   <Application.Resources>



   8:   



   9:     <ResourceDictionary>



  10:       <ResourceDictionary.MergedDictionaries>



  11:         <ResourceDictionary Source="Assets/Styles.xaml"/>



  12:       </ResourceDictionary.MergedDictionaries>



  13:     </ResourceDictionary>



  14:         <local:ServiceLocator x:Key="serviceLocator" />



  15:     </Application.Resources>



  16:  



  17: </Application>




and Ninject code for Service Locater goes like…





   1: namespace SilverlightApp.ViewModel



   2: {



   3:     using Ninject.Core;



   4:     public class ServiceLocator



   5:     {



   6:         private static readonly IKernel kernel;



   7:  



   8:         static ServiceLocator()



   9:         {



  10:             if (kernel == null)



  11:             {



  12:                 kernel = new StandardKernel(new Module());



  13:             }



  14:         }



  15:  



  16:         public HomeViewModel HomeViewModel



  17:         {



  18:             get



  19:             {



  20:                 return kernel.Get<HomeViewModel>(); 



  21:             }



  22:         }



  23:  



  24:         public static T Get<T>()



  25:         {



  26:             return kernel.Get<T>();



  27:         }



  28:     }



  29: }




 



The commands are taken care by the SLExtensions. here is how…



I will be using and blogging about the following DI … Please feel free to write more… if you have anything to add..



1. Nikhil Silverlight FX… This is really good stuff; the only thing which is “does NOT” goes down well (to most of developers) is use of customized controls. Having said that i must say, personally, i love this approach and how Nikhil keep updating it with newest stuff!!!



2. CAB(Prism): I personally think it is more opt for WPF. Having said that it also follows “injection through interface” paradigm.. which sometimes introduces too much hassles…



3. MEF. Latest from Microsoft. Very promising, however yet to mature as a tool.



4. Caliburn: Excellent tool. I found it at codeplex…



 



My plan is to retest each of the above wrt SL3.0, RIA services abd MVVM in context abd post results on this blog.. and get more tractions on the results i get to..



Keep jotting your comments…



Technorati Tags: ,,

Silverlight 3.0 – TechEd on Roads

I presented “What's new in silverlight 3.0” at Teched, Delhi on roads and got overwhelming response for it. Actually there was two events. The venue for the first event was Microsoft office, Gurgaon, Delhi. I must admit i had to change gears because most of the attendees were new to “Silverlight” itself; and i was introducing them to Silverlight 3.0 version!!

So i was back to questions like

  • Why Silverlight?
  • What silverlight means to
    • Developer
    • Architect
    • Manager
    • End user

It did generated lots of interest and my deal on capturing user attention by hatching on to the psychology made it home to most of the users. Examples i gave was as simple as making a grid rotate (flip) to use the same screen space to display more data. OR blurring the grid so that user can concentrate on more relevant information on screen…

Both of the above were, interestingly speaking examples of new features of SL 3.0…

There was also this interesting bit about “what it takes to move to SL platform” and concerns like “I felt lots of resistance from developers in my team while moving away from ASP .net”

It took them a moment before that they realized that SL is actually easy to work on and most importantly its the same C#, VB.net model  developers leverage on. The results they get

  • looks awesome (UI is simply great)
  • Works on every browser and just the same(no more coding for each browser and its version)
  • coding actually is easy

Getting the resistance out is just a matter of fact to demonstrate “how convenient it is” to code in silverlight and the goodies (best practices) are just there out-of-the-box.

Attached the the presentation deck along with the demo.

the best part for me is the compliment from Bijoy (who himself is renowned Microsoft evangelist) on my comment ‘Good products need good evangelists’

Technorati Tags: