Subodh Pushpak’s Blog

Technical musings on .Net, silverlight, WCF and DLR

Management is Doing Things Right, Leadership is Doing the Right Things

Posted by subodhnpushpak on September 26, 2009

 

I am recently involved in a project which involves reengineering a system which has out grown over more than 7 years.

I was having a tough time just comprehending such a task as most of the requirement was coming as “design” use cases of previous implementation. So here is what i referred to: Big write by Chad Fowler: Here is a reproduction of his work for reference:

"Make it do what it already does." That’s a tempting and simple way to view software requirements on a rewrite project. After all, the system already exists. The question of "what should it do when…" can presumably always be answered with: "what it already does".

There are two major problems with this assumption.

  • The first, and most disruptive, is that the programmers don’t know what questions to ask.
  • With the fragile safety net of an existing implementation, programmers can easily oversimplify the interface, and assume they know the capabilities of the system.

Solution:

  • If there is a  software that is complex enough that it needs to be rewritten, it’s probably also so complex that it’s not discoverable in this way.
    • This means that domain experts are going to have to be heavily involved.
      • It means that requirements are going to need to be communicated in much the same way they are on a green-field project.
        • And it means that, unless it’s only used as a supplement, the existing system is more a liability to the rewrite than an asset.

Optimistic programmers might think I’ve missed something important here. If you’re rewriting a system, you’ve already got the code. The code can serve as the spec, right? Probably not.

I will also like to quote another excellent book “The Mythical Man-Month” by Fred Brooks which states the “Second System Effect”, i am particularly wary about.

The second system that an architect designs is the most dangerous system he will ever design since he will tend to incorporate all of the additions he originated but did not add (due to the inherent time constraints) to the first system. Thus, when embarking upon a second system, an engineer should be mindful that he is susceptible to over-engineering it.

By the way the “The Mythical Man Month” also provides an estimation insight as in Brooks’s law [adding manpower to a late software project makes it later]

  • Group Intercommunication Formula: n(n − 1) / 2
  • Example: 50 developers give 50 · (50 – 1) / 2 = 1225 channels of communication.

i got into reading into Chad Fowler when i found “The Passionate Programmer: Creating a Remarkable Career in Software Development

That was when i realized that i was NOT enjoying my work as architect[as it was abstract with NO coding] and wanted to know what lies for people like me; specially in India. [Ironically, The first edition of the book was released as My Job Went to India: 52 Ways To Save Your Job ]. Anyway, I was immediately hooked to the book.

He says “The important thing to realize is that change is not only possible in your career but necessary. As a software developer, you would never want to pour yourself into developing something your client doesn’t want. Agile methodologies help prevent you from doing so. The same is true of your career. Set big goals, but make constant corrections along the way. Learn from the experience, and change the goals as you go.”

I chose AGILE. I choose to change and go for an organization which has ample of opportunities for coder in me over a “well-defined architect role” . And here i am spreading the word of AGILE following “Better Than Yesterday” methodology. I wish everyone could read Fred instead. After all, i am doing the right thing!! :D

Posted in Uncategorized | Leave a Comment »

Architect / leader / Manager or All-in-One??

Posted by subodhnpushpak on September 21, 2009

I stumbled on an article here, and could help but to agree more on the same. The thought is just awesome and almost echoes what i was thinking for long but i was always in loss of words.

Initially, I shunned the very thought of managing people and getting more into managing timelines, schedule and execution of the project. I looked for the role if Individual Contributor (IC) and quickly discovered that the role is almost non-existent for mere mortals like me!!

So, i decided to train myself in Leadership and while i am yet into it and get down to level of doing a part time MBA i figured out that there is much more work which i need to do than i imagined.

There is a set notion about architects:

  1. There is set architecture solution for every problem (its same n-layered architecture and yes i-know-we-have-MVC-in-Presentation-Layer syndrome).
  2. Architects know how to talk technologies. They are BAD business communicators. [So if you call a business flow a USE-CASE or stakeholders a ACTOR… You will have it!!! ]
  3. Architects DO NOT code. They define what technologies to use and what the latest jargon round the corner.

All the above points cannot be more incorrect from truth.

1. Every solution is diverse even if it is from 30,000 feet view. Architect need to to think beforehand about the problem in hand, the bottlenecks which may be there and a solution for that.

2. Architects are the bridge between the BIG chasm of business and the technology. They have to talk both the languages and somehow manage the collaboration among all the business and the technology stakeholders.

3. Architects certainly do POCs. They are smart coders who are always challenging code and push it to limits. While they must know new technologies; they need to have more deeper insight into technology.

4. Architect also need to provide more insights while providing time, effort estimates. They should also know team members strengths so they have best team on job while project is executing.

5. Architect need to be educate the client about the limitations of the technology and at the same time educate the developers about the power of the technology.

Keeping above in view i have followed the below mantras quite successfully. Its 12 Rules for Self management and leadership by Rosa Say.

12 rules for self-management

  1. Live by your values, whatever they are. You confuse people when you don’t, because they can’t predict how you’ll behave.
  2. Speak up! No one can "hear" what you’re thinking without you be willing to stand up for it. Mind-reading is something most people can’t do.
  3. Honor your own good word, and keep the promises you make. If not, people eventually stop believing most of what you say, and your words will no longer work for you.
  4. When you ask for more responsibility, expect to be held fully accountable. This is what seizing ownership of something is all about; it’s usually an all or nothing kind of thing, and so you’ve got to treat it that way.
  5. Don’t expect people to trust you if you aren’t willing to be trustworthy for them first and foremost. Trust is an outcome of fulfilled expectations.
  6. Be more productive by creating good habits and rejecting bad ones. Good habits corral your energies into a momentum-building rhythm for you; bad habits sap your energies and drain you.
  7. Have a good work ethic, for it seems to be getting rare today. Curious, for those "old-fashioned" values like dependability, timeliness, professionalism and diligence are prized more than ever before. Be action-oriented. Seek to make things work. Be willing to do what it takes.
  8. Be interesting. Read voraciously, and listen to learn, then teach and share everything you know. No one owes you their attention; you have to earn it and keep attracting it.
  9. Be nice. Be courteous, polite and respectful. Be considerate. Manners still count for an awful lot in life, and thank goodness they do.
  10. Be self-disciplined. That’s what adults are supposed to "grow up" to be.
  11. Don’t be a victim or a martyr. You always have a choice, so don’t shy from it: Choose and choose without regret. Look forward and be enthusiastic.
  12. Keep healthy and take care of yourself. Exercise your mind, body and spirit so you can be someone people count on, and so you can live expansively and with abundance.

12 rules for self-leadership:

  1. Set goals for your life; not just for your job. What we think of as "meaning of life" goals affect your lifestyle outside of work too, and you get whole-life context, not just work-life, each feeding off the other.
  2. Practice discretion constantly, and lead with the example of how your own good behavior does get great results. Otherwise, why should anyone follow you when you lead?
  3. Take initiative. Volunteer to be first. Be daring, bold, brave and fearless, willing to fall down, fail, and get up again for another round. Starting with vulnerability has this amazing way of making us stronger when all is done.
  4. Be humble and give away the credit. Going before others is only part of leading; you have to go with them too. Therefore, they’ve got to want you around!
  5. Learn to love ideas and experiments. Turn them into pilot programs that preface impulsive decisions. Everything was impossible until the first person did it.
  6. Live in wonder. Wonder why, and prize "Why not?" as your favorite question. Be insatiably curious, and question everything.
  7. There are some things you don’t take liberty with no matter how innovative you are when you lead. For instance, to have integrity means to tell the truth. To be ethical is to do the right thing. These are not fuzzy concepts.
  8. Believe that beauty exists in everything and in everyone, and then go about finding it. You’ll be amazed how little you have to invent and much is waiting to be displayed.
  9. Actively reject pessimism and be an optimist. Say you have zero tolerance for negativity and self-fulfilling prophecies of doubt, and mean it.
  10. Champion change. As the saying goes, those who do what they’ve always done, will get what they’ve always gotten. The only things they do get more of are apathy, complacency, and boredom.
  11. Be a lifelong learner, and be a fanatic about it. Surround yourself with mentors and people smarter than you. Seek to be continually inspired by something, learning what your triggers are.
  12. Care for and about people. Compassion and empathy become you, and keep you ever-connected to your humanity. People will choose you to lead them.

Do let me know your thoughts / comments. Keep discovering.

Posted in Architecture | Tagged: | Leave a Comment »

I am on Microsoft Stack!!

Posted by subodhnpushpak on September 3, 2009

I am visiting beautiful city of Nashvillie, TN, US and involoved in rather interesting project involving WCF, silverlight and SQL server 2008.

Also being used are

  • Search server (FAST) / Lucene .Net
  • Omniture (for Web analytics)
  • Integration with Community server, Twitter, Facebook
  • Velocity – Distributed caching.
  • MemCache – Web server Cache
  • I am also planning to use Nikhil’s MVVM Silverlight Fx at silverlight end  or MEF
  • LINQ / Enity framework – for ORM.

TechStack

That remind me of scenario where i had to register MIME type at IIS 7.0 server to get silverlight (Skecthflow) running. below is the list

  • .xaml             application/xaml+xml
  • .xap               application/x-silverlight-app
  • .xbap             application/x-ms-xbap
  • .deploy           application/octet-stream
  • .xps               application/vnd.ms-xpsdocument
  • .application     application/x-ms-application

I will be posting more details when i get a breather from the project :D . Of course, it will have some more architecture docs :D

Keep me posted !!

Posted in Uncategorized | Leave a Comment »

Silverlight 3.0, RIA services and MVVM

Posted by subodhnpushpak on July 20, 2009

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: ,,

Posted in DesignPattern, Silverlight 3.0 | Tagged: , , | 3 Comments »

Silverlight 3.0 – TechEd on Roads

Posted by subodhnpushpak on July 20, 2009

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:

Posted in Silverlight 3.0 | Tagged: | Leave a Comment »

Twitter Tree in Silverlight

Posted by subodhnpushpak on June 23, 2009

At last i got some time to work on long pending “project: i have thought of. This one is about listing all twitter friends in a connected graph and see their statuses. It uses Twitter API and WCF service to feed the silverlight. WCF acts as an adapter to twitter service. The idea is to connect to other services like “orkut”, “facebook”, “Mayspace” etc in future.

It uses SL 3.0; so you must have it installed to run this:

Here are the snapshots of the running application.(Running in flock)!! You may see Tim heuer and Nikhil in the graph below… (I have learnt a lot from all these folks by following their blogs and twitter feeds) :D

image

While i still follow very selective list of people; here is graph of people following Nikhil ( Most of the people following him are really cool techies too!!)

image

And here is list for Tim!!!

image

If you want to play with the application here is the link

As a next step i am planning to move the same to AZURE!

Feedback / suggestions/ comments are welcome!!!

Technorati Tags: ,

Posted in .Net, Silverlight, Silverlight 3.0, Twitter | Tagged: , , | Leave a Comment »

Microsoft Azure, Bull Dog, Zurich ???

Posted by subodhnpushpak on May 28, 2009

Someone mentioned “Zurich” and I was again wondering how it was different from “Geneva” or “Zermatt”.

Finally searching got me into this very useful “codename” info.

And I thought only “open-source” can think of funny names.

Hope you will find it useful.

Hats off to Mary Jo Foley for compiling this… here is the list.

Technorati Tags: ,,

Posted in .Net, Azure | Leave a Comment »

Databinding in Silverlight and WPF

Posted by subodhnpushpak on May 27, 2009

Databinding in SL and WPF are interesting concepts and once mastered really solves many a issues with cleaner code. In XAML everything is dataaware.

Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML.

In this post we will discuss about

  • Simple CLR Object binding using code
  • Simple CLR Binding using XAML only – Demo value converters
  • Control Binding – Slider and textbox
  • Implementing IValueConverter
  • Validation
  • Update Source Trigger
  • StaticResource / DynamicResource

Simple CLR Object binding using code

if we declare a class like below in C# code

   1: public class MyClass

   2:    {

   3:  

   4:        #region ID

   5:        /// <summary>

   6:        /// Gets or sets ID 

   7:        /// </summary>

   8:        public int ID { get; set; }

   9:        #endregion ID

  10:  

  11:  

  12:        #region Name

  13:        /// <summary>

  14:        /// Gets or sets Name 

  15:        /// </summary>

  16:        public string Name { get; set; }

  17:        #endregion Name

  18:  

  19:  

  20:        #region dob

  21:        /// <summary>

  22:        /// Gets or sets dob 

  23:        /// </summary>

  24:        public DateTime dob { get; set; }

  25:        #endregion dob

  26:  

  27:  

  28:    }

   1: public Window1()

   2:        {

   3:            InitializeComponent();

   4:            Validation.AddErrorHandler(txt3, (o, e) =>

   5:                {

   6:  

   7:                    MessageBox.Show((string)e.Error.ErrorContent, "Error");

   8:  

   9:                }

  10:  

  11:                );

  12:  

  13:            DummyData();

  14:        }

  15:  

  16:        public void DummyData()

  17:        {

  18:            MyClass ob = new MyClass() { ID = 1, Name = "abc", dob = new DateTime(1980, 06, 08) };

  19:            this.DataContext = ob;

  20:  

  21:        }

we can simply bind it by using following

<StackPanel DataContext={Binding}>

        <TextBox x:Name="txt1" Text="{Binding Path=Name}" ></TextBox>

</StackPanel>

Simple CLR Binding using XAML only

We can just use XAML to declare variables of the class and use databinding as below

   1: <Window.Resources>

   2:         <local:MyClass x:Key="ob1" ID="1" Name="abc"></local:MyClass>

   3:         <local:MyClass x:Key="ob2" ID="2" Name="Red1"></local:MyClass>

   4:  

   5:     </Window.Resources>

   6:    <StackPanel>

   7:         <TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=OneWay}"></TextBox>

   8:         <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=OneWay}"></TextBox>

   9:     </StackPanel>

the output is:

image

Similar to setting “text” property we may even set “Background” to the text peoperty like below:

<TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob1}, Path=Name}"

                 ></TextBox>

        <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob2}, Path=Name}"

                 ></TextBox>

the output changes to: :D . the name of color is also the background!!!

image

Notice as i write and into text box and then click else where the color also changes as below:

image

What will happen if i give a improper color name? An exception? WPF and SL gives into trace message in case something goes wrong with databining. IT DOES NOT GIVES AN EXPLICIT EXCEPTION. like below

image

Notice that there is a trace in output window stating that there is no color “Subodh” however, it does not give an error on UI.

If i want a Blue color everytime i write “Subodh”, then i can write a Converter.

Value converters

   1: public class MyValueConverter : IValueConverter

   2:     {

   3:  

   4:         #region IValueConverter Members

   5:  

   6:         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   7:         {

   8:             string str = (string)value;

   9:             if (!string.IsNullOrEmpty(str))

  10:             {

  11:                 if (str == "Subodh")

  12:                 {

  13:                     return new SolidColorBrush(Colors.Blue);

  14:                 }

  15:             }

  16:             return value;

  17:         }

  18:  

  19:         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  20:         {

  21:             throw new NotImplementedException();

  22:         }

  23:  

  24:         #endregion

  25:     }

When this Converter is used in XAML, whenever is write “subodh” background will be blue. But for that i have declare the converter in XAML also like:

<Window.Resources>

        <local:Person x:Key="ob1" ID="1" Name="Subodh"/>

        <local:Person x:Key="ob2" ID="2" Name="Yellow"/>

        <local:MyValueConverter x:Key="myValueConverter"></local:MyValueConverter>

    </Window.Resources>

    <StackPanel Background="{DynamicResource solidColorBrush}">

        <TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob1}, Path=Name, Converter={StaticResource myValueConverter}}"

                 ></TextBox>

        <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob2}, Path=Name}"

                ></TextBox></StackPanel>

output:

image 

Control Binding:

We can bind two controls to each other value using XAML only code like:

if we define something like below.

<StackPanel>

            <ListBox x:Name="lst1" ItemsSource="{Binding Source={x:Static Sys:DateTimeFormatInfo.CurrentInfo}, Path=MonthNames}"></ListBox>

            <TextBox Text="{Binding ElementName=lst1, Path=SelectedItem}"></TextBox>

        </StackPanel>

for the above you may need

xmlns:Sys="clr-namespace:System.Globalization;assembly=mscorlib"

then the output is like :

image

Notice how we are binding MonthNames and then each selected item is displayed in the textbox… All using XAML!!!

If i require the list box items change according to the textbox at runtime and vice versa then i need to inherit my datasource using ObservableCollection as

   1: /// <summary>

   2:     /// Interaction logic for Window2.xaml

   3:     /// </summary>

   4:     public partial class Window2 : Window

   5:     {

   6:         public Window2()

   7:         {

   8:             InitializeComponent();

   9:             personTeam = new PersonTeam() { new Person() { ID = 1, Name = "sdS" }, new Person() { ID = 2, Name = "def" } };

  10:             this.DataContext = personTeam;

  11:         }

  12:         PersonTeam personTeam;

  13:         private void Button_Click(object sender, RoutedEventArgs e)

  14:         {

  15:             personTeam.Add(new Person() { ID = 1, Name = "zzz" }); ;

  16:         }

  17:     }

  18:  

  19:     public class PersonTeam : ObservableCollection<Person>

  20:     { 

  21:         

  22:     }

Now in XAML i may write

   1: <StackPanel DataContext="{Binding}">

   2:            <ListBox x:Name="lst2" ItemsSource="{Binding}">

   3:                <ListBox.ItemTemplate>

   4:                    <DataTemplate>

   5:                        <TextBox Text="{Binding Path=Name, Mode=TwoWay}"></TextBox>

   6:                    </DataTemplate>

   7:                </ListBox.ItemTemplate>

   8:            </ListBox>

   9:            <TextBox Text="{Binding ElementName=lst2, Path=SelectedItem.Name, UpdateSourceTrigger=PropertyChanged }"></TextBox>

  10:            <!--<Button Content="Add" Click="Button_Click"></Button>-->

  11:        </StackPanel>

here are the effects

image

Whenever i change something in either of the test box; the value changes in both!!!

I will blog the validations part in the next series.

Here is the code for the above and the ppt slides.

Please let me know you thoughts / comments.

Technorati Tags: ,

Posted in Silverlight, Silverlight 3.0, XAML | Leave a Comment »

Empty Data template in Silverlight DataGrid

Posted by subodhnpushpak on May 18, 2009

One of my colleagues mentioned the “missing feature” of silverlight datagrid where in a message needs to be displayed when no records are present in the datagrid Itemsource.

So the objective is to make a datagrid which have a Empty Data grid template which may be overridden in case there are no records in the datagrid Item source. Like below.

image

The datagrid itself is trivial. I have introduced 3 dependency properties and overridden the Datagrid and the DataTemplate itself.

Here is how the XAML looks like

 

   1: <local:DataGridWithEmptyTemplate ItemsSource="{Binding Person}"  x:Name="MyDataGrid" AutoGenerateColumns="True">

   2:            <local:DataGridWithEmptyTemplate.EmptyTemplate>

   3:                <local:EmptyDataTemplate Width="420.0" EmptyHeaderText="FirstName    |   LastName    |   Gender    " >

   4:                    <Border CornerRadius="5" BorderThickness="2" BorderBrush="Gray" Margin="5" >

   5:                        <Border.Background>

   6:                            <LinearGradientBrush EndPoint="0.512,1.154" StartPoint="0.512,0.154">

   7:                                <GradientStop Color="Red" Offset="1"/>

   8:                                <GradientStop Color="AntiqueWhite" Offset="0.339"/>

   9:                            </LinearGradientBrush>

  10:                        </Border.Background>

  11:                        <StackPanel Width="Auto" Background="Transparent">

  12:                            <TextBlock Text="No Records"  ></TextBlock>

  13:                            <TextBlock Text="Please change the criteria. This template may be changed using XAML!!"></TextBlock>

  14:                        </StackPanel>

  15:                    </Border>

  16:                </local:EmptyDataTemplate>

  17:            </local:DataGridWithEmptyTemplate.EmptyTemplate>

  18:        </local:DataGridWithEmptyTemplate>

you may notice the Width and EmptyHeaderText Properties of EmptyDataTemplate.

The code behind looks like

   1: public class EmptyDataTemplate : DataTemplate

   2:    {

   3:        public EmptyDataTemplate()

   4:        {

   5:            

   6:        }

   7:  

   8:        public string EmptyHeaderText

   9:        {

  10:            get

  11:            {

  12:                return (string)GetValue(EmptyHeaderTextProperty);

  13:            }

  14:            set

  15:            {

  16:                SetValue(EmptyHeaderTextProperty, value);

  17:            }

  18:        }

  19:  

  20:        public static readonly DependencyProperty EmptyHeaderTextProperty = DependencyProperty.Register(

  21:            "EmptyHeaderText", typeof(string), typeof(EmptyDataTemplate), new PropertyMetadata(null));

  22:  

  23:        public double Width

  24:        {

  25:            get

  26:            {

  27:                return (double)GetValue(WidthProperty);

  28:            }

  29:            set

  30:            {

  31:                SetValue(WidthProperty, value);

  32:            }

  33:        }

  34:  

  35:        public static readonly DependencyProperty WidthProperty = DependencyProperty.Register(

  36:            "Width", typeof(double), typeof(EmptyDataTemplate), new PropertyMetadata(100.0,null));

  37:    }

  38:  

  39:    public class DataGridWithEmptyTemplate : DataGrid

  40:    {

  41:  

  42:        public static TextBlock textBlock = new TextBlock();

  43:  

  44:        public DataGridWithEmptyTemplate()

  45:        {

  46:  

  47:            this.Loaded += new RoutedEventHandler((o, e) =>

  48:            {

  49:                int count = 0;

  50:                base.ItemsSource = this.ItemsSource;

  51:                var q = (IEnumerable)base.ItemsSource;

  52:                if (q != null)

  53:                {

  54:                    foreach (var items in q)

  55:                    {

  56:                        count++;

  57:                    }

  58:                }

  59:                if (count == 0)

  60:                {

  61:                    EmptyDataTemplate nodeTemplate = (EmptyDataTemplate)this.EmptyTemplate;

  62:                    if (nodeTemplate != null)

  63:                    {

  64:                        DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn();

  65:                        

  66:                        dataGridTemplateColumn.CellTemplate = nodeTemplate;

  67:                        dataGridTemplateColumn.Header = nodeTemplate.EmptyHeaderText;

  68:                        dataGridTemplateColumn.Width = new DataGridLength(nodeTemplate.Width);

  69:                        // we can even display the properties of object binded. 

  70:                        //var properties = from propertyInfo in typeof(Person).GetProperties()

  71:                        //                 select propertyInfo.Name;

  72:                        //foreach (string header in properties)

  73:                        //{

  74:                        //    d.Header = d.Header + header + "  |  ";

  75:                        //}

  76:                        FrameworkElement frameworkElement = dataGridTemplateColumn.CellTemplate.LoadContent() as FrameworkElement;

  77:                        this.Columns.Add(dataGridTemplateColumn);

  78:                        base.ItemsSource = new List<UIElement>() { frameworkElement };

  79:                        base.AutoGenerateColumns = false;

  80:                    }

  81:                }

  82:            }

  83:            );

  84:        }

  85:  

  86:        public EmptyDataTemplate EmptyTemplate

  87:        {

  88:            get

  89:            {

  90:                return (EmptyDataTemplate)GetValue(EmptyTemplateProperty);

  91:            }

  92:            set

  93:            {

  94:                SetValue(EmptyTemplateProperty, value);

  95:            }

  96:        }

  97:  

  98:        public static readonly DependencyProperty EmptyTemplateProperty = DependencyProperty.Register(

  99:            "EmptyTemplate", typeof(EmptyDataTemplate), typeof(DataGridWithEmptyTemplate), new PropertyMetadata(null));

 100:  

 101:    }

So, even if you forget to assign Itemsource or assigned itemsource which have zero items like before

MyDataGrid.ItemsSource = null;/// or even if you forget to assign Itemsource

MyDataGrid.ItemsSource = new List<Person>();

The result is same as below. You may override the template too!!!

   1: <local:DataGridWithEmptyTemplate ItemsSource="{Binding Person}"  x:Name="MyDataGrid" AutoGenerateColumns="True">

   2:             <local:DataGridWithEmptyTemplate.EmptyTemplate>

   3:                 <local:EmptyDataTemplate Width="420.0" EmptyHeaderText="FirstName    |   LastName    |   Gender    " >

   4:                     <Border CornerRadius="5" BorderThickness="2" BorderBrush="Gray" Margin="5" >

   5:                         <Border.Background>

   6:                             <LinearGradientBrush EndPoint="0.512,1.154" StartPoint="0.512,0.154">

   7:                                 <GradientStop Color="White" Offset="1"/>

   8:                                 <GradientStop Color="AntiqueWhite" Offset="0.339"/>

   9:                             </LinearGradientBrush>

  10:                         </Border.Background>

  11:                         <StackPanel Width="Auto" Background="Transparent">

  12:                             <TextBlock Text="No Records" Foreground="Red" ></TextBlock>

  13:                             <TextBlock Text="This template may be changed using XAML!!" Foreground="Red"></TextBlock>

  14:                         </StackPanel>

  15:                     </Border>

  16:                 </local:EmptyDataTemplate>

  17:             </local:DataGridWithEmptyTemplate.EmptyTemplate>

  18:         </local:DataGridWithEmptyTemplate>

image

Needless to say, the other functionality of datagrid remain the same as we have only introduced new DPs which have NO impact on existing functionality.

Finally here is the code.

Technorati Tags: ,

Posted in .Net, C#, Silverlight, Silverlight 3.0, XAML | Tagged: , | Leave a Comment »

Dependency Properties

Posted by subodhnpushpak on May 8, 2009

Dependency properties is one concept which i always marvel. As programmer / developer i always like the concept, as by just introducing DP, so many stuff now is so easy(Read Template programming in XAML).

DP is called a BEAST (in Silverlight and WPF) for reasons of complexity involved in understanding them. Also, of course, because they are so powerful language paradigm. I sometimes do think DP did not actually got their due. I mean, so many efforts is gone into explaining Lambda expressions, LINQ, and other stuff but DP still remains a taboo.

So, when i took up to the task of explaining WPF, many were skeptical about my thought of actually introducing DP in second session itself. (the audiences had people from testing and not-so-much-into-coding). But i have always felt, new programming concept are like mathematics, once you have the concept, its interesting. But, mostly the concept part is ignored and then it all becomes a mystery.

here is a whirlwind introduction of DP… The ppts are here and the demo code here.

Below is explanations:

Purpose of dependency properties is to compute the value of a property based on values of other inputs available

 

DPs provide for

–Change Notification

–Callbacks

–Property value validation

–Property value inheritance *

–Participation in animations *

–Participation in Styles *

–Participation in Templates *

–Data binding

–Layout changes *

Overriding default data values *

Example 1 – Explaining DP visual inheritance

consider:

   1: <Window x:Class="Demo2.Window1"

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

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" TextElement.FontSize="15"

   4:     Title="Window1" Height="300" Width="300">

   5:     <StackPanel>

   6:         <TextBlock Text="this has inherited Fonstsize DP property"></TextBlock>

   7:         <TextBlock Text="this has its own Fonstsize DP property" FontSize="20"></TextBlock>

   8:     </StackPanel>

   9: </Window>

output is : The one encircled in Red inherits Font size from visual parent Window, which sets TextElement.FontSize to 15. The one encircled in Blue overrides this to font size 20.

DP1

Example2: Now lets implement our own version of DP inheritance for POC. The idea is to introduce a new DP “Text” for stackpanel which is propagated to its visual children DP.

Consider:

   1: namespace Demo2

   2: {

   3:     /// <summary>

   4:     /// Interaction logic for Window2.xaml

   5:     /// </summary>

   6:     public partial class Window2 : Window

   7:     {

   8:         public Window2()

   9:         {

  10:             InitializeComponent();

  11:         }

  12:     }

  13:     public class MyStackPanel : StackPanel

  14:     {

  15:  

  16:  

  17:         public string Text

  18:         {

  19:             get { return (string)GetValue(TextProperty); }

  20:             set { SetValue(TextProperty, value); }

  21:         }

  22:  

  23:         // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...

  24:         public static readonly DependencyProperty TextProperty =

  25:             DependencyProperty.Register("Text", typeof(string), typeof(MyStackPanel), 

  26:             new FrameworkPropertyMetadata("stackPanel Default Text",

  27:                 FrameworkPropertyMetadataOptions.Inherits));

  28:  

  29:     }

  30:  

  31:  

  32:     public class MyButton : Button 

  33:     {

  34:         public string Text

  35:         {

  36:             get { return (string)GetValue(TextProperty); }

  37:             set { SetValue(TextProperty, value); }

  38:         }

  39:  

  40:         // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...

  41:         public static readonly DependencyProperty TextProperty =

  42:             MyStackPanel.TextProperty.AddOwner(typeof(MyButton), 

  43:             new FrameworkPropertyMetadata("Button Default Text", FrameworkPropertyMetadataOptions.Inherits));

  44:     }

  45: }

We have added DP for both StackPanel and button. However in Button the DP is registered as

public static readonly DependencyProperty TextProperty =

            MyStackPanel.TextProperty.AddOwner(typeof(MyButton),

            new FrameworkPropertyMetadata("Button Default Text", FrameworkPropertyMetadataOptions.Inherits));

now here are scenarios:

1. if we set Text DP for both MyStackPanel and MyButton as below

   1: <StackPanel>

   2:         <local:MyStackPanel x:Name="sp" Text="This is Test set by StackPanel">

   3:             <ContentPresenter Content="{Binding ElementName=sp, Path=Text}" ></ContentPresenter>

   4:             <local:MyButton Text="This is text set by MyButton"

   5:                 Content="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Text}"                           

   6:                             ></local:MyButton>

   7:         </local:MyStackPanel>

   8:     </StackPanel>

output is

image 

2. if we set ONLY the Text in MYstackpanel, the MYButton Text will inherit from visual parent as below

   1: <local:MyStackPanel x:Name="sp" Text="This is Test set by StackPanel">

   2:             <ContentPresenter Content="{Binding ElementName=sp, Path=Text}" ></ContentPresenter>

   3:             <local:MyButton 

   4:                 Content="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Text}"                           

   5:                             ></local:MyButton>

   6:         </local:MyStackPanel>

image Notice button caption is same as Stackpanel

3. If we Do NOT set any text, the TEXT will assume default values for BOTH.

image 

4. If we only set Button Text DP

   1: <local:MyStackPanel x:Name="sp" >

   2:            <ContentPresenter Content="{Binding ElementName=sp, Path=Text}" ></ContentPresenter>

   3:            <local:MyButton Text="This is text set by MyButton"

   4:                Content="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Text}"                           

   5:                            ></local:MyButton>

   6:        </local:MyStackPanel>

image

Notice in above case the Text DP is still default for stackpanel. that is DP is NOT propogated to visual parent from child.

We want to achieve the above case we have to make Attached DP property. I which parent property may be changed by the child element contained in parent

Attached DP Property

for this we will override an stackpanel and expose a Attached DP text which may be set by ANY visual children.

   1: <StackPanel>

   2:        <local:MyStackAttached x:Name="sp">

   3:            <Button x:Name="btn" local:MyStackAttached.Text="This text set by child button" Content="OK"></Button>

   4:        </local:MyStackAttached>

   5:        <TextBox x:Name="textBox" ></TextBox>

   6:    </StackPanel>

   1: namespace Demo2

   2: {

   3:     /// <summary>

   4:     /// Interaction logic for Window3.xaml

   5:     /// </summary>

   6:     public partial class Window3 : Window

   7:     {

   8:         public Window3()

   9:         {

  10:             InitializeComponent();

  11:             // notice , we are getting DP value from btn and NOT stackpanel :D 

  12:             textBox.Text =  (string)btn.GetValue(MyStackAttached.TextProperty);

  13:         }

  14:     }

  15:  

  16:     public class MyStackAttached : StackPanel

  17:     {

  18:         static ContentPresenter contentPresenter = new ContentPresenter() { Height = 100.0, Width = 200.0 };

  19:  

  20:         public MyStackAttached()

  21:         {

  22:             base.Children.Add(contentPresenter);

  23:         }

  24:  

  25:         public static string GetText(DependencyObject obj)

  26:         {

  27:             return (string)obj.GetValue(TextProperty);

  28:         }

  29:  

  30:         public static void SetText(DependencyObject obj, string value)

  31:         {

  32:             obj.SetValue(TextProperty, value);

  33:         }

  34:  

  35:         // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...

  36:         public static readonly DependencyProperty TextProperty =

  37:             DependencyProperty.RegisterAttached("Text", typeof(string), typeof(MyStackAttached),

  38:             new UIPropertyMetadata((o, e) =>

  39:             {

  40:                 contentPresenter.Content = GetText(o); 

  41:             }

  42:             ));

  43:     }

  44: }

output:

image

Data Validation, Coerce using DP

The idea is to create a textbox which accepts only correct AGE values between 1 and 100. This is achieved by exposing a DP AGE.

   1: public class MyTextBox : TextBox

   2:    {

   3:        public int Age

   4:        {

   5:            get { return (int)GetValue(AgeProperty); }

   6:            set { SetValue(AgeProperty, value); }

   7:        }

   8:  

   9:        // Using a DependencyProperty as the backing store for Age.  This enables animation, styling, binding, etc...

  10:        public static readonly DependencyProperty AgeProperty =

  11:            DependencyProperty.Register("Age", typeof(int), typeof(MyTextBox), new FrameworkPropertyMetadata(1,

  12:            FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback((o, e) => { }), new CoerceValueCallback((o, e) =>

  13:            {

  14:                int current = (int)e;

  15:                if (current <=0 )

  16:                    current = 1;

  17:                return current;

  18:            })),

  19:             new ValidateValueCallback((o) =>

  20:             {

  21:                 int current = (int)o;

  22:                 if (current > 100)

  23:                 { return false; }

  24:                 else

  25:                 { return true; }

  26:             }));

  27:    }

the XAML looks like:

   1: <StackPanel>

   2:         <TextBox x:Name="mytext"></TextBox>

   3:         <local:MyTextBox Age="{Binding ElementName=mytext, Path=Text, Mode=TwoWay}"

   4:                         Text="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Age, Mode=TwoWay}" 

   5:                          ></local:MyTextBox>

   6:     </StackPanel>

Output:

imageWhen Age value is <= 0 , the Age=1

image When age is valid

image  when age > 100 then Age =1

 

Along with above i have also included a unit test case for the last scenario in the code.

Your thoughts / comments are welcome:

Technorati Tags: ,,,

Posted in .Net, C#, WPF, XAML | Tagged: , , , , | Leave a Comment »