Sunday, September 2, 2012

Common Converters in WPF/Silverlight

In WPF/Silverlight many times we have to provides a way to apply custom logic to binding. In this situation Converters are very handy to use. For converters we have to create a class which implements IValueConverter class. Below are few common Converters used in WPF/Silverlight.

Byte Array to Image Converter

    public class ByteToImageConverter : IValueConverter
    {
        public BitmapImage ConvertByteArrayToBitMapImage(byte[] imageByteArray)
        {
            BitmapImage img = new BitmapImage();
            using (MemoryStream memStream = new MemoryStream(imageByteArray))
            {
                img.SetSource(memStream);
            }
            return img;
        }


        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            BitmapImage img = new BitmapImage();
            if (value != null)
            {
                img = this.ConvertByteArrayToBitMapImage(value as byte[]);
            }
            else
            {
                //img = new BitmapImage(new Uri("/AssemblyName;component/Images/defaultImage.jpg", UriKind.Relative));
                 img = null;
            }
            return img;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

Example
        <Image Margin="3" Source="{Binding Path=ByteArray, Converter={StaticResource byteToImageConverter}}"/>
ByteToImageConverter will convert byte array of image to a BitmapImage which can be used in Source property of an image. This can be used when we have an image saved in binary form in database and we want to bind that and show in image control. We can show a default image if byte array is null by uncommenting the code in “else” part of BitmapToImageConverter class.

Null or Empty Visibility Converter

    public class NullEmptyVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {    
                if (value == null)
                {
                    return Visibility.Collapsed;
                }
                else if (value.GetType() == typeof(string) && string.IsNullOrWhiteSpace(value.ToString()) == true)
                {
                    return Visibility.Collapsed;
                }
                else
                {
                    return Visibility.Visible;
                }    
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new Exception("Not implemented");
        }
    }

Example
        <TextBlock Margin="3" Text="{Binding Path=Data, Converter={StaticResource nullVisibilityConverter}}"/>

NullEmptyVisibilityConverter can be used if we don’t want to show the control if value in binding is null. In above class, we are setting Visibility property as Collapsed if value is null or if string type value is null or empty.

Negative Converter

Public Class NegativeConverter
    Implements IValueConverter
    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
        If value.[GetType]() Is GetType(Boolean) Then
            Dim result As Boolean = CBool(value)
            Return Not result
        Else
            Return value
        End If
    End Function


    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Throw New Exception("Not implemented")
    End Function
End Class

Example
        <StackPanel Orientation="Vertical">
            <CheckBox  HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="chkFirst"/>
            <CheckBox Name="chkSecond" HorizontalAlignment="Left" Margin="3" Height="25" IsChecked="{Binding Path=IsChecked, ElementName=chkFirst, Converter={StaticResource negativeConverter}}"/>
        </StackPanel>
Sometime we want to display reverse result of the binded value. For example, we want to disable the control if value is true. Now the disable control we have to set IsEnabled = false and we have value of true to disable. So in this case we can use above NegativeConverter.

In above example code, we are unchecking the chkSecond checkbox if chkFirst checkbox is checked and vice versa. So for this we are setting staticResource of NegativeConverter in binding converter property.

Multiplication Converter

Public Class MultiplyConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
        If parameter IsNot Nothing Then
            Dim result As Double = Double.Parse(parameter.ToString())
            Return CDbl(value) * result
        Else
            Return CDbl(value)
        End If
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Throw New Exception("Not implemented")
    End Function
End Class

Example
 <StackPanel Orientation="Vertical">
            <TextBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="txtFirst"/>
            <TextBox Name="txtSecond" HorizontalAlignment="Left" Margin="3" Height="25" Width="{Binding Path=ActualWidth, ElementName=txtFirst, Converter={StaticResource multiplyConverter}, ConverterParameter=2.0}"/>
 </StackPanel>

In the above code in txtSecond textbox we are binding  it’s width property to txtFirst textbox width property. So we have set ElementName as txtFirst and Path as ActualWidth. And we want to have txtSecond width double of txtFirst. So we would be setting staticresource of MultiplyConverter in converter property and “2.0” as ConverterParameter property.

Now in MultiplyConverter class we would have ActualWidth of txtFirst in value parameter and “2.0” in “parameter” parameter. So we will multiply the two value and return the result.

Divide Converter

Public Class DivideConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
        If parameter IsNot Nothing Then
            Dim result As Double = Double.Parse(parameter.ToString())

            If result > 0 Then
                Return CDbl(value) / result
            Else
                Return CDbl(value)
            End If

        Else
            Return CDbl(value)
        End If
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Throw New Exception("Not implemented")
    End Function
End Class

Example
 <StackPanel Orientation="Vertical">
            <TextBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="txtFirst"/>
            <TextBox Name="txtSecond" HorizontalAlignment="Left" Margin="3" Height="25" Width="{Binding Path=ActualWidth, ElementName=txtFirst, Converter={StaticResource divideConverter}, ConverterParameter=2.0}"/>
 </StackPanel>

Similar to Multiplication Converter,  in the above code in txtSecond textbox we are binding  it’s width property to txtFirst textbox width property. So we have set ElementName as txtFirst and Path as ActualWidth. And we want to have txtSecond width half of txtFirst. So we would be setting staticresource of DivideConverter in converter property and “2.0” as ConverterParameter property.

Now in DivideConverter class we would have ActualWidth of txtFirst in value parameter and “2.0” in “parameter” parameter. So we will divide the ActualWidth by “2.0” and return the result.

Subtract Converter

Public Class SubtractConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
        If parameter IsNot Nothing Then
            Dim result As Double = Double.Parse(parameter.ToString())
            Return CDbl(value) - result
        Else
            Return CDbl(value)
        End If
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Throw New Exception("Not implemented")
    End Function
End Class

Example
<StackPanel Orientation="Vertical">
            <TextBox HorizontalAlignment="Left" Margin="3" Width="100" Height="25" Name="txtFirst"/>
            <TextBox Name="txtSecond" HorizontalAlignment="Left" Margin="3" Height="25" Width="{Binding Path=ActualWidth, ElementName=txtFirst, Converter={StaticResource subtractConverter}, ConverterParameter=15.0}"/>
</StackPanel>
Here we want txtSecond textbox, 15 pixels less than txtFirst.  In above code in txtSecond textbox we are binding  it’s width property to txtFirst textbox width property. So we have set ElementName as txtFirst and Path as ActualWidth. And as we want to have txtSecond 15 pixels less than txtFirst, we would be setting staticresource of SubtractConveter in converter property and “15.0” as ConverterParameter property.

Now in SubtractConverter class we would have ActualWidth of txtFirst in value parameter and “15.0” in “parameter” parameter. So we will subtract 15 from  ActualWidth and return the result.

Note:

In all the above converters we have to create it’s instance in resource and reference it using their key. For example you can write following code to create instance of SubtractConverter.
<Window.Resources>
          <local:SubtractConverter x:Key="subtractConverter" />
</Window.Resources>

Sunday, February 26, 2012

Microsoft Forums Mobile Application

Microsoft Customer Services and Support have launch of Microsoft Forums Mobile Application. The web version of this application is available for all smart phones that support HTML5, in the web browser.

“Microsoft Forums” Application allows you access MSDN, TechNet and Office365 forums directly right from your mobile devices. You can keep on track with the hottest topics, your own threads, favorite forums, in search with major topics, FAQs, and the latest news from OneCode & OneScript. Microsoft Forums connects you with our forum communities like never before. Access now and get started with all the Microsoft Forums right in your palms @ Aka.ms/msforums

MicrosoftForumFeatures

Capture

By simply inserting your Forum Display Name in the Settings Menu, without further saving. It’s done! For better experience, Wifi or 3G network environment is preferable.  

Also, experience “Microsoft Forums” from your PC desktop:

MSDN Gadget TechNet Gadget Office 365 Gadget

Saturday, February 4, 2012

Windows Phone Camp in Ahmedabad

Windows Phone Camp is coming to Ahmedabad on February 24, 2012. Developers and Designers can directly interact with domain experts in this event. These experts will share their knowledge, answer questions which could be helpful to everyone in creating future Windows Phone app and games.

Event Agenda


Time Session
09:00am - 10:00am Registration
10:00am - 11:00am The Windows Phone opportunity
11:00am - 12:00pm Getting Started - tools & marketplace
12:00pm - 01:00pm Designing Applications for Windows Phone
02:00pm - 03:00pm Developing Applications for Windows Phone
03:00pm - 04:00pm Making your application submission ready

Venue: Le Meridien, Near Nehru Bridge, Ahmedabad, Gujarat

You can find more details about the event from following link

Event Page

Speaker

Event Agenda

Registration

Monday, January 2, 2012

Microsoft MVP Hat-trick

I am proud to announce that I am awarded Microsoft MVP for the third consecutive year in VB.NET Category. I would like to thank Mr. Abhishek Kant and Microsoft MVP Community, without their support this journey would be quite difficult to achieve. I got this award because of my contribution on MSDN Forum so I would like to thank all the Moderators and MSFT associated with the forum. Also congratulation to all the new and renewed MVP awarded in this quarter.

Email from Microsoft

Dear Gaurav Khanna,

Congratulations! We are pleased to present you with the 2012 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual Basic technical communities during the past year.

The Microsoft MVP Award provides us the unique opportunity to celebrate and honor your significant contributions and say "Thank you for your technical leadership."

Nestor Portillo
Director
Community & Online Support

What is MVP Award?

The Microsoft Most Valuable Professional (MVP) is the award given by Microsoft to those it considers "the best from technology communities around the world who actively share their technical expertise with the community and with Microsoft. An MVP is awarded for contributions over the previous year. Each year, around 4,000 MVPs are honoured.

More information about the Microsoft MVP Program are available on following links

Friday, December 9, 2011

ApplicationContext to run background task

Many of times we need to create an application which need to run in background and doesn’t require a form or a GUI. We have an option of creating a Windows Service but sometime it’s difficult to use it for a normal user. So in this situation we have an option of creating an application by inheriting a ApplicationContext class which is available in Windows Form.

To create a project to run a background task we can perform following steps

  1. Create a new Windows Form project
  2. Delete the available Forms and Application class.
  3. Create a new class which will inherit ApplicationContext where we can perform background task.
  4. Create a new module which will contain main method to run the application.

Below is a simple example where we are inheriting ApplicationContext class. In the constructor of class we are starting a new thread where we can perform some long running task and when the task get completed we can call ExitThread which will close the application.

Public Class CustomApplicationContext
Inherits ApplicationContext

Public Sub New()
MyBase.New()

Try
Dim
th As New Thread(AddressOf StartBackgroundTask)
th.Start()
Catch ex As IOException
ExitThread()
End Try
End Sub

Private Sub
StartBackgroundTask()
Try
'Some background Task
For i As Integer = 0 To 5
Threading.Thread.Sleep(1000)
Next
Finally

'Task completed. Close the application
ExitThread()
End Try
End Sub
End Class

We also have to create a new Module which will contain Main method to start the application using Application.Run and having CustomApplicationContext class as it’s parameter.

Module MainModule
Public Sub Main()
Dim context As New CustomApplicationContext
Application
.Run(context)
End Sub
End Module

Download Code: CustomApplicationContext.rar

Tuesday, November 29, 2011

Multiple Columns in WPF ListBox

In this article we will discuss ways to have multiple columns in WPF ListBox control and layout the ListBox such that each row has 3 items. All WPF controls deriving from ItemsControl provide an ItemsPanel property that allows us to replace the internal layout panel that arranges the items. So to have multiple columns in a ListBox we have to change the ItemsPanel property of the control.

WrapPanel

One of the most simple way of displaying content horizontally in ListBox is to have WrapPanel in ItemsPanel property of Listbox. But if we need to display fixed number of items in a row then we have to disable the horizontal scrollBar so that item get wrap to next row and set fixed width for ListBox. But as item get wrap the ListBoxItem are not positioned uniformly. So we have to set Width for each ListBoxItem so that all the items are positioned in a tabular way.

        <ListBox Width="300" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<
ListBox.ItemsPanel>
<
ItemsPanelTemplate>
<
WrapPanel Orientation="Horizontal"/>
</
ItemsPanelTemplate>
</
ListBox.ItemsPanel>

<
ListBoxItem Content="Visual Basic" Width="80"/>
<
ListBoxItem Content="Silverlight" Width="80"/>
<
ListBoxItem Content="ASP.NET" Width="80"/>
<
ListBoxItem Content="WCF" Width="80"/>
<
ListBoxItem Content="Web Services" Width="80"/>
<
ListBoxItem Content="Windows Service" Width="80"/>
</
ListBox>

UniformGrid


One of the drawback with WrapPanel was we had to disable horizontal scrollbar, set Width for ListBox and also width for ListBoxItem. So we can use UniformGrid instead of WrapPanel in ItemsPanel property and set Columns property of it to the number of items we need to display in a row. Using UniformGrid all the items in the ListBox will have same width and height.


        <ListBox>
<
ListBox.ItemsPanel>
<
ItemsPanelTemplate>
<
UniformGrid Columns="3"/>
</
ItemsPanelTemplate>
</
ListBox.ItemsPanel>

<
ListBoxItem Content="Visual Basic" />
<
ListBoxItem Content="Silverlight" />
<
ListBoxItem Content="ASP.NET" />
<
ListBoxItem Content="WCF" />
<
ListBoxItem Content="Web Services" />
<
ListBoxItem Content="Windows Service" />
</
ListBox>
Grid

Although UniformGrid is the best solution for multiple column ListBox but sometime we don’t want all the columns in the ListBox of same size. Also in some scenario we could have a requirement where we need to merge two or more columns (or rows) for a larger text. In this situation using Grid is very useful option.


        <ListBox>
<
ListBox.ItemsPanel>
<
ItemsPanelTemplate>
<
Grid>
<
Grid.RowDefinitions>
<
RowDefinition Height="*"/>
<
RowDefinition Height="*"/>
<
RowDefinition Height="*"/>
</
Grid.RowDefinitions>
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="0.8*"/>
<
ColumnDefinition Width="*"/>
<
ColumnDefinition Width="Auto"/>
</
Grid.ColumnDefinitions>
</
Grid>
</
ItemsPanelTemplate>
</
ListBox.ItemsPanel>

<
ListBoxItem Content="WCF" Grid.Row="0" Grid.Column="0"/>
<
ListBoxItem Content="ASP.NET" Grid.Row="0" Grid.Column="1"/>
<
ListBoxItem Content="VB.NET" Grid.Row="0" Grid.Column="2"/>
<
ListBoxItem Content="Silverlight" Grid.Row="1" Grid.Column="0"/>
<
ListBoxItem Content="Web Services" Grid.Row="1" Grid.Column="1"/>
<
ListBoxItem Content="Windows Service" Grid.Row="1" Grid.Column="2"/>
<
ListBoxItem Content="Windows Presentation Foundation" Grid.Row="2" Grid.ColumnSpan="3"/>
</
ListBox>

Only headache of using Grid in ItemsPanel is that we have to set RowDefinitions and ColumnDefinitions for the Grid. Also we have to set the Grid.Row and Grid.Column for each item to position them in the ListBox. But in some scenario as described above it is very useful.

Sunday, November 6, 2011

I unlock Joy

At the recent Mobile Developer Summit which took place on November 2, 2011 at Bangalore Microsoft announced the details of the developer programme for Windows Mobile in India with ‘I unlock Joy’, a unique Application Development and Submission Program, where technology professionals and students get an opportunity to develop applications and showcase creativity.

‘I unlock Joy’ programme for developers has started from November 1, 2011 and will continue till June 30, 2012 whereas the program for students will begin on December 18, 2011 and conclude on March 30 next year.

Developer competitive categories:

· “SUBMIT & WIN” CATEGORY: A registered participant submits THREE qualified Windows Phone Application in the Marketplace and gets a chance to win a Windows Phone. In this category, the Applications must be distinct and of non-trivial utility value for the Application User.

· “PORT 2 APPS & WIN” CATEGORY: A registered participant submitting TWO qualified Windows Phone Applications in the Marketplace which are ported from existing Android or iPhone Applications get to win a Windows Phone.

· “WOMEN SPECIAL” CATEGORY: A first of its kind in the developer space. The first 100 registered Woman Developers who submit ONE (1) qualified Windows Phone Application each in the Marketplace qualify to win a Windows Phone each. The applications can be based on Entertainment, Fashion, Leisure, Sports, Recreation or Travel themes.

Student competitive categories:

· “STUDENT” CATEGORY: Calling on the community to be a part of the initiative, the “I unlock Joy” programme is customized to unfold their innovative and creative best and become among the select first few proud owners of the Windows Phone.

The contestants need to build one or more applications using Dev Tools and submit on AppHub. If their apps get certified and published on the Windows Phone Marketplace during the contest period which ends November 18, they can claim goodies like a brand new Windows Phone, certificate of acknowledgment from Microsoft and Windows Phone T-Shirts as well as USB flash drives.

You can find more information from official Website

http://www.microsoft.com/india/iunlockjoy/