Monday, December 6, 2010

Technology v/s Concepts and architecture

First of all this is not a WPF technology post.I posted this in my WPF blog since it has some relation with WPF.ok let’s start.

Technology here means the implementation languages or mediums for a programming solution such as WPF, Silverlight, Linq,WCF etc…While taking interviews, I have often heard that “I can learn or work in any technology since I know concepts and architecture”.Mostly this is the answer from a candidate when we ask “Do you know WPF or are you able to work in Silverlight?”. Some of my friends,they don’t even ready to rate themselves in the technology.If we ask them how do you rate yourself in WPF out of 10? they will say I am strong in concepts so I can do whatever work assigned to me in WPF.

If we think from an entrepreneur perspective this cannot be accepted every time.A person cannot estimate the work in WPF without the knowledge in WPF whatever strong he is in programming concepts and architectures.Also if the work in WPF or Silverlight is critical companies cannot rely on the statement “I know concepts and architecture”.Lets take one example to prove this.

The driver selection story

You are working in Cochin and on a Friday your CEO decided to go Chennai to attend an important meeting on Saturday.There are no tickets in flights and trains since the trip is decided suddenly.So he decided to go by his new highly sophisticated BMW car.He needs some body with him to drive the whole 700 kilometers since he need to attend the meeting with freshness.

There are 5 persons who are free in the week end and ready to accompany CEO.The first person, lets call him A said I have license but have no experience.Person B said I have license and have experience in riding motor cycle.Person C said I had driven my father’s truck.Person D said I have my own car which I am usually driving to come office.But its a 10 year old model.Person E said my uncle owns the same BMW model of yours and I usually drive it in the week ends and holidays.Who will accompany your CEO? obviously person E provided your CEO is smart :)

The case of Person A can be compared like a network guy saying I can do WPF.Person B is like a assembly language programmer saying I can do the WPF without training since I know basics an experience in programming.The case C can be compared as a Java programmer applying for WPF job saying that I am strong in OOPS.The D is like a .Net 1.0 programmer saying I can do WPF since all are .Net.E is the real one who knows WPF.Persons A,B,C & D can do the job provided they get certain time to familiarize the new car and its features.But since the time is limited nobody can be considered for the position.

Do I need to give more importance on technology?

The technology is getting importance over architecture depends on the situation or the demand.If we think from employer perspective ,he needs a technology guy if the work in particular technology is so critical and should be done in time.He don’t have time to give training to the guy he hires. If the requirement is for future project, the choice should give to the guys who are strong in concepts and architecture.Again that depends on the available time.If a WPF project is supposed to come on next month ,.Net guys can be hired and they can get training in WPF.If the time gap is 2 months JAVA or even assembly programming guys can also be included.

Coming to the developer perspective ,he should find some time to the technology as well while learning the architecture.Also while learning technology, learn the technology by comparing with the previous one.Main important thing to consider is “why I should learn a new technology ?”.I know some of my friends doing WPF /Silverlight projects without using data binding.Also they are simply creating controls when and where needed without changing templates.I asked why are you using this technology ? They simply replied “My company/client wants this project to be done in WPF”.

The moral of the story is “Learn technology before architecting your application and get benefits from it’s features”.

Sunday, August 8, 2010

Common Code Base 3 handling controls

Another issue you are going to face is the namespace and assembly differences of classes in WPF and Silverlight.Especially you will find when dealing with controls.ie the classes will be there with same methods and properties.But in different namespaces or assemblies .That prevent us from having common code base.

Lets just consider the case of TreeView in System.Windows.Controls namespace which is present in both WPF and Silverlight.In WPF it is in the assembly PresentationFramework.dll but in Silverlight its System.Windows.Controls.dll. Ideally the schema mapping should do the correct mapping and we should be able to use the xaml. But unfortunately it is not mapped to the schema.Means if we use common xaml file for tree view it will show a compilation error in Silverlight.

The tag 'TreeView' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'.

Does this indicate we should stop common code? Not at all.We have one solution which uses inheritance as a hack.I didn’t even think, inheritance will have such a usage.Solution is as follows.

  1. Create your own class for TreeView by inheriting the framework TreeView.Have this linked to WPF too.
  2. Use your treeview throughout the application.
Public Class CCBTreeView
Inherits System.Windows.Controls.TreeView
End Class


CCBTreeView would be in your controls project which refers PresentationFramework.dll and System.Windows.Controls.dll in WPF and Silverlight respectively. While using, use as follows.


<UserControl x:Class="TestCompatibility.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CCBControls="clr-namespace:CCB.Controls;assembly=CCB.Controls">
<CCBControls:CCBTreeView ItemsSource="{Binding Persons}" />
</UserControl>


This applies to so many controls such as HierarchicalDataTemplate,TabControl etc which differs in namespace or assembly.Refer the sample uploaded here if you still have confusion.Also let me know if anybody have better solution to this problem.

Previous posts on Common Code Base

----------------------------------------------

Common Code Base 1 Introduction

Common Code Base 2 Styles and Templates

Saturday, August 7, 2010

Debugging WPF and Silverlight DataBinding

Good article about debugging data binding in WPF and silverlight.

http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/debugging-data-bindings-in-a-wpf-or-silverlight-application.aspx

In short we can debug databinding in 2 ways

  1. Looking at the output/immediate window.
  2. Using converters.
  3. Putting break points in get and set regions of properties

Sunday, July 4, 2010

Common Code Base 2 Styles and Templates

As everybody knows Silverlight doesn’t support the Triggers which are most common in WPF.That means we cannot use WPF styles as it is.So obviously we need to create new styles even for Silverlight 4 which are same in behavior but using different xaml.Below are the best practices which we can follow to tackle the styles and templates in Common Code Base  scenario.

  • Don’t write any inline styles.Use resource dictionaries.
  • Merge the resource dictionaries at the application level only.

This will solve the issue with basic styles.Think of a scenario where you are loading the styles dynamically.In WPF you can handle this using DynamicResource binding extension.But the sad thing is Silverlight doesn’t support DynamicResource. So what is the solution.
The solution which we applied was very easy.Use StaticResource in the XAML files and load the styles through code in the App.xaml.vb file.Yes it worked in WPF too.
Download sample from here to see the styles and templates in action in CCB.(See the foreground of Button.Its coming through Style)

Previous posts on Common Code Base
----------------------------------
Common Code Base 1 Introduction

Thursday, June 17, 2010

Calling WCF service without AddReference

One of my Silverlight blog post is about creating a proxy without using the add reference menu in the Visual studio.The solution there is to write all the code which is auto generated when we add the reference through the proxy.ie we are just avoiding the auto generation and writing ourselves.Not a good solution.The reason we need to write all is because Silverlight supports only the Async service calls.But if we consider WPF we can call the service in Sync way.That means we can try out new things which will reduce our works in creating the manual proxy.

Didn’t get anything? In short we are going to create a proxy and call service without using the Add Service Reference menu or the any of the tool (eg:svcutil)available for generating the proxy.How can we achieve that.It’s simple .Share the contract dll.Important thing here is the sharing of contract dll is possible only because WPF and the WCF is using the same framework and runtime.This will not be possible in case of Silverlight since the runtime is different.

Ok.Lets start.We need 3 projects mainly.One is the Contracts where we keep all the WCF contracts.Then a service host project and a consumer of services.In the attached sample the host is a web host and the consumer is a WPF application.We can also host the WCF service in ConsoleHost.But in that case we need to solutions.Thats why I decided to go with WebHost.Below is solution structure.
Note that there is no ServiceReference in the WPF UI project.Only thing is the reference to Core project which contains all the contracts.App.Config should be same as of normal proxy creation in case you want to use default connection settings.All the magic happens inside the ServiceProxy class which is inheriting the ClientBase with a generic class.It will be clear after seeing the code below.
Imports System.ServiceModel
Imports ManualProxyTest.Core
Public Class ServiceProxy
    Inherits ClientBase(Of IMyService)
    Implements IMyService
    Public Function GetData(ByVal value As Integer) As String Implements IMyService.GetData
        Return Me.Channel.GetData(value)
    End Function
    Public Function Divide(ByVal no1 As Integer, ByVal no2 As Integer) As Double Implements IMyService.Divide
        Return Me.Channel.Divide(no1, no2)
    End Function
    Public Function GetChar(ByVal data As String, ByVal position As Integer) As Char Implements IMyService.GetChar
        Return Me.Channel.GetChar(data, position)
    End Function
End Class


For calling the service just create the instance of ServiceProxy and call as usual.Main advantage is the cleanliness in the code and we will have full control over the code.

Saturday, June 12, 2010

Common Code Base 1 Introduction

The thoughts on common code base or single code base for both desktop applications and internet applications has been started with introduction of C# in Silverlight 2. That brought not only the same design and coding languages into WPF and Silverlight but also the same APIs.

Same coding language was used earlier too.It was for Windows forms and ASP.Net.Even we were able to share the assemblies among them.But we were not able to create same application layer for them since the APIs and the design mediums were different.As time evolves Microsoft introduced the concept of XAML and made almost all the APIs same.

As everybody knows still Silverlight is the subset of WPF even in its 4th version.There are so many classes and members missing in Silverlight if we compare with the WPF equivalent.Does that means we cannot go for the common code base?

No.We can go for the approach of common code base as of now.But you cannot have certain WPF specific features in your application.Do your client allows that ? absolutely not.So we need to tackle that situation by providing WPF specific features in the desktop release.That means the road to the single code base is not that much easy as you think. So what is the simpe solution?

The solution is very easy.Develop your application against Silverlight excluding Silverlight specific features such as DeepZoom and compile the same code for WPF.It should work.I am saying this should work because most of the Silverlight classes and their members are available in WPF as same.

This will work if you are developing a simple application without WPF specific features.If you want to use WPF specific features you need to architect your application in such a way that it is following MVVm strictly.MVVm will allow you to switch the views very easily without changing the underlying layers.

Solution structure.

Develop against Silverlight then it will work in WPF. We need to remember this thing while creating the visual studio solution structure.So first create the Silverlight projects and keep the code and xaml files there.Then create WPF projects and link the files from Silverlight project location.Easy..What ever feature you implement in Silverlight or the fixes you do will reflect in WPF application too.

Look at the files MyControl.xaml and MyViewModel.They are real files in the Online solution and linked in Desktop project.

Issues

First issue you may encounter is XAML incompatibility.In WPF when we create a xaml style you normally specify as x:Type Classname.But this x:Type is not at all supported in Silverlight. Silverlight needs just the class name without x:Type .If you look at some of the controls like TreeView ,In WPF this resides in the PresentationFramework dll but in Silverlight it is in System.Windows.Controls.dll so we cannot have same xaml shared between WPF and Silverlight projects.There are so many issues like this.Will discuss about one by one in subsequent posts to make the real common code base.

Sunday, June 6, 2010

WPF 3.5 Bug in inheriting DataTemplate

You can easily reproduce the bug.Just inherit the DataTemplate and use the new DataTemplate class instead of default.You will get an runtime exception.

Your DataTemplate class

public class MyDataTemplate :DataTemplate
{
}


Nothing unusual rite? Then use this DataTemplate in your XAML.

<ListBox x:Name="lstPersons" >
<ListBox.ItemTemplate>
<local:MyDataTemplate >
<StackPanel>
<Button Content="{Binding Name}" />
</StackPanel>
</local:MyDataTemplate>
</ListBox.ItemTemplate>
</ListBox>


Just using the new class.But when we run this we get the exception as follows.


StackPanel' object cannot be added to 'MyDataTemplate'. Object of type 'System.Windows.Controls.StackPanel' cannot be converted to type 'System.Windows.FrameworkElementFactory.

This is true same in the case of HierarchicalDataTemplate too.

This is an identified bug.Microsoft has fixed this and WPF 4 contains the fix.

Friday, April 9, 2010

Getting ListBoxItem from selected entity

There will be some scenarios where we need to get the object of ListBoxItem which is hosting one of the the bound entity.Most probably it may be the SelectedItem.

Consider this scenario there is an business class called Employee and it’s collection class is EmployeeCollection.We have binding which binds object of EmployeeCollection to a ListBox.If we access the SelectedItem property of ListBox it will return the Employee object.But the requirement is to get the ListBoxItem which hosts the selected entity on an event say SelectionChanged.

Dim lbi As ListBoxItem = lstBox.ItemContainerGenerator.ContainerFromItem(lstBox.SelectedItem)



The above code can be used to get ListBoxItem of any object which is present in the collection.

Wednesday, April 7, 2010

Why WPF ProgressBar is not updating

When you put a loop and try to update the ProgressBar from that loop, it will not update the visual.The visual will update only after the execution of the loop.ie you can’t see the incremental animation.Here is the solution for that issue.

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
IncrementContinuously()
End Sub
Sub IncrementContinuously()
For i = 0 To 50
Thread.Sleep(100)
prgs.Dispatcher.Invoke(New CrossAppDomainDelegate(AddressOf IncrementBy1), DispatcherPriority.Background, Nothing)
Next
End Sub
Sub IncrementBy1()
prgs.Value = prgs.Value + 1
End Sub



This link contains some more solutions.

Tuesday, March 9, 2010

MCTS in WPF

It was my great ambition to clear WPF exam and became a MCTS from the day I started developing in WPF.Yesterday I achieved that.After getting the certification I was just thinking what are the benefits of taking such a certification? Even one of my colleague asked me what you are going to earn by writing these exams? Is it just because company is paying me the fees?

Absolutely no.There are some benefits as a developer.One is “We will get full coverage of WPF”.Second we gets some sort of “recognition in the community” .Third ,we can have the MCTS logo in our resume.The last benefit is our certification will help our company to get or retain partnership with Microsoft.

I don’t care about the last 3 points .Normally people does certification for that.If you elaborate the first point we can see the real benefit of certification.The coverage I meant is about the different areas in WPF.The certification includes all most all areas of WPF including 3D. Even if a person is working in WPF from the beginning, the chance for him to work in 3D is very less.That means he may know anything about 3D programming which is a great feature in WPF.By going for certification he needs to have a little knowledge about 3D programming in WPF using ViewPort3D,Camera etc…

Even I learnt different usages of documents only because of the preparation for the MCTS Exam.So try to get certified in the technology and move smoothly in the fast moving tech world.

Monday, February 1, 2010

Type safe INotifyPropertyChanged

Usually we pass the property name as string from the setter of properties and raise the INotifyPropertyChanged.PropertyChanged event.This is not type safe as you.There are chances that the end developers may misspell the property name.The below link gives a great idea to make your OnPropertyChanged calls type safe.

http://mfelicio.wordpress.com/2010/01/10/safe-usage-of-inotifypropertychanged-in-mvvm-scenarios/