Mobile version of this blog
10x to great service of mofuse, I have mobile version of this blog now. So bookmark it: http://m.0×15.net/
Here the QR code for your convenience
July 14th, 2008 · Comments (2)
TechEd preparation session + other announcements
If you want to attend my preparations before TechEd, you’re invited to attend 27-Jul in Microsoft Ra’anana.
What is preparation session? This is the training for myself. I’ll present all four session (each one is an hour + one hour rep.) This is your chance to hear live my TechEd South Africa sessions, without paying the fee (ZAR 4,500 which is about $600)
Please note, that all lectures are in English (not in Hebrew)
Here the agenda for 27-Jul (Sunday). It will take place in Microsoft Israel building in 2, Ha’Pnina st. Ranana, Israel
| Time | Session title | Conference room |
| 8:30-10:30 | Creating Rich Applications with Windows Presentation Foundation (300) | Media Center |
| 11:00-13:00 | WPF Performance (400) | Visual Studio |
| 14:30-16:30 | Game Development Using Microsoft’s Latest Technologies (300) | Vista |
| 17:00-19:00 | Understanding Reflection (400) | Vista |
Also, be sure, you’re attending my session in Expert Days 11-14 August
- 12-Aug, Windows Presentation Foundation for fellow developers – 027
- 13-Aug, Mastering Microsoft Silverlight 2.0 – 020
- 14-Aug, Advanced .NET 3.5 SP1 – Windows Presentation Foundation – 011
And/or if you were not able to attend Silverlight 2.0 for building Rich Internet Applications event, you are welcome to book the next session at 23-Jul
That’s all for now, see ya…
July 13th, 2008 · Comments (4)
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.
July 6th, 2008 · Comments (3)
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:
- 12-Aug “Windows Presentation Foundation for fellow developers – 027”
- 14-Aug “Advanced .NET 3.5 SP1 – Windows Presentation Foundation – 011”
Download slides from today session >>
Register to attend next event at 23 July >>
Thank you and leave a comment…
June 30th, 2008 · Comments (2)
Silverlight 2.0 for building Rich Internet Applications (Local Event) – Take 2
As promised earlier, the next session of Silverlight 2.0 for building Rich Internet Applications will take place at 23 July, 8:30 AM-12:30 PM in ILDC. This is exactly the same session for those, who unable to attend tomorrow due to lack of place.
Please, this time, try to register as soon as possible to assure seat assignment.
Register to attend Silverlight 2.0 for building RIA >>

June 29th, 2008 · Comments (1)
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.

June 25th, 2008 · Comments (0)
How to consume WCF or Webservice from Vista Sidebar gadget by using Silverlight?
The challenge today is really simple. All we have to do is to write Silverlight Vista Sidebar Gadget, that consumes either WCF, ASMX or REST based service. Really simple, isn’t it? Let’s start
Build server side services
We should start from services. This is very straight forward mission. Here the logic I want to implement
public string Echo(string input)
{
return string.Format("ACK from {0}", input);
}
Well, WCF? We should mark service and operation contracts. That’s all
[ServiceContract(Namespace = "")]
public class EchoService
{
[OperationContract]
public string Echo(string input)
{
return string.Format("ACK from WCF with {0}", input);
}}
This does not works. Why? Silverlight knows only consumes ASP.NET compatible (simplified) web services, thus we should add following attribute to the our class attributes collection
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EchoService
{
Now, the service is discoverable and accessible by Silverlight. Great news. Now let’s put it into our shared host. Hmm, we got strange error: “Deploying WCF Services: This collection already contains an address with scheme http.” What the hell is it?
This is shared hosting problem. Your host provider uses virtual IP and host addresses and has number of different web services, sitting on the same shared host. How to solve it?
Simple, all you have to do is to specify your own service host factory. Here the example of classes to put into code behind
class SLHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
SLHost customServiceHost =
new SLHost(serviceType, new Uri("[Your URL goes here]",UriKind.Absolute));
return customServiceHost;
}
}class SLHost : ServiceHost
{
public SLHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{ }
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
}
}
And one attribute into your service tag
Factory="SLHostFactory"
Now it works. So what’s next? Build ASMX web service. This is even simpler
[WebMethod]
public string Echo(string input)
{
return string.Format("ACK from web service with {0}", input);
}
We done, now either WCF and Web services are accessible from your Silverlight application. So, add Service reference and consume it
Building client side
Inside code behind of your Silverlight project, you should define two proxies – one for Web Service and another for WCF service. Bother services implements the same interface, so it should not be a problem
ServerEcho.EchoServiceClient proxy;
WebServiceEcho.EchoWebServiceSoapClient wsProxy;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
proxy = new ServerEcho.EchoServiceClient();
proxy.EchoCompleted += new EventHandler<ServerEcho.EchoCompletedEventArgs>(proxy_EchoCompleted);wsProxy = new SLGadget.WebServiceEcho.EchoWebServiceSoapClient();
wsProxy.EchoCompleted += new EventHandler<SLGadget.WebServiceEcho.EchoCompletedEventArgs>(wsProxy_EchoCompleted);
}
Silverlight work only asynchronously, thus you should begin to understand, that synchronous programming is for pussies
. Consume it
private void WCF_Click(object sender, RoutedEventArgs e)
{
proxy.EchoAsync(txt.Text);
}private void WS_Click(object sender, RoutedEventArgs e)
{
wsProxy.EchoAsync(txt.Text);
}
And Update output
void wsProxy_EchoCompleted(object sender, SLGadget.WebServiceEcho.EchoCompletedEventArgs e)
{
txt.Text = e.Error == null ? e.Result : (e.Error.InnerException != null ? e.Error.InnerException.ToString() : e.Error.Message);
}void proxy_EchoCompleted(object sender, ServerEcho.EchoCompletedEventArgs e)
{
txt.Text = e.Error == null ? e.Result : (e.Error.InnerException != null ? e.Error.InnerException.ToString() : e.Error.Message);
}
Now let’s run it. What? Another error? Security? Access denied? Of cause you have no crossdomain.xml.
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-access-from domain="*" /> </cross-domain-policy>
What? You have it and still getting the same error? Look into sniffer. You application is looking for other file, named clientaccesspolicy.xml. Why? According the documentation, you can use either… Hm, another bug with WCF consuming. Never mind, let’s put it too
<?xml version="1.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"> <domain uri="*"/> </allow-from> <grant-to> <resource path="/" include-subpaths="true"/> </grant-to></policy> </cross-domain-access> </access-policy>
Very well, now we are ready to run our application. It works! So, the only thing we should do is to pack it into MyGadget.gadget directory and put inside %userprofile%\appdata\local\microsoft\windows sidebar\gadgets together with gadget.xml manifest.
But… It stopped working… What’s the problem?
Very client side networking in Silverlight
The problem is, that SideBar executes it’s gadgets with local path, not with network path. Silverlight cannot use any network provider, when running locally. Why? Actually I do not know (maybe to prevent local applications development). so what to do?
Simple! Microsoft SideBar knows to run cross domain AJAX without any warnings and problems. So why not to use external XmlHttp from JavaScript for network access. Let’s do it
First we should initialize XMLHttpRequest object in JavaSctipt
var xObj;
function getEchoWCF(text) {if(xObj == null) {
xObj = new XMLHttpRequest();}
else if(xObj) {
xObj.abort();
}
Then create SOAP request to WCF or WebService
var sURL = "[Path yo your service]";
//Build SOAPvar sReq = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><Echo><input>"+text+"</input></Echo></s:Body></s:Envelope>";
xObj.open("POST", sURL, true);
xObj.setRequestHeader( "Content-Type", "text/xml; charset=utf-8" );
xObj.setRequestHeader( "Cache-Control", "no-cache" );
…
xObj.send(sReq);
After the request created and send we should handle result. So we need an access from HTML page, hosting Silverlight object to Silverlight. Simple. “ScriptableMember – ScriptableType”, remember?
[ScriptableType]
public partial class Page : UserControl
{
…
[ScriptableMember]
public void UpdateResponse(string result)
{
Now return the result
xObj.onreadystatechange = function() {
if (xObj.readyState === 4) {if (xObj.status && xObj.status === 200) {
var control = document.getElementById("silverlightControl");control.Content.Page.UpdateResponse(xObj.responseText);
}
}
But this is not enough. We also should know to call Javascript from Silverlight… This is really simple
private void JS_Click(object sender, RoutedEventArgs e)
{HtmlPage.Window.Invoke("getEchoWCF", txt.Text);
}
We done. Now you can pack your Silverlight control, together with hosting HTML and Javascript into windows sidebar gadget and use it even with external network support.
Have a good day and be nice people.
June 23rd, 2008 · Comments (10)
Quick Silverlight tip: How to set format and validate value in TextBox?
Today morning I got an email from one of Microsofties, asking following question:
Is there any way to set format and validation on TextBox in Silverlight 2. TextBox format: Date Format, Currency Format etc, TextBox validation: Regular date expression, should allow only numeric etc. If it’s possible out-of-box how do I do it?
The answer is, that there is no data validation or formatting in Silverlight, however it’s very simple to build converter to format binded value. Here the code of the converter:
public class TextFormatConverter:IValueConverter
{#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Format(value, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Format(value, parameter);
}object Format(object value, object param)
{
if (value == null)
return value;
int ri;
double rd;
if (int.TryParse(value.ToString(), out ri))
{
return string.Format(param.ToString(), ri);
}
else if (double.TryParse(value.ToString(), out rd))
{
return string.Format(param.ToString(), rd);
}
else
{
return string.Format(param.ToString(), value);
}
}#endregion
}
Here the usage:
<TextBox Text="{Binding String, Source={StaticResource data}, Mode=TwoWay, Converter={StaticResource formatConverter}, ConverterParameter=’{0:0.00}’}" />
Regarding validators – There is no ValidationRule or IDataErrorInfo in Silverlight right now. If you want to have it, you’ll need to write your own custom TextBox with validation. But, I’ll speak next time about it. ValidatingTextBox with format support will be a part of Silverlight controls library when I’ll have a time for it.
Have a nice day and be good people.
June 18th, 2008 · Comments (5)
Quick Silverlight tip: How to open new window or tab by using HyperlinkButton and Ctrl-Shift modifiers
Regular behavior of any HTML anchor element is to open new Window if you’re clicking the link with Shift key and new Tab, if you’re clicking with Ctrl key or middle mouse button. Unfortunately, Silverlight HyperlinkButton does not support opening new window or tab. It also does not support key modifiers. What to do?
(rotary reading desk – first tabbed browser, invented in 1588. via Athanasius Kircher society)
First of all, request this feature. This is regular behavior and there is no reason not to support it in Silverlight. Next, we should do something to fix it by now. So let’s start.
We should understand what happens under the hoods of HyperlinkButton. It does not generate html anchor, however it uses window.navigate to move. One of HyperlinkButton properties is TargetName – this one is actually html ”target” attribute. So we can just change it according the keystrokes. This is acceptable, but ugly solution. The better one is to subclass HyperlinkButton and check KeyModifiers. Then void Click event and navigate
if(Keyboard.Modifiers == ModifierKeys.Control | Keyboard.Modifiers == ModifierKeys.Shift)
{
this.TargetName=”_blank”;
}
base.OnClick();
So far so good, but not good enough. What will happen if user explicitly set TargetName Value? We’ll override it and this is something we wont to do. Also, following approach will work differently between browsers. For example in IE it will open new window, while in FF – new tab by default. So how to avoid it?
We can use HtmlPage.Window.Navigate method to assure opening of new window. Navigate method receives three parameter, Uri for navigation address, target frame and “target features”. What are those target features? Actually, it parameters we’re using in JavaScript for window.open method. Thus HtmlPage.Window.Navigate(new Uri(“http://blogs.microsoft.co.il/blogs/tamir”,null,”menubar=1,resizable=1,width=350,height=250”) will open resizable window with menubar and size of 350×250.
Very well. Now we almost finished, but how to assure, that I opened new tab? Actually, we cannot until all browsers will support CSS3. In CSS3 we have style attributes, which can target into tab or window. By now, the only workaround is to use IWebBrowser2::Navigate2 method for IE and pass 0×1000 (navOpenInBackgroundTab) as second parameter. This “heck” can only be done in Full trust mode. For Mozilla (FireFox or any Geco + ancestors) we should use nsIBrowserWindow::OPEN_NEWTAB override for nsIBrowserWindow::OPEN_NEWWINDOW. There is no known way to do it for Safari.
So, the best thing can be done is inheritance of build-in feature of any supported browser to handle Ctrl/Shift modifiers for force opening links in other tabs or new windows.
Have a nice week and be good people.
May 25th, 2008 · Comments (4)
Action required: Smart client users group
Recently I browsed INETA to seek for some group and was really surprising. There is no Smart Client user group registered there. Maybe there is a reason? Let’s understand what Smart Client is?
According wikipedia, the term “Smart Client” is meant to refer to simultaneously capturing the benefits of a “thin client” (zero-install, auto-update) and a “fat client” (high performance, high productivity). However, I think, that this term is much wider. It is not only thin-fat client application, it’s also most of applications we’re using today.
Thick Client
We always want to provide our users with best experience and increase their performance. However we are (as developers) want to avoid complicated development and deployment. This why we should know as much as possible about user’s system, when users do not want to have real footprint in their systems. That’s dilemma. Is it possible to solve it? Let’s look deeper…
Are we really need installation? Most of old software installations put things in registry. It because you were never sure what client has in his system and were our application can put files or temporary data. Today, when we have local application or user isolated storage, so we not really need to use registry. Maybe only for our own ego – this is cool to have something like “HKLM/Software/MYNAME” in 1,000,000 user’s computers…
No installation is good, but what to me with maintenance. We want our system connected…
Thin Client
Could you imagine your user to visit product site twice a week to see what’s going on? I can not. However I know, that if I’ll ask him first about automatic updates and he’ll agree to forget about application maintenance, his experience will be much better.
So,we are connected. What now? I want to make time reporting system. Web service? Maybe some kind of distributed application. Maybe, even Twitter? This way we can be sure, that our data is safe and if user reinstall whole system, he do not really need to care about backups.
But users not always have internet access. Sometimes they are offline. How to solve the problem of occasionally connected users? I do not want him every lunch want for two minutes, until I realize, that there is no internet connection and will not even give him a chance to use the application?
So, we also want our system to be useful offline. But what’s up with Web 10.0? We want millions. We want very broad reach for our application. Also we want to be able to manage application updates remotely?
Let’s take a look into other pan of application development. Do you like JavaScript? I do not! I think it’s too complicated to develop things for web. We should invest into at least 50% of coverage and integration tests, while giving customers pretty poor user experience. What is we want to provide the same look and feel everywhere? In web, desktop, mobile and other devices? Our customers want the application everywhere?
Summary
This is exactly what Smart client designed for. Technologies such as .NET, WPF, Silverlight from Microsoft, Flex, Thermo from Adobe and others tries to make you to be there with your application. But how to do it? How to answer all those hard questions, I asked?
I want to announce new (currently virtual) user group, dedicated to Smart Client development. I do not want to restrict this group geographically, due to fact, that current infrastructures allows us to forget about distances and be together. Join today “Smart Client development” user group.
In order to join, just send me an email to tamir [at] khason.biz with information about you. I put the request to create this user group in INETA. Once it will be opened, I’ll send everyone email to register and connect them selves to this group.
Be in touch.
May 22nd, 2008 · Comments (25)
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard




