Looking for a job

I am looking for a job either contract or perm in WPF, Silverlight, Windows 8, asp.net. Please contact me if you have any open positions. I am available immediately and will send my resume.

Thanks

Using DataTemplateSelector in Metro Style App

This is a short post on using DataTemplateSelector to show items differently in the same list.

Lets say we have

public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
}

public class PreferredCustomer: Customer
{
public int Discount { get; set; }
}

and we create a list of customers like this and set the itemssource to any ItemsControl

List<customers> = new List();
customers.Add(new Customer { Id = “1”, Name = “customer..1” });
customers.Add(new PreferredCustomer { Id = “2”, Name = “customer..2”, Discount=10 });
customers.Add(new Customer { Id = “3”, Name = “customer..3” });
customers.Add(new PreferredCustomer { Id = “4”, Name = “customer..4”, Discount=20 });
customers.Add(new Customer { Id = “5”, Name = “customer..5″ });

list1.ItemsSource = customers;

In resources section, we create couple of datatemplates and a DataTemplateSelector which returns a datatemplate based on the item.

We bind the ItemTemplateSelector property of Listview to the one we created in resource section.

public class CustomerDataTemplateSelector : DataTemplateSelector
{
public DataTemplate CustTemplate { get; set; }
public DataTemplate PrefCustTemplate { get; set; }

protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
Customer c = (Customer)item;
DataTemplate dt = c is PreferredCustomer ? this.PrefCustTemplate : this.CustTemplate;
return dt;
}

}

<Page
x:Class=”Application1.BlankPage1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:local=”using:Application1″
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d”>
<Page.Resources>
<DataTemplate x:Key=”dtCustomer”>
<TextBlock Text=”{Binding Name}” FontSize=”25″/>
</DataTemplate>
<DataTemplate x:Key=”dtPrefCustomer”>
<TextBlock Foreground=”Green” Text=”{Binding Name}” FontSize=”25″ FontWeight=”Bold”/>
</DataTemplate>
<local:CustomerDataTemplateSelector x:Key=”cdst” CustTemplate=”{StaticResource dtCustomer}” PrefCustTemplate=”{StaticResource dtPrefCustomer}”/>
</Page.Resources>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>

<ListView Width=”300″ x:Name=”list1″ FontSize=”30″ ItemTemplateSelector=”{StaticResource cdst}”/>

</Grid>
</Page>

Here is the result.

Customizing GridView Items in Metro App

This is a short post on customizing height and width of the items in GridView. by default if we use a WrapGrid we get items as bunch of tiles.

We can change the height and width of the tiles by deriving from gridview and overriding PrepareContainerForItemOverride method like below. In the code I am making the tile double the width if the city is “City 4”.  Ofcourse we can add properties and not hardcode stuff like shown
public class MyGridView : GridView
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
var obj = item as Person;
var gi = element as GridViewItem;
if (obj.City == “City 4”)
{
gi.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, 2);
gi.Background = new SolidColorBrush(Colors.Beige);
gi.Foreground = new SolidColorBrush(Colors.Black);
gi.FontSize = 22;
}
base.PrepareContainerForItemOverride(gi, item);
}
}

Here is the xaml and code I used in the BlankPage .

protected override void OnNavigatedTo(NavigationEventArgs e)
{
Random r = new Random();
var items = Enumerable.Range(0, 50).Select(x =>
new Person { Id = x,
Name = “person..” + x.ToString(),
City = “City ” + (r.Next(0,5)).ToString() });
cvs.Source = items;

}

<Page.Resources>         <CollectionViewSource x:Name=”cvs”/>     </Page.Resources>

<local:MyGridView FontSize=”20″ FontFamily=”segoe ui” Margin=”100″ ItemsSource=”{Binding Source={StaticResource cvs}}” >
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment=”Left” >
<TextBlock Text=”{Binding Id}” />
<TextBlock Text=”{Binding Name}” />
<TextBlock Text=”{Binding City}” />
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>

<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid ItemHeight=”120″ ItemWidth=”120″ MaximumRowsOrColumns=”6″ Orientation=”Vertical”/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>

</local:MyGridView>

Here is the result.

Finding Key State using PInvoke in SL5 RC

If we have to find the Key State of  CAPS lock,  NUM lock etc in silverlight 5 RC, we could do like this using PInvoke

Add the Declaration

[DllImport(“user32.dll”, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);

And to get the different Key states

bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;

bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;

bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;

 

 

Using PInvoke in SL5 to show MessageBox

One of the new features in SL5 is the ability to use PInvoke. This post shows how to use PInvoke to show MesageBox with lot more options.

Start by creating a SL5 OOB application with elevated trust and add the following code

[DllImport(“user32.dll”, CharSet = CharSet.Auto)]
public static extern MessageBoxResult MessageBox(IntPtr hWnd, String text, String caption, int options);
public enum MessageBoxOptions
{
Ok = 0x000000,
OkCancel = 0x000001,
AbortRetryIgnore = 0x000002,
YesNoCancel = 0x000003,
YesNo = 0x000004,
RetryCancel = 0x000005,
CancelTryContinue = 0x000006,

IconHand = 0x000010,
IconQuestion = 0x000020,
IconExclamation = 0x000030,
IconAsterisk = 0x000040,
UserIcon = 0x000080,

IconWarning = IconExclamation,
IconError = IconHand,
IconInformation = IconAsterisk,
IconStop = IconHand,

DefButton1 = 0x000000,
DefButton2 = 0x000100,
DefButton3 = 0x000200,
DefButton4 = 0x000300,

ApplicationModal = 0x000000,
SystemModal = 0x001000,
TaskModal = 0x002000,

Help = 0x004000, //Help Button
NoFocus = 0x008000,

SetForeground = 0x010000,
DefaultDesktopOnly = 0x020000,
Topmost = 0x040000,
Right = 0x080000,
RTLReading = 0x100000,
}

public enum MessageBoxResult : uint
{
Ok = 1,
Cancel,
Abort,
Retry,
Ignore,
Yes,
No,
Close,
Help,
TryAgain,
Continue,
Timeout = 32000
}

To actually see the messagebox, we could do something like

MessageBoxOptions options = MessageBoxOptions.CancelTryContinue | MessageBoxOptions.DefButton1 | MessageBoxOptions.IconQuestion;
MessageBox(IntPtr.Zero, “This is a messagebox with 3 buttons, one of them being default and a question icon”, “Caption”, (int)options);

Here is the result

Enum’s and MarkupExtension

Here is quick sample to get all the values from an enum using MarkupExtension. This returns a Dictionary

 public class EnumValuesExtension : MarkupExtension
    {
        public string EnumName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IXamlTypeResolver xamlResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
            Type t = xamlResolver.Resolve(EnumName);
            return t.GetFields().Where(field => field.IsLiteral).ToDictionary(x => (int)x.GetValue(null), x => x.Name);
        }
    }

If we have a enum like below

 public enum Days
    {
        Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri
    }

We can use it in xaml like this. ‘local’ is the xmlns declaration pointing to the namespace

 <ComboBox Width=”150″ Height=”25″ DisplayMemberPath=”Value”
                  ItemsSource=”{local:EnumValues EnumName=’local:Days’}”/>

DataGrid random behavior when scrolling

I came across a post in the silverlight forums which shows the random behavior of the DataGrid. This happens obviously only when scrollbars are there and when we scroll. Wraping DataGridRowsPresenter in the Template of the DataGrid in a scrollviewer seems to get around this issue. As scrollviewer has some border margin etc. I styled it to remove all unnecessary stuff.

 <ScrollViewer Grid.ColumnSpan=”2″ Grid.Row=”1″ Style=”{StaticResource ScrollViewerStyle1}”>
                                        <sdk:DataGridRowsPresenter x:Name=”RowsPresenter” />
                                    </ScrollViewer>  

If you remove the style applied to the DataGrid in the sample you can clearly see the random behavior. You can download the sample here .

DataGrid and “No Records Found” message

Here is one way to display a message when we dont have any data returned

1. Grab the Template of the DataGrid from Blend

2. Modify the Template. All we do is find the RowsPresenter line
<sdk:DataGridRowsPresenter x:Name=”RowsPresenter” Grid.ColumnSpan=”2″ Grid.Row=”1″/>
and move it inside a Grid element, we add in the template in the same place.
The Grid has a TextBlock to show the message and Visibility is controlled by a Converter

Here is the relevant part of the Template

<sdk:DataGridColumnHeader x:Name=”TopLeftCornerHeader” Template=”{StaticResource TopLeftHeaderTemplate}” Width=”22″/>
<sdk:DataGridColumnHeadersPresenter x:Name=”ColumnHeadersPresenter” Grid.Column=”1″/>
<sdk:DataGridColumnHeader x:Name=”TopRightCornerHeader” Grid.Column=”2″ Template=”{StaticResource TopRightHeaderTemplate}”/>
<Rectangle x:Name=”ColumnHeadersAndRowsSeparator” Grid.ColumnSpan=”3″ Fill=”#FFC9CACA” Height=”1″ StrokeThickness=”1″ VerticalAlignment=”Bottom” Width=”Auto”/>
<!–<sdk:DataGridRowsPresenter x:Name=”RowsPresenter” Grid.ColumnSpan=”2″ Grid.Row=”1″/>–>
<Grid Grid.ColumnSpan=”2″ Grid.Row=”1″ >
<sdk:DataGridRowsPresenter x:Name=”RowsPresenter”/>
<TextBlock Text=”No Records found”
Visibility=”{Binding ElementName=RowsPresenter, Path=Children.Count, Converter={StaticResource noRecordsConverter}}”
HorizontalAlignment=”Center” VerticalAlignment=”Center”
FontSize=”12″/>
</Grid>

<Rectangle x:Name=”BottomRightCorner” Grid.Column=”2″ Fill=”#FFE9EEF4″ Grid.Row=”2″/>
<Rectangle x:Name=”BottomLeftCorner” Grid.ColumnSpan=”2″ Fill=”#FFE9EEF4″ Grid.Row=”2″/>
<ScrollBar x:Name=”VerticalScrollbar” Grid.Column=”2″ Margin=”0,-1,-1,-1″ Orientation=”Vertical” Grid.Row=”1″ Width=”18″/>

And the Converter

public class NoRecordsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString() == “0” ? Visibility.Visible : Visibility.Collapsed;
}

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