Tuesday, October 16, 2012

Microsoft Community Contributor

Contributor

I am proud to announce that I am recognized with Microsoft Community Contributor badge by Microsoft for my contribution in MSDN Forum. I have answered above 2000 answers with 29K points on MSDN Forum so far. Microsoft Community Contributor is a quarterly recognition by Microsoft.

Capture

More information about Microsoft Community Contributor is available on following link

https://www.microsoftcommunitycontributor.com/faq.aspx

Sunday, October 7, 2012

MultiPanel Control in WPF/Silverlight

Many time during designing we require different pages similar to a TabControl but without displaying Tabs. There are few article to create similar control for Windows Form and ASP.NET but not much for WPF or Silverlight. So I decide the create my own Custom MultiPanel.
MultiPanel is a simple control which inherits an ItemsControl and has SelectedIndex and SelectedPanel property to change the selected panel.
Public Class MultiPanel
    Inherits ItemsControl

    Public Sub New()
        MyBase.New()
        Me.DefaultStyleKey = GetType(MultiPanel)
    End Sub

    Public Property SelectedIndex() As Integer
        Get
            Return CInt(GetValue(SelectedIndexProperty))
        End Get

        Set(value As Integer)
            SetValue(SelectedIndexProperty, value)
        End Set
    End Property

    Public Event SelectionChanged As EventHandler(Of EventArgs)

    Public Shared ReadOnly SelectedIndexProperty As DependencyProperty = DependencyProperty.Register("SelectedIndex", GetType(Integer), GetType(MultiPanel), New PropertyMetadata(-1, New PropertyChangedCallback(AddressOf SelectedIndexChanged)))

    Public Property SelectedPanel() As Object
        Get
            Return GetValue(SelectedPanelProperty)
        End Get

        Set(value As Object)
            SetValue(SelectedPanelProperty, value)
        End Set
    End Property


    Public Shared ReadOnly SelectedPanelProperty As DependencyProperty = DependencyProperty.Register("SelectedPanel", GetType(Object), GetType(MultiPanel), New PropertyMetadata(Nothing, New PropertyChangedCallback(AddressOf SelectedPanelChanged)))

    Private Shared Sub SelectedIndexChanged(sender As DependencyObject, e As DependencyPropertyChangedEventArgs)
        Dim mp As MultiPanel = DirectCast(sender, MultiPanel)
        Dim index As Integer = Integer.Parse(e.NewValue.ToString())
        Dim oldIndex As Integer = Integer.Parse(e.OldValue.ToString())

        If index <> -1 AndAlso index <> oldIndex Then
            mp.SelectedPanel = mp.Items(index)
        ElseIf index = -1 Then
            mp.SelectedPanel = Nothing
        End If

        mp.RaiseSelectionChanged()
    End Sub

    Private Sub RaiseSelectionChanged()
        RaiseEvent SelectionChanged(Me, New EventArgs())
    End Sub

    Private Shared Sub SelectedPanelChanged(sender As DependencyObject, e As DependencyPropertyChangedEventArgs)
        Dim mp As MultiPanel = DirectCast(sender, MultiPanel)
        Dim pnl As Panel = DirectCast(e.NewValue, Panel)

        If pnl Is Nothing OrElse mp.Items.IndexOf(pnl) = -1 Then
            mp.SelectedPanel = Nothing
            mp.SelectedIndex = -1
        Else
            mp.SelectedPanel = pnl
            mp.SelectedIndex = mp.Items.IndexOf(pnl)
        End If
    End Sub

   
End Class



And below is the MultiPanel Style

    <Style TargetType="local:MultiPanel">
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MultiPanel">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" >

                        <ContentPresenter Content="{TemplateBinding SelectedPanel}"
                                                Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>



Below is a simple XAML Code example of using this control

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <my:MultiPanel x:Name="MainMultiPanel">
            <my:MultiPanel.Items>
                <Grid Name="grdCustomer">
                    <my:CustomerDetailControl />
                </Grid>
                <Grid Name="grdEmployee">
                    <my:EmployeeDetailControl />
                </Grid>
                <Grid Name="grdOrder">
                    <my:OrderDetailControl />
                </Grid>
            </my:MultiPanel.Items>
        </my:MultiPanel>
    </Grid>
</Window>



Now you can use SelectedIndex or SelectedPanel property of MultiPanel to display the required grid

MainMultiPanel.SelectedIndex = 2


Hope this control help you in your designing task. Look forward to your feedbacks.

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