Wednesday, September 09, 2009

Billiards Game developed in Silverlight

I have developed Billiards game in Silverlight .This game supports 8 ball and Pool. Below are the screens of this game and to play this game please click here



How to get content and text of each element of a Window

 Some times it is needed to get the content/text of  the children of a control.Then we have to iterate through all elements and should know its type.After comparing its type with the predefined types, we can cast that UIElement object to the particular object type.Then we can get/set its text/content values.Here is the sample code.

        foreach (UIElement oObject in this.LayoutRoot.Children)
            {

                Type type= oObject.GetType();
                string name=oObject.GetValue(NameProperty).ToString();
                if (type == typeof(TextBlock))
                {
                    TextBlock textBlock = oObject as TextBlock;
                    if (textBlock != null)
                    {
                        MessageBox.Show(textBlock.Text);
                    }
                }

                if (type == typeof(TextBox))
                {

                    TextBox textBox = oObject as TextBox;
                    if(textBox != null)
                    {

                        MessageBox.Show(textBox.Text);
                    }
                }
                if(type == typeof(ComboBox))
                {
                    ComboBox comboBox = oObject as ComboBox;

                    if(comboBox != null)
                    {

                        MessageBox.Show(comboBox.SelectedItem.ToString());

                    }

                }

                if(type==typeof(Button))

                {

                    Button button = oObject as Button;

                    if(button != null)

                    {

                        MessageBox.Show(button.Content.ToString());

                    }
                }        
}

Tuesday, September 08, 2009

.Net Technology Quest: Silverlight ComBoBox Selected Item not Setting

.Net Technology Quest: Silverlight ComBoBox Selected Item not Setting

Silverlight ComBoBox Selected Item not Setting

Here is the code I developed to Bind data to a ComboBox and set the selected Item. This code is tested and working fine. Xaml page

<UserControl x:Class="WorldOfVenkat.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="900" Height="600">

<Canvas x:Name="LayoutRoot" Background="Black">

<ComboBox Name="comBoBox" Width="400" Height="30" ></ComboBox>

</Canvas>

</UserControl>

Code behind in C#

public partial class Page : UserControl

{ public Page()

{

InitializeComponent(); BindComBoBox(); }

private void BindComBoBox()

{

List<Country> coutries = new List<Country>();

Country India = new Country(1,"India");

Country USA = new Country(2, "USA");

Country Canada = new Country(3,"Canada");

coutries.Add(India);

coutries.Add(USA);

coutries.Add(Canada);

comBoBox.ItemsSource = coutries; comBoBox.DisplayMemberPath = "Name"; comBoBox.SelectedItem = Canada;

}

public class Country

{

public int ID { get; set; }

public string Name { get; set; }

public Country(int id,string name)

{

ID = id;

Name = name;

}

} }

Thursday, July 16, 2009

Fix Windows Live Messenger Not Remembering ID and Password

Suddenly my Windows live messenger stopped 'Auto login' even when I select the check boxes 'Remember me' and 'Remember my password'.This is because of Yahoo tool bar. Here is the fix for this problem.Please go through the below article posted by Raymond. Fix Windows Live Messenger Not Remembering ID and Password

Thursday, February 19, 2009

How to Enable Silver light Debugging


If we try to add a new silver light project to a solution, then Visual studio prompts with the following dialogue box.



So that we can enable debugging on this newly created silver light application. However if we wanted to add an existing silver light application to a solution which contains a website project then we have to explicitly enable debugging on this silver light application, otherwise Visual studio wont debug this silver light application, when we set the Web application as the start up project.


To enable debugging on this newly added existing silver light project.
1) In solution Explorer, Right click on the Web Project and select ‘Property Pages’ .Here is the screen shot to select ‘Property Pages’



2) In ‘Property pages’ Window in ‘Start Options’ , make sure that the check boxes ‘ASP.NET’ and ‘Silverlight ‘ both are selected.



3) Select ‘Silverlight Application’ then Click on the ‘Add’ button, it will open the following window. Select the check box ‘Enable Silverlight Debugging’ then press ‘Apply’ then ‘Ok’.


Tuesday, February 03, 2009

CSS: Shared Classes

CSS: Shared Classes

Summary: You can group styles common to different rules into their own classes to save repeating yourself. By applying multiple classes to one element in CSS you can modularize your code to help optimize your style sheets.

You can group styles common to different rules into their own classes to save repeating yourself. CSS2-compliant browsers can reference multiple classes within individual elements.

For example:

<div id="nav" class="nav center">...</div>

This ability to reference multiple classes gives authors newfound options when styling their content. For elements that share the same styles (text-align:center for example), you can group these shared styles into one shared class. So this:

<style type="text/css">

.nav{color:red; text-align:center;}

.main{color:#000; text-align:center;}

</style>

...

<div id="nav" class="nav">...</div>

<div id="main" class="main">...</div>

Becomes this after grouping the common center style into one shared class:

<style type="text/css">

.nav{color:red;}

.main{color:#000;}

.ctr{text-align:center;}

</style>

...

<div id="nav" class="nav ctr">...</div>

<div id="main" class="main ctr">...</div>

The third .ctr class groups the common styles (in this case the center declaration) into a class now shared by two elements. The additional class saves space by eliminating redundant common declarations, which can add up for larger style sheets. In effect, you are normalizing your CSS.

Here is a small example about styles with classes and Id.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Shared Classes</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<style type="text/css">

body {

width: 40em;

font-family: Arial, Helvetica, sans-serif;

}

h1 {

font-size: 1.5em;

}

h2 {

font-size: 1.2em;

margin-top: 40px;

}

h3 {

font-size: 1.0em;

font-weight: bold;

}

h4 {

text-transform: uppercase;

font-size: 1.0em;

}

/*----these are the test classes and ids----*/

.orange {

color: orange;

}

.bold {

font-weight: bold;

}

#boldness {

font-weight: bold;

}

.orangegrouped.boldgrouped {

color:orange;

font-weight: bold;

}

#boldgroup.orangegroup {

color: orange;

font-weight: bold;

}

</style>

</head>

<body>

<h1>Applying multiple styles to HTML elements</h1>

<h2>Case I: Two separate classes applied to one element</h2>

<p class="orange bold">This text should be orange and bold. Two classes are applied to the <p> tag, "orange"

and "bold."</p>

<h2>Case II: A class and an ID applied to one element</h2>

<p class="orange" id="boldness">This text should be orange and bold. The <p> tag has the class "orange"

applied to it, and is assigned the id "boldness."</p>

<h2>case III: Two grouped classes applied to one element</h2>

<p class="orangegrouped boldgrouped">This text should be orange and bold. Two classes are applied to the <p>

tag, "orangegrouped" and "boldgrouped", which are defined together in the CSS.</p>

<h2>Case IV: Two grouped classes applied to one element in the opposite order</h2>

<p class="boldgrouped orangegrouped">This text should be orange and bold. Two classes are applied to the <p>

tag, "orangegrouped" and "boldgrouped", which are defined together in the CSS but in

the opposite order than they are applied in the <p> tag.</p>

<h2>Case V: A class and an ID grouped and applied to one element</h2>

<p class="orangegroup" id="boldgroup">This text should be orange and bold. The <p> tag has the class "orangegroup"

as well as the id "boldgroup" applied to it, which are defined together in the CSS.</p>

</body>

</html>

Conclusions

Netscape 4.x for Windows and Mac cannot support the application of multiple classes to a single element. It results in ignoring all classes. (Cases I, III, IV) It can, however, understand the application of a class and an id to a single element. (Case II) This technique only works, however, if the class and id are defined separately in the style sheet, not grouped together. (Test Case V)

Internet Explorer 4.x for Windows cannot support the application of multiple classes to a single element. It results in ignoring all classes. (Cases I, III, IV) It can, however, understand the application of a class and an id to a single element. (Case II) This technique works even if the class and id are grouped together in the style sheet, not defined separately. (Test Case V) In this respect IE 4.x differs from NN 4.x.

Friday, January 30, 2009

WPF data templates

WPF Data Templates.

While displaying data in data grid or ListBox, we may need to display various types of data. For example we may need to display dates in ‘MM/DD/YYYY’ format, float or double values in currency format ($560.00) or in some other format and all numeric data should be right aligned.

In our application we used Xceed data grid control. We can bind data by converting all fields in to string format. Initially what I did is, created a data table dynamically from data .All columns of the data table are of data type string. I used this data table as the Item source to the data grid control. It worked properly but the mistake I did was, I converted all numeric and date fields into string so that sorting on the date and numeric fields is not working. As I defined all the columns of the data table as string data type, the Data grid using string comparison instead of date comparison .

So my headache started …at last I came up with a beautiful and simple solution for the problem .Using Data Template we can solve this problem. While creating data table, I defined various columns with various data types corresponding to the binding data, so that the data table contains various data types of columns. Then sorting working properly but data is not formatted. With data template I solved this problem. Here is the sample code.

[ValueConversion(typeof(double), typeof(string))]

public class CurrencyConverter : IValueConverter

{

public object Convert(object value, Type targetType,object parameter, CultureInfo culture)

{

if ((value != null) && (!object.Equals(string.Empty, value)))

{

try

{

// Convert the string value provided by an editor to a double before formatting.

double tempDouble = System.Convert.ToDouble(value, CultureInfo.CurrentCulture);

return string.Format(CultureInfo.CurrentCulture, "{0:C}", tempDouble);

}

catch (FormatException)

{

}

catch (OverflowException)

{

}

}

return string.Format(CultureInfo.CurrentCulture, "{0}", value);

}

public object ConvertBack(object value, Type targetType,object parameter, CultureInfo culture)

{

return double.Parse(value as string, NumberStyles.Currency,CultureInfo.CurrentCulture);

}

}

[ValueConversion(typeof(DateTime), typeof(string))]

public class DateConverter : IValueConverter

{

public object Convert(object value, Type targetType,object parameter, CultureInfo culture)

{

if ((value != null) && (!object.Equals(string.Empty, value)))

{

try

{

DateTime dateTime = System.Convert.ToDateTime(value);

if (dateTime == DateTime.MinValue)

return String.Empty;

return dateTime.ToString("MM/dd/yyyy");

}

catch (FormatException)

{

}

catch (OverflowException)

{

}

}

return string.Format(CultureInfo.CurrentCulture, "{0}", value);

}

public object ConvertBack(object value, Type targetType,object parameter, CultureInfo culture)

{

return DateTime.Parse(value as string);

}

}

The data binding infrastructure of the WPF is extremely flexible. One of the major contributors to that flexibility is the fact that a custom value converter can be injected between two bound objects (i.e. the data source and target). A value converter can be thought of as a black box into which a value is passed, and another value is emitted.

A value converter is any object which implements the IValueConverter interface. That interface exposes two methods: Convert and ConvertBack. Convert is called when a bound value is being passed from the data source to the target, and ConvertBack is called for the inverse operation. If a value converter decides that it cannot return a meaningful output value based on the input value, it can return Binding.DoNothing, which will inform the data binding engine to not push the output value to the binding operation’s respective target.

Above I defined two Converter classes one for currency and the other for date conversion.

public static void SetDataTemplatesForGridColumns(DataTable dataTable, DataGridControl dataGrid)

{

Binding itemsBinding;

FrameworkElementFactory textBlockFactory;

foreach (DataColumn column in dataTable.Columns)

{

if (column.DataType == typeof(double) || column.DataType == typeof(Int32))

{

if (column.ColumnName == "Amount" || column.ColumnName == "LocalAmount")

{

itemsBinding = new Binding();

CurrencyConverter converter = new CurrencyConverter();

itemsBinding.Converter = converter;

//itemsBinding.ConverterParameter = c.DisplayFormat;

itemsBinding.ConverterCulture = CultureInfo.CreateSpecificCulture("en-US");

textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));

textBlockFactory.Name = "myTextBlockFactory" + column.ColumnName;

textBlockFactory.SetBinding(TextBlock.TextProperty, itemsBinding);

textBlockFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Right);

textBlockFactory.SetValue(TextBlock.MarginProperty, new Thickness(0, 0, 5, 0));

dataGrid.Columns[column.ColumnName].CellContentTemplate = new DataTemplate();

dataGrid.Columns[column.ColumnName].CellContentTemplate.VisualTree = textBlockFactory;

}

else

{

itemsBinding = new Binding();

textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));

textBlockFactory.Name = "myTextBlockFactory" + column.ColumnName;

textBlockFactory.SetBinding(TextBlock.TextProperty, itemsBinding);

textBlockFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Right);

textBlockFactory.SetValue(TextBlock.MarginProperty, new Thickness(0,0,5,0));

dataGrid.Columns[column.ColumnName].CellContentTemplate = new DataTemplate();

dataGrid.Columns[column.ColumnName].CellContentTemplate.VisualTree = textBlockFactory;

}

}

if(column.DataType == typeof(DateTime))

{

itemsBinding = new Binding();

DateConverter dateConverter = new DateConverter();

itemsBinding.Converter = dateConverter;

itemsBinding.ConverterCulture = CultureInfo.CreateSpecificCulture("en-US");

textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));

textBlockFactory.Name = "myTextBlockFactory1" + column.ColumnName;

textBlockFactory.SetBinding(TextBlock.TextProperty, itemsBinding);

textBlockFactory.SetValue(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Left);

dataGrid.Columns[column.ColumnName].CellContentTemplate = new DataTemplate();

dataGrid.Columns[column.ColumnName].CellContentTemplate.VisualTree = textBlockFactory;

}

}

}

itemsBinding = new Binding();

CurrencyConverter converter = new CurrencyConverter();

itemsBinding.Converter = converter;

itemsBinding.ConverterCulture = CultureInfo.CreateSpecificCulture("en-US");

the above lines creates a Binding object and sets its Converter property.Here itemsBinding.ConverterCulture set to ‘en-US’ (English USA) to display data in currency format(245.89378 as $245.89). The .NET format strings are useful if you want to convert one of the standard .NET Framework data types to a string that represents that type in some other format. For example, if you have an integer value of 100 that you want to represent to the user as a currency value, you could easily use the ToString method and the currency-format string ("C") to produce a string of "$100.00". Computers that do not have English (United States) specified as the current culture will display whatever currency notation is used by the current culture. The original value contained in the data type is not converted, but a new string is returned that represents the resulting value. This new string cannot be used for calculation until it is converted back to a .NET base data type. The original value, however, can be calculated at any time.

In the following code example, the ToString method displays the value of 100 as a currency-formatted string in the console's output window.

double Amount=100;

string formatedAmount=Amount.ToString("C”);

Console.WriteLine(formatedAmount);

This code displays $100.00 to the console on computers that have English (United States) as the current culture.

In CurrencyConverter class, the line

return string.Format(CultureInfo.CurrentCulture, "{0:C}", tempDouble);

will do the same.

FrameworkElementFactory class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate;

I created a FrameworkElementFactory object of type TextBlock.Then set its horizontal alignment and margin properties.

dataGrid.Columns[column.ColumnName].CellContentTemplate = new DataTemplate();

dataGrid.Columns[column.ColumnName].CellContentTemplate.VisualTree = textBlockFactory;

the above two lines creates a DataTemplate for DataGrid CellContentTemplate ,set its VisualTree to the FrameworkElementFactory object textBlockFactory. DateConverter also do the same as CurrencyConverter but it displays the data in the given date format,here the format given is "MM/dd/yyyy".