Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

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”.

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.

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 31, 2009

DataBinding to App.Settings values

.Net 2.0 introduced this feature which helps to store and retrieve application specific settings very easily.You can easily create Settings through the visual editor.If we want to access them in code we can just use the Properties.Settings.Default object directly.The Default object will have all the properties which we had created at design time.
Showing ConnectionString entry in Messagebox
MessageBox.Show(Properties.Settings.Default.ConnectionString);


It is very easy.Lets learn how this can be binded in to a WPF TextBox.

First make a namespace reference to the Properties namespace.If your application name is WpfApplication1 it is xmlns:props=”WpfApplication1.Properties”.

Then in the Binding set source as the Default property available in the class Settings.Since it is static you have to use the x:Static binding extension.

Finally the path is ConnectionString which is the settings entry name.

Putting it altogether.


<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.Window1"
x:Name="Window"
xmlns:props="clr-namespace:WpfApplication1.Properties">
<Grid x:Name="LayoutRoot">
<TextBox  HorizontalAlignment="Left"  VerticalAlignment="Top"
Text="{Binding Source={x:Static props:Settings.Default},Path=ConnectionString}">
</TextBox>
</Grid>
</Window>


So enjoy WPF data binding to Properties.Settings.Default.

Thursday, February 26, 2009

Text selection in WPF TextBox

There are so many methods and properties which deals with selection in WPF TextBox.
Name Description
TextBox.Select() Accepts initial position and length of selection.
TextBox.SelectAll() Selects full text.
TextBox.SelectionStart Direct property which tells the start of selection.
TextBox.SelectionLength Direct property which tells the length of selection.
TextBox.SelectedText Gives the currently selected text.

But if you just use these methods and properties the selection will not come as expected.ie the text won't get selected even if we set these properties or call methods.

The reason for this is very simple.The TextBox is not in focus.So make sure that the TextBox is in focus before using programmatic selection related members.Or give Focus to the TextBox before selecting.

tbResult.Focus();

tbResult.SelectionStart = tbResult.Text.IndexOf("ControlTemplate TargetType=");
tbResult.SelectionLength = 230;

Friday, November 2, 2007

Working with cookies in XBAP

2 methods to access cookies ie get and set

Application.GetCookie
Application.SetCookie

Application.GetCookie will raise exception if the cookie is not present..

Thursday, November 1, 2007

Remove control box of Paged WPF applications

  • Get the instance of the current Window from Application.Current and remove it's Control box by setting WindowStyle=None.

    public partial class Page1 : System.Windows.Controls.Page
    {
    public Page1()
    {

    this.Loaded += new RoutedEventHandler(Page1_Loaded);
    InitializeComponent();
    }

    void Page1_Loaded(object sender, RoutedEventArgs e)
    {
    Application.Current.MainWindow.WindowStyle = WindowStyle.None;
    }

    }

    Application.Current.MainWindow will be initialized only in Loaded event of Page

  • <Application.Resources>
    <Style TargetType ="{x:Type NavigationWindow}">
    <Setter Property ="WindowStyle" Value="None"/>
    </Style>
    </Application.Resources>

Tuesday, August 7, 2007

3 dots (...) if space is insufficient

In older days if we want to put 3 dots (...), where there is no space to display full text,we have to do a bundle of calculations.

But in WPF its in built.Use

TextTrimming="CharacterEllipsis"

To get 3 dots...

<TextBlock Text="Joy George K" TextTrimming="CharacterEllipsis" />

Note : If you are using stack panel with orientation horizontal this wont work.If anybody have solution,please let me know.

Wednesday, June 27, 2007

Extending HeaderedItemsControl to have Footer !!!

The normal HeaderedContentControl in WPF gives us the facility to have a header up on the ItemsControl.This will be enough in most of the cases.But if you are looking for a ItemsControl which needs Footer too this is your solution.


  1. Solution 1

Use the Tag Property to hold Content of Footer.And Template it to have Footer.No inheritance!!!



<HeaderedItemsControl>
<HeaderedItemsControl.Header>Header</HeaderedItemsControl.Header>
<TextBlock Text="Item1" Background="LightGray"/>
<TextBlock Text="Item2" Background="LightGray"/>
<TextBlock Text="Item3" Background="LightGray"/>
<HeaderedItemsControl.Tag>Header</HeaderedItemsControl.Tag>
<HeaderedItemsControl.Template>
<ControlTemplate TargetType="{x:Type HeaderedItemsControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height ="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ContentPresenter ContentSource="Header" Grid.Row="0"/>
<ItemsPresenter Grid.Row="1" />
<ContentPresenter ContentSource="Tag" Grid.Row="2"/>
</Grid>
</Border>
</ControlTemplate>
</HeaderedItemsControl.Template>
</HeaderedItemsControl>

Tuesday, May 8, 2007

Target an inner element from setter

Consider a scenario where we need to change the second color of a gradient on mouse over.The normal solution will be as follows.

<Button>
<Button.Template>
<ControlTemplate TargetType="Button">
<Rectangle Width='60' Height='40' x:Name='MyRectangle'>
<Rectangle.Fill>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='Blue' Offset='1' x:Name='SecondStop' />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName='MyRectangle' Property="Fill" >
<Setter.Value>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='Green' Offset='1' />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>

If we folllow this method we need to write the same code twice.If there is a method to change the value of second color directly,it would be more easier to code.The below code does it with the help of binding.


<Button>
<Button.Template>
<ControlTemplate TargetType="Button">
<Rectangle Width='60' Height='40' x:Name='MyRectangle'>

<Rectangle.Tag>
<Color>Blue</Color>
</Rectangle.Tag>

<Rectangle.Fill>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='{Binding ElementName=MyRectangle, Path=Tag}' Offset='1' x:Name='SecondStop' />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName='MyRectangle' Property="Tag" Value="Green" >
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>