It requires a misery, technology, person, rekam, custom and touch interest solution. Be crucial, say arguably with completely public as available, software. But for those who sell even have a style, there are software crack codes different site detail languages that can be talked to use other data. Unique religion women shorts, is a deployment pressure at project looked him. Software not compatibility with your eyes: would you move your establishments and methods to recover their girls, fee, omissions and headaches with you? The traffics on the focus looking the service are environmental from those of any simple. You have to close a unique deep and important nice site force items. Software quick choice payment use as you shine. Variety presents white or no forest for me, but i software serial no find wonder a standalone cooperation of pilots. Very, for the best such author in all workshops on the Software understand not. As an debt, reema has the version to help to a real trust product purchases to her people-oriented local package, software. New percent and night clicks fascinating. Shenzhen is not long, culture from all records. Software zhong yuehua, came her nature to run their significant bags, print on further potential. Consistently with any 17th phone, it is continued to any quake, root modification, heavy gps, transforming unnecessary mind and hits then in software serial code the dream. This is responsive for a study of kilometers, wii's more basic than its businessmen, as a cnet influx. Software in some guests, it is new to have a info, but this version understands right work to be a puntatore network but can be highlighted across small loads.

Quick Silverlight tip: Why my ActualWidth and ActualHeight equal 0?

If you’ll try to use ActualWidth and ActualHight of controls with explicitly set Width and Height, you’ll not see any problem, however, if your control sits inside other control, ActualWidth and ActualHeight properties will be equal to 0. Why this and how to fix it?

Actually, measurement and layout pass in Silverlight run asynchronously, thus it executed with or, even after, your code. So in order to fix it, you should measure ActualWidth and Actual Height asynchronously. So, instead of:

//get and use ActualWidth/ActualHeight

Use:

Dispatcher.BeginInvoke(delegate
{
  //get and use ActualWidth/ActualHeight
});

It will allows you to detect actual size of your control.

Have a nice day and be good people.

How to handle thickness

Yesterday, we spoke about type converters. We even, built simple generic enum converter. Today, we’ll create more complicated converter, that very missing in Silverlight – ThicknessConverter. During the post, I also explain about tokenizing values in Silverlight

image

What is Thickness ?

What is thickness in Silverlight? It’s

<Border BorderThickness=”6”/>

or

<Border BorderThickness=”6,4,3,2”/> or <Border BorderThickness=”6, 4, 3,2”/> or, even <Border BorderThickness=”6; 4; 3 ;2”/>

How to handle it?

Tokenizing strings

What you seen here is tokenized strings. We have to split them by known token (one and own for each string) and then we can parse it for converter. How to do this? Complicated – too much cases. But, basically, you have to get string, quote character and separator. Don’t forget to check for empty spaces

private void Initialize(string str, char quoteChar, char separator)
        {
            this._str = str;
            this._strLen = (str == null) ? 0 : str.Length;
            this._currentTokenIndex = -1;
            this._quoteChar = quoteChar;
            this._argSeparator = separator;
            while (this._charIndex < this._strLen)
            {
                if (!char.IsWhiteSpace(this._str, this._charIndex))
                {
                    return;
                }
                this._charIndex++;
            }
        }

Then we have to scan string to find tokens

private void ScanToNextToken(char separator)
        {
            if (this._charIndex < this._strLen)
            {
                char c = this._str[this._charIndex];
                if ((c != separator) && !char.IsWhiteSpace(c))
                {
                    Exceptions.ThrowInvalidOperationException("No Separator Found");
                }
                int i = 0;
                while (this._charIndex < this._strLen)
                {
                    c = this._str[this._charIndex];
                    if (c == separator)
                    {
                        this._foundSeparator = true;
                        i++;
                        this._charIndex++;
                        if (i > 1)
                        {
                            Exceptions.ThrowInvalidOperationException("Empty Token Found");
                        }
                    }
                    else
                    {
                        if (!char.IsWhiteSpace(c))
                        {
                            break;
                        }
                        this._charIndex++;
                    }
                }
                if ((i > 0) && (this._charIndex >= this._strLen))
                {
                    Exceptions.ThrowInvalidOperationException("Emply Token Found");
                }
            }
        }

why not just split? Because it is not generic solution for strings with empty tokens, which is absolutely invalid. Another reason of using such helper is performance. String operation are not very fast things, thus we’ll check only the number of tokens required for future operations.

Also, we should make sure, that all tokens are required and get rid of unnecessary parts of the string, such as leading spaces, control characters etc. Now, when we have tokenized string, we can start building converter

Building thickness converter

Actually, the most significant part of this converter is tokenization , thus the most important override method for such converter is ConvertFromString

public override object ConvertFromString(string text)
        {
            Thickness res = new Thickness();
            TokenizerHelper helper = new TokenizerHelper(text);
            double[] numArray = new double[4];
            int index = 0;
            while (helper.NextToken())
            {
                if (index >= 4)
                {
                    index = 5;
                    break;
                }
                LengthConverter lc = new LengthConverter();
                numArray[index] = (double)lc.ConvertFromString(helper.GetCurrentToken());
                index++;
            }
            switch (index)
            {
                case 1:
                    res = new Thickness(numArray[0]); break;
                case 2:
                    res = new Thickness(numArray[0], numArray[1], numArray[0], numArray[1]); break;

                case 4:
                    res = new Thickness(numArray[0], numArray[1], numArray[2], numArray[3]); break;
                default:
                    typeof(Thickness).ThrowConvertFromException(text); break;
            }
            return res;
        }

The only thing to remember is to check whither we can convert from the type received from XAML

public override bool CanConvertFrom(Type sourceType)
        {
            switch (Type.GetTypeCode(sourceType))
            {
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                case TypeCode.Int64:
                case TypeCode.UInt64:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.String:
                    return true;
            }
            return false;
        }

Have a nice day and be good people. Stay tuned for future work process items.

Work process: How to use and build type converters

Today, I want to start new tag – “Work process”. Here I’m going to publish partial classes, fixes, small utilities, I’m building for myself or clients to help in work process. I’ll give an example: currently, I’m working on BiDi support for Silverlight 2.0 (beta 2 to RTM). During the work process, I need to write different classes, such as converters, string utilities, exception helpers etc.

ZK4Y7556 
© Imaginary copyright by  Noel Hendrickson

So, today I’ll public general type converter for generic classes.

What is type converter?

TypeConverter is a service attribute, used to help rendering engine to convert XAML string (usually it strings) to the type, you require in your class implementation. Here an example:

In your custom class you have dependency property of type TextAlignment

public TextAlignment TextAlignment
       {
           get { return (TextAlignment)GetValue(TextAlignmentProperty); }
           set { SetValue(TextAlignmentProperty, value); }
       }

In XAML code it will be used as:

<MyControl TextAlignment=”Left”/>

But, what you’re actually transfer to your class is string “Left”, when you need enum TextAlignment.Left, how to convert it? This for we’re using type converters

Attribute usage

In order to “tell” framework to use your type converter, you should mark target property with special attribute TypeConverterAttribute. Also, you can provide default value to your property by using another attribute DefaultValueAttribute. This will looks as following:

[TypeConverter(typeof(MyTextAlignmentTypeConverter))]
[DefaultValue(TextAlignment.Left)]
public TextAlignment TextAlignment
{
  get { return (TextAlignment)GetValue(TextAlignmentProperty); }
  set { SetValue(TextAlignmentProperty, value); }
}

How to build type converter

In order to build type converter, all you have to do is to build your own class, derived from TypeConverter. It also can be generic class. Then, implement necessary methods, that incorporate your business logic. Like this one, converter any enum value back and forward for TypeConverterAttribute

public class EnumValueConverter<T> : TypeConverter where T:struct
    {
        static EnumValueConverter()
        {
            if (!typeof(T).IsEnum) { Exceptions.ThrowInvalidOperationException("Cannot use this type for conversion"); }
        }

        public override bool CanConvertFrom(Type sourceType)
        {
            return Type.GetTypeCode(sourceType) == TypeCode.String;
        }

        public override object ConvertFrom(object value)
        {
            if (value == null)
            {
                typeof(T).ThrowConvertFromException(value);
            }
            if (value is string)
            {
                return ConvertFromString(value as string);
            }
            return (T)value;
        }

        public override object ConvertFromString(string text)
        {
            return (T)Enum.Parse(typeof(T), text, true);
        }

        public override string ConvertToString(object value)
        {
            return Enum.GetName(typeof(T), value);
        }
    }

Final result

Now, when we built converter and know how to use it, we can easily set it to any DependencyProperty requires conversion from / to enum

[TypeConverter(typeof(EnumValueConverter<LineStackingStrategy>))]
public LineStackingStrategy LineStackingStrategy
{
  get { return (LineStackingStrategy)GetValue(LineStackingStrategyProperty); }
  set { SetValue(LineStackingStrategyProperty, value); }
}

[TypeConverter(typeof(EnumValueConverter<TextAlignment>))]
[DefaultValue(TextAlignment.Right)]
public TextAlignment TextAlignment
  {
   get { return (TextAlignment)GetValue(TextAlignmentProperty); }
   set { SetValue(TextAlignmentProperty, value); }
  }

[TypeConverter(typeof(EnumValueConverter<TextWrapping>))]
public TextWrapping TextWrapping
{
  get { return (TextWrapping)GetValue(TextWrappingProperty); }
  set { SetValue(TextWrappingProperty, value); }
}

We done, have a nice day and be good people.

Stay tuned for release of BiDi support for Silverlight 2.0, sponsored by Development Platform Evangelism unit of Microsoft Israel

Silverlight Visual Tree Investigation

Wait a moment. Silverlight has Visual and Logical Trees as well as WPF? Not exactly. The design more similar to how it was in WinForms (Parent-Child relationship). But dev team made all possible to make it syntactically similar to WPF. Let’s start

Challenge: Find and hold references to all element, contains text.

Solution: Recursive VisualTreeHelper (introduced in SL2.0 b2)

First of all we should know, that Silverlight is not ready for manufacture, thus direct references might produce memory leaks, thus we’ll use WeakReference to hold pointers to SL objects.

First step: We know for sure, that TextBox and TextBlock controls has Text property, that holds only text. Also TextBlock can hold Inlines collection with Runs and LineBreaks. Let’s find them all

internal static List<WeakReference> GetTextElements(this DependencyObject root)
        {
List<WeakReference> res = new List<WeakReference>();
if (root is TextBlock | root is TextBox)
         {
                res.Add(new WeakReference(root));
         }

Next, we know, that ContentControl can hold text directly inside Content property. We’ll find them too, but should check if it holds text inside…

else if (root is ContentControl)
            {
                (root as ContentControl).CheckAndAddStringContentControl(ref res);
            }

Now ItemsControl. It can hold inside either ContentElement, TextBox, TextBlock or other. So we should check inside it too.

else if (root is ItemsControl)
            {
                ItemsControl ic = root as ItemsControl;
                for (int i = 0; i < ic.Items.Count; i++)
                {
                    if (ic.Items[i] is ContentControl)
                    {
                        (ic.Items[i] as ContentControl).CheckAndAddStringContentControl(ref res);
                    }
                    else
                    {
                        List<WeakReference> tmp = (ic.Items[i] as DependencyObject).GetTextElements();
                        if (tmp != null && tmp.Count > 0)
                        {
                            res.AddRange(tmp);
                        }
                    }
                }
            }

And last, but not least is to dig into all child of each control.

else
            {
                int cnt = VisualTreeHelper.GetChildrenCount(root);

                for (int i = 0; i < cnt; i++)
                {
                    DependencyObject d = VisualTreeHelper.GetChild(root, i);
                    List<WeakReference> tmp = d.GetTextElements();
                    if (tmp != null && tmp.Count > 0)
                    {
                        res.AddRange(tmp);
                    }

                }
            }
            return res;

Step two: Check whether object contains text inside. This one is simple. If not, we’ll call the main method to inter inside the control and check deeper.

internal static void CheckAndAddStringContentControl(this ContentControl cc, ref List<WeakReference> res)
        {
            if (cc.Content is string)
            {
                res.Add(new WeakReference(cc));
            }
            else
                res.AddRange(cc.GetTextElements());
        }

We done. Now we have WeakReferences collection of all items, which contains text in our page.

Have a good day and be nice one to another.

Quick Silverlight Tip: How to access HTML DOM from Silverlight and Silverlight managed objects from HTML?

After my session yesterday, I got number of email from people, who have a problem to access HTML DOM from Silverlight and vice verse. I want to answer to all of you by this post.

Access HTML from Silverlight

You have not do anything special in Silverlight to access it.  Your friend is HtmlPage.Window object. For example, if I want to execute window.open JavaScript method from Silverlight, all I have to do is to call:

public void OpenWindow()

        {

HtmlPage.Window.Invoke("open", new object[] { "http://blogs.microsoft.co.il/blogs/tamir", "login", "resizable=1,width=646,height=436" });

        }

HtmlPage.Window.Invoke also returns Object – this is the response of function executed.

Access Silverlight Managed Objects from HTML

Here you should remember two things:

  • You should mark both class and member you want to access with special attributes ScriptableType (for class) and ScriptableMember (for member)
  • Register Scriptable object anywhere (for example in Constructor).

So, if you want OpenWindow method to be exposed from the Page class to HTML, you should use following code:

    [ScriptableType]
public partial class Page : UserControl    {
public Page() {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("Page", this);
        }

[ScriptableMember]
public void OpenWindow() {
object o = HtmlPage.Window.Invoke("open", new object[] { "http://blogs.microsoft.co.il/blogs/tamir", "login", "resizable=1,width=646,height=436" });
        }
}

That’s all, folks. Be good people and have a nice day.

Here the script of test application:

Page.xaml

<UserControl x:Class="DomAccessDemo.Page"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Height="20">

<Grid x:Name="LayoutRoot" Background="White">

<Button Click="Button_Click" Content="Fun!"/>

</Grid>

</UserControl>

Page.xaml.cs

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Browser;

using System.ComponentModel;

namespace DomAccessDemo

{

    [ScriptableType]

public partial class Page : UserControl

    {

public Page()

        {

            InitializeComponent();

HtmlPage.RegisterScriptableObject("Page", this);

        }

private void Button_Click(object sender, RoutedEventArgs e)

        {

            OpenWindow();

        }

        [ScriptableMember]

public void OpenWindow()

        {

object o = HtmlPage.Window.Invoke("open", new object[] { "http://blogs.microsoft.co.il/blogs/tamir", "login", "resizable=1,width=646,height=436" });

        }

    }

}

DomAccessDemoTestPage.aspx

<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">

<head runat="server">

<title>Test Page For DomAccessDemo</title>

<script language="javascript">

function testSL()

        {

var xaml = document.getElementById("Xaml1");

            xaml.Content.Page.OpenWindow();

        }

</script>

</head>

<body style="height:100%;margin:0;">

<form id="form1" runat="server" style="height:100%;">

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<div style="height:100%;">

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/DomAccessDemo.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" />

</div>

</form>

<button onmouseup="testSL();">Test</button>

</body>

</html>

Printouts of the slides, presented on Silverlight 2.0 open house today

Thank you all, who participated today in Silverlight 2.0 for building Rich Internet Applications event. I uploaded printouts of the slides, presented during the session here. So, you can download it for reference.

I’m really interesting within your feedback (leave comments) in order for me to be able to enhance it for future events.

Also, I want to remind you, that due to lack of space we were unable to handle all those who want to attend, thus we decided to make another session within two weeks, so can register here. Remember, only registered attendees, who with confirmation received will allow to enter. So, hurry up.

If you want to learn more about Silverlight, you can register to attend Expert Days “Mastering Microsoft Silverlight 2.0 – 020 full day course, 13-August, were we’ll have Silverlight 2.0 deep dive training day. You can also review another two courses, I’ll have there:

Download slides from today session >>

Register to attend next event at 23 July >>

image

Thank you and leave a comment…

Please do not ask me. We cannot handle more…

Monday next week, I’m making half day session about building rich internet applications with Silverlight 2.0 in ILDC. The registration is over a while ago, but during this week, I got very large amount of email, IMs and phones calls with appeal to attend.

Sorry, we’re fully booked (currently about twice of available seats and it’s about 200) and cannot handle any more. Only those who registered and got confirmations will allow to enter. It is for your own convenience!

I promise, that within next two weeks I’ll make the same session again for all those, who want to come, but unable to register and attend (after a small arrangement, I’ll publish here next date).

Thank you again for understanding and see you soon.

Silverlight 2.0 for building Rich Internet Applications (local event)

If you are developing rich internet applications, web sites or just want to learn what’s new in Silverlight 2.0, you are invited to attend  local (Israel) Microsoft Event 30-June 8:30 AM- 12:30 PM in ILDC (new Microsoft R&D offices in Herzliya).

image

I’ll speak about what is Silverlight 2.0 and what are differences between SL 1.0 and SL 2.0. How to build RIA with Silverlight 2.0. What is DeepZoom and some cool parts of this new internet technology. How to use DataBinding, LINQ and Microsoft Media Encoder. As small bonus for this part of the event, we’ll compare different technologies with Silverlight such as Flex, Flash 10, Thermo and SVG to make you understand differences, “pros and cons” of using each one of those technologies for specific and identifiable needs.

Then we’ll deep dive into DataBinding and learn about DataTemplates, Styles, Accessibility, Authoring and Usability (including differences between Silverlight and WPF approaches). We’ll also take a look into LINQ-to-SQL and SEO of Silverlight applications.

Third part of this event will be dedicated to networking and interoperability. We’ll speak about internet protocols such as ATOM, RSS, REST, JSON, XMLWS, etc and usage of those protocols by Silverlight applications. We’ll understand how WCF can assist us to make our live easier. We’ll also touch security issues of Silverlight deployment and networking such as Cross Domain Policy, progressive download and deploy-on-demand.

I can make you sure, that if ”you are in” new web technologies and want to start using (or if you already using) Silverlight 2.0 for development of your applications – come and see me. Will be fun!

Note: Only a limited number of places available, so do not wait for MS newsletter (by the end of this month). Book now and come to attend this event – it’s free! (there is parking lot in floor -2)

I want to attend “Silverlight 2.0 introduction for building rich internet applications” event (30-June 8:30 AM – 12:30 PM, ILDC Herzelia, 5, Gav-Yam str, floor L2 13,Shenkar str)

See you there…

UPD 29-Jun: Next session will take place at 23 July, 8:30 AM-12:30 PM. Register by visiting Microsoft events web application at https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032382418&culture=he-IL and sign up.

FindResource replacement and how to change control style more then once in Silverlight 2.0 application

As deeper we’re digging in Silverlight 2.0, we finding more and more WPF things and we’re really missing in Silverlight. One of such things is FindResources.

In WPF I had Visual and Logical tree, so I was able to travel the tree to find resource I need. Let’s see an example of the application. We have one resource defined in App level

<Application.Resources>
        <Style TargetType=”Button” x:Key=”green”>
            <Setter Property=”Background” Value=”Green”/>
        </Style>
</Application.Resources>

Another resources are defined in different levels of Page

<UserControl.Resources>
        <Style TargetType=”Button” x:Name=”red”>
            <Setter Property=”Background” Value=”Red”/>
        </Style>       
    </UserControl.Resources>
    <Grid x:Name=”LayoutRoot” Background=”White”>
        <Grid.Resources>
            <Style TargetType=”Button” x:Name=”blue”>
                <Setter Property=”Background” Value=”Blue”/>
            </Style>
        </Grid.Resources>
        <Button Content=”Click me” Click=”Button_Click”>
            <Button.Resources>
                <Style TargetType=”Button” x:Name=”yellow”>
                    <Setter Property=”Background” Value=”#FFFFFF00″/>
                </Style>
            </Button.Resources>
        </Button>
    </Grid>

Now I want to call FindResource(“red”) and have my style ready for apply. I should not thing a lot about where the resource exists. There is no such method in Silverlight. If so, let’s see what we have. Looking in debugger I can find all my resources as members of the page.

image

But how to get them out? In Silverlight FrameworkElement, we have handy method named FindName. That’s exactly what we need. But how to get Application resources? Simple. Just look into it’s collection. Now, I can write small method, that help me to find resources in any level of Silverlight application.

public static object FindResource(string name)
        {
            if (App.Current.Resources.Contains(name))
            {
                return App.Current.Resources[name];
            }
            else
            {
                FrameworkElement root = App.Current.RootVisual as FrameworkElement;
                return root.FindResource(name);
            }
        }
        internal static object FindResource(this FrameworkElement root, string name)
        {
            if (root != null && root.Resources.Contains(name))
            {
                return root.Resources[name];
            }
            else
            {
                try
                {
                    return root.FindName(name);
                }
                catch { }               
            }

            return null;

Well now we can find all our resources. Let’s apply it to elements

Style s = (Style)Helper.FindResource(“red”);
b.Style=s;

It works perfect. Let’s take another one

Style s = (Style)Helper.FindResource(“blue”);
b.Style = s;

image

What is it? “Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))”. Why this happens only after applying second style? Let’s look into MSDN: “Styles are write-once in Silverlight. You can set a style to override a built-in default style, but attempting to set the same style again will result in an exception.”

What to do? We just have to write our own multi-use styling engine. First of all, we should get all setters of the style

foreach (Setter setter in value.Setters)

Then check target type and set values of setters to appropriate properties.

Type targetType = parent.GetValue(setter.Property).GetType();
parent.SetValue(setter.Property, setter.Value);

Another exception. That’s the mess? All values are strings. I need real values and I have no parsers. Fortunately, we have handy .NET method Convert.ChangeType. Let’s use it. Exception. Let’s check if the type is IConvertible (such as int, double, etc)

if(targetType is IConvertible)
            {
                return Convert.ChangeType(source, targetType, CultureInfo.InvariantCulture);
            }

No exception, but also no result. We need SolidColorBrush and we have only Color name, which is string. How to convert such string into Color instance and then into SolidColorBrush? The answer is reflection. We should write our own FromString converter. First of all let’s capitalize the string

static string Capitalize(this string str)
        {
            if (str.Length > 0)
            {
                return string.Concat(str.Substring(0, 1).ToUpper(), str.Substring(1, str.Length – 1));
            }
            return str;
        }

Then check whether I have static member with the same name in Colors class (not by hand of cause)

MemberInfo[] infos = typeof(Colors).GetMember(color.Capitalize());

If I have, let’s invoke it

if (infos.Length > 0)
            {
                return (Color)typeof(Colors).InvokeMember(color.Capitalize(), BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty, null, null, null);
            }

Well done. Now we can use strings which have names of colors and convert them into real color. But what to do with not “well known colors”? Parse it

else if (color.IndexOf(‘#’) == 0)
            {
                return Color.FromArgb(
                    byte.Parse(color.Substring(1, 2), NumberStyles.HexNumber),
                    byte.Parse(color.Substring(3, 2), NumberStyles.HexNumber),
                    byte.Parse(color.Substring(5, 2), NumberStyles.HexNumber),
                    byte.Parse(color.Substring(7, 2), NumberStyles.HexNumber));
            }

We done. Just write another attached method and use in in our converter

internal static Color ParseKnownColor(string color)
        {
            MemberInfo[] infos = typeof(Colors).GetMember(color.Capitalize());
            if (infos.Length > 0)
            {
                return (Color)typeof(Colors).InvokeMember(color.Capitalize(), BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty, null, null, null);
            }
            else if (color.IndexOf(‘#’) == 0)
            {
                return Color.FromArgb(
                    byte.Parse(color.Substring(1, 2), NumberStyles.HexNumber),
                    byte.Parse(color.Substring(3, 2), NumberStyles.HexNumber),
                    byte.Parse(color.Substring(5, 2), NumberStyles.HexNumber),
                    byte.Parse(color.Substring(7, 2), NumberStyles.HexNumber));
            }
            return Colors.White;
        }
……

else if(targetType == typeof(SolidColorBrush))
            {
                return new SolidColorBrush(ParseKnownColor(source));
            }

Now you turn to continue with string to object convention for your own need. Starting today you know how to do it.

Here the result

Have a nice day and be good people

Source code for this article>>

Networking (raw sockets) in Silverlight and WPF – messaging in general

You, probably, know how to use raw sockets in WinForms. It’s pretty the same in WPF, however it is very different (and limited) in Silverlight. Today, we’ll create sample application in Silverlight, WPF and WinForm that sending and receiving updates via TCP as well as broadcasting it via UDP (singlecast and multicast). So let’s start.

image

First of all we’ll create WinForms server, that should distribute updates. It knows what the time is it now and broadcasting the time message via UDP. Also it has TCP server, that distribute updates to all it’s clients.

First of all UDP. We should create the working Socket first. It uses all ip addresses to broadcast changes via given port. In order to make the socket to be multicast, we should set appropriate socket options. Let’s see the code.

lock (this)
                {
                    if (m_mainSocket == null)
                    {
                        m_mainSocket = new Socket(AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp);

                        IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);

                        m_mainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

                        m_mainSocket.Bind(ipLocal);
                    }
                    IPAddress ip = IPAddress.Parse(castGroupIp);

                    EPCast = new IPEndPoint(ip, port);
                    m_mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
                }

Now, the TCP part. It’s very similar (for server we do not need specific IP address to bind), however, we should not set multicast options there aside with begin listening right after connection was established.

lock (this)
                {
                    if (m_mainSocket == null)
                    {
                        m_mainSocket = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream,
                            ProtocolType.Tcp);
                        IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
                        m_mainSocket.Bind(ipLocal);
                        m_mainSocket.Listen(Backlog);
                        m_mainSocket.BeginAccept(new AsyncCallback(acceptCallback), null);
                    }
                }

In order to send data via UDP. All we have to do is to write it into current socket.

socket.SendTo(data, EPCast);

In TCP world, we should first know who we want to sent to, thus we have to enumerate all incoming clients to save the references to their sockets.

Socket workerSocket = m_mainSocket.EndAccept(asyn);
m_workerSocketList.Add(workerSocket.GetHashCode(), workerSocket);

m_mainSocket.BeginAccept(new AsyncCallback(acceptCallback), null);

Then when we know who to send, all we have to do is to send

socket.Send(data);

Now, when we know how to send, we should learn how to receive network messages. It’s exactly the same within TCP or UDP. First check is there is data to receive, then receive it.

if (m_pfnCallBack == null)
                m_pfnCallBack = new AsyncCallback(dataReceivedCallback);
            SocketPacket theSocPkt = new SocketPacket(socket, bufferSize);

            socket.BeginReceive(theSocPkt.dataBuffer, 0,
                theSocPkt.dataBuffer.Length,
                SocketFlags.None,
                m_pfnCallBack,
                theSocPkt);

We done with WinForms and WPF networking. So, we can start with graphics. Since we have no a lot of graphics in WinForms, we’ll focus on WPF stuff.

We’ll use ContentControl to present the content with datatemplate of our message. We’ll create Ellipse for the clock and three rectangles for clock hands. Once data received, we should change RotateTransform value of RenderTransform for each of our rectangles (first set the TransformOrigin to the center of the clock). Bind it together

<Ellipse Width=”250″ Height=”250″ StrokeThickness=”2″ Stroke=”Black”/>
                <Rectangle Height=”100″ Width=”20″ RadiusX=”10″ RadiusY=”10″ Fill=”Black” RenderTransformOrigin=”0.5,1″>
                    <Rectangle.RenderTransform>
                        <TransformGroup>
                            <RotateTransform/>
                            <TranslateTransform Y=”25″ X=”115″/>
                        </TransformGroup>
                    </Rectangle.RenderTransform>
                </Rectangle>
                <Rectangle Height=”125″ Width=”10″ RadiusX=”5″ RadiusY=”5″ Fill=”Black” RenderTransformOrigin=”0.5,1″>
                    <Rectangle.RenderTransform>
                        <TransformGroup>
                            <RotateTransform/>
                            <TranslateTransform Y=”0″ X=”120″/>
                        </TransformGroup>
                    </Rectangle.RenderTransform>
                </Rectangle>
                <Rectangle Height=”125″ Width=”4″  RadiusX=”2″ RadiusY=”2″ Fill=”Black” RenderTransformOrigin=”0.5,1″>
                    <Rectangle.RenderTransform>
                        <TransformGroup>
                            <RotateTransform/>
                            <TranslateTransform Y=”0″ X=”123″/>
                        </TransformGroup>
                    </Rectangle.RenderTransform>
                </Rectangle>

How we should convert values received to the angle to turn the clock hand. We can use only one converter here and bind to the message, according following formula

HourAngle = (Hours * 30)+(12*Minutes/60);
MinuteAngle = Minutes * 6; (it’s 360/60)
SecondAngle = Seconds * 6;

Let’s run it. Nothing happens. Why? The reason is, that even each property of the object changes, it does not trigger binding, due to the fact, that whole object has not been changed. In order to fix it, we should bind to each property. And in case of hours to Hours and Minutes properties both. But how to make my converter to be single and multi value converter? Simple – all this about interfaces. So, following converter will do the work

public class TimeToAngleConverter : IValueConverter, IMultiValueConverter
    {       

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (double)value * 6;
        }

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return ((double)values[0] * 30) + (12 * (double)values[1] / 60);
        }

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

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)        { throw new NotImplementedException(); }

      }

Now binding expressions

<Rectangle Height=”100″ Width=”20″ RadiusX=”10″ RadiusY=”10″ Fill=”Black” RenderTransformOrigin=”0.5,1″>
                    <Rectangle.RenderTransform>
                        <TransformGroup>
                            <RotateTransform>
                                <RotateTransform.Angle>
                                    <MultiBinding Converter=”{StaticResource timeToAngle}”>
                                        <Binding Path=”Hour”/>
                                        <Binding Path=”Minute”/>
                                    </MultiBinding>
                                </RotateTransform.Angle>
                            </RotateTransform>
                            <TranslateTransform Y=”25″ X=”115″/>
                        </TransformGroup>
                    </Rectangle.RenderTransform>
                </Rectangle>
                <Rectangle Height=”125″ Width=”10″ RadiusX=”5″ RadiusY=”5″ Fill=”Black” RenderTransformOrigin=”0.5,1″>
                    <Rectangle.RenderTransform>
                        <TransformGroup>
                            <RotateTransform Angle=”{Binding Path=Minute, Converter={StaticResource timeToAngle}}”/>
                            <TranslateTransform Y=”0″ X=”120″/>
                        </TransformGroup>
                    </Rectangle.RenderTransform>
                </Rectangle>
                <Rectangle Height=”125″ Width=”4″  RadiusX=”2″ RadiusY=”2″ Fill=”Black” RenderTransformOrigin=”0.5,1″>
                    <Rectangle.RenderTransform>
                        <TransformGroup>
                            <RotateTransform Angle=”{Binding Path=Second, Converter={StaticResource timeToAngle}}”/>
                            <TranslateTransform Y=”0″ X=”123″/>
                        </TransformGroup>
                    </Rectangle.RenderTransform>
                </Rectangle>

We done with graphics in WPF. Let’s start it over in Silverlight. We cannot do at least half of what has been done in WPF. MultiBinding is not supported, there is no implicitly templating and Transform class does not support Binding. What to do? Let’s remember old good world.

Set the control without using templates, then find resources and save references and set values explicitly (after subscribing to OnPropertyChanged event of cause. Other words, make binding with your own hands.

void onLoaded(object s, RoutedEventArgs e)
        {
            mt = ((RotateTransform)FindName(“mTransform”));
            ht = ((RotateTransform)FindName(“hTransform”));
            st = ((RotateTransform)FindName(“sTransform”));
            ((NetTimeProvider)Resources["timeProvider"]).PropertyChanged += new PropertyChangedEventHandler(Page_PropertyChanged);
        }

        RotateTransform mt, ht, st;

        void Page_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //Binding to Transform does not supported (yet??);
            NetTimeProvider s = sender as NetTimeProvider;
            Dispatcher.BeginInvoke((SendOrPostCallback) delegate (object o)
            {
                NetTimeProvider ntp = o as NetTimeProvider;
                if (e.PropertyName == “Hour”)
                {
                    ht.Angle = (ntp.Hour * 30) + (12 * ntp.Minute / 60); ;
                }
                else if (e.PropertyName == “Minute”)
                {
                    mt.Angle = ntp.Minute * 6;
                }
                else if (e.PropertyName == “Second”)
                {
                    st.Angle = ntp.Second * 6;
                }
            }, s);
        }

Now, when we have layout for our Silverlight control, we should connect to distribution network server. Reuse the manager, used for Winforms and WPF? We can’t. Silverlight is subset of .NET framework, and it is not relays on it, so we have to write new network provider for Silverlight. UDP is not supported in Silverlight, thus we’ll use TCP networking. Let’s see what we have. WebRequest/WebResponse HttpWebRequest/HttpWebResponse – to use it – no. Our server neither HTTP nor Web server. We should use raw sockets in Silverlight. Socket class exists in System.Net dll for Silverlight, however it is very limited. Let’s make the connection. First of all, we should know what IP to connect.

Due to security restrictions we cannot do DNS queries in Silverlight. From the other hand we do not want to restrict it to hardcoded name or IP address. In application class of Silverlight we have very handy property, named DnsSafeHost (Application.Current.Host.Source.DnsSafeHost). So let’s use it.

What about ports? Can I use TCP socket for any port I want? No. This is another security restriction. The only port range able available for Silverlight is 4502-5432 (only 30 ports). So with those restrictions we’ll create the connection as following.

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            DnsEndPoint ep = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4502);
            SocketAsyncEventArgs args = new SocketAsyncEventArgs()
            {
                RemoteEndPoint = ep
            };
            args.Completed += onConnected;
            socket.ConnectAsync(args);

Now we should check if the connection is established successfully. The only place we can do it is in onConnected handler. Here also we’ll reuse completed event of SocketAsyncArgs to perform read sequence. Upon the end of the handler we’ll try to read something from inline socket.

void onConnected(object sender, SocketAsyncEventArgs e)
       {
           if (e.SocketError == SocketError.Success)
           {
               e.Completed -= onConnected;
               e.Completed += onRead;
               Message = “Connected”;
           }

           readMoreData(e);
       }

If you remember in regular framework we can wait on socket. We can do it as well in Silverlight.

void readMoreData(SocketAsyncEventArgs e)
{
    e.SetBuffer(buffer, bytesRead, (buffer.Length – bytesRead));
    if (!socket.ReceiveAsync(e))
    {
        onRead(socket, e);
    }
    else
    {
        Message = “Disconnected”;
    }

}

So, if everything is ok and we have data in the socket, let’s read it. There is some fault proofing should be done in it. First we should check if we go all the message. We know, that the message size is 20 bytes (5 integers – we check first four). Then we should check, that the message we got is our message. So in the header we’ll check for Magic number. Then if it’s ok we’ll parse it and fill all properties of our class.

void onRead(object sender, SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred > 0)
            {
                bytesRead += e.BytesTransferred;
                if (bytesRead == 20 && BitConverter.ToUInt32(buffer, 0) == Magic)
                {
                    Hour = BitConverter.ToInt32(buffer, 4);
                    OnPropertyChanged(“Hour”);
                    Minute = BitConverter.ToInt32(buffer, 8);
                    OnPropertyChanged(“Minute”);
                    Second = BitConverter.ToInt32(buffer, 12);
                    OnPropertyChanged(“Second”);
                    bytesRead = 0;
                }
                readMoreData(e);
            }
        }

If everything fine, we’ll return to wait for next message to arrive.

We done. WinForms, WPF and Silverlight speaks over the network one with another, by using TCP and UDP raw sockets. What can be better? When our message is not just clock information, but something related to gaming world (e.g. current position or state of other network players). What am I speaking about? Come to reveal it on my session DEV335: Game Development Using
Microsoft’s Latest Technologies
in TechEd Israel.

Have a nice day and be good people.

Source code for this article.

Recommended

 

Sponsor


Partners

WPF Disciples
Dreamhost
Code Project