Allowing Silverlight to access a cross domain service without a policy file

I wanted to access a site that provides gaming information (http://steamcommunity.com/) as an xml string. However, this particular site doesn’t seem to have a policy file which means I can’t use WebClient to access the data. So I thought I’d be clever and use Silverlight 4’s WebControl. So I wrote a quick OOB with elevated trust and sure enough it downloaded the page. However, when you ask for the string of HTML that’s what you get, HTML encoded XML…yuk. It then occurred to me that perhaps WebClient would work now I’m running with elevated permissions. Sure enough it does. So if you’re the position to run OOB with elevated permissions then you can use Silverlight to access a non-policy “web service”.

Getting starting with MS Ajax & WCF Service

After a fair bit of reading about live binding et al, I decided to have a play with it myself. However, I found it wasn’t that obvious how to get it going so I thought I’d better record what I had to do.

1. Download the latest version of AJAX kit in order to get hold of System.Web.Ajax.dll

2. Create a ASP Web Application Project, if you want to use my sample then call the project WebAjaxSvcTest

3. Reference Ajax dll from (1)

4. Add a new item to the project –> Add Ajax-enabled WCF Service (I left it at Service1). This should create a default method called DoWork

5. In the properties of the project change the Web setting to use local IIS Server

6. From IIS try and browser the service you created (i.e. right click on the webservce.svc file and browse). If it’s ok then skip to 8

7. WCF may not be installed on your server,you’ll need to run the configuration utility, for me that is; D:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –r

8. Change your default aspx page to look something like;

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebAjaxSvcTest._Default" %>

<%@ Register Assembly="System.Web.Ajax" Namespace="System.Web.UI" TagPrefix="asp" %>

<!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 runat="server">
    <title></title>
      <script type="text/javascript" src="http://ajax.microsoft.com/ajax/beta/0911/Start.js"></script>
<script type="text/javascript">

    Sys.require([Sys.components.dataView, Sys.scripts.WebServices], function() {
        //Scripts loaded
    });
    </script>
</head>
<body xmlns:sys="javascript:Sys">
    <form id="form1" runat="server">   
    <div>

<script type="text/javascript">
    Sys.require([Sys.components.dataView, Sys.scripts.WebServices], function() {
        Sys.create.dataView("#CustomerView",
    {
        dataProvider: "/WebAjaxSvcTest/Service1.svc",
        fetchOperation: "DoWork",
        autoFetch: true,
        itemRendered: CustomerRendered
    });
        function CustomerRendered(dataView, ctx) {
            Sys.bind(Sys.get("li", ctx), "innerHTML", ctx.dataItem, "ContactName");
        }
    });

</script>

<div id="CustomerView" class="sys-template">
    <ul>
        <li />
    </ul>
</div>

    </div>
    </form>
</body>
</html>

9. Take care to change the dataprovider to be the path to your service, in my example my project (and therefore site) it called WebAjaxSvcTest and I called my Service Service1 😉

10. Hopefully you should have a demo that now runs the DoWork method and does absolutely nothing. Hopefully we now have the basic plumbing to do something interesting.

Sharing ASP Session state with Silverlight

I’ve been working on a Silverlight project that where the SL application is used within an authenticated ASP.net site. During my testing I found a problem where using Silverlight 3’s Out-Of-Browser feature seem to lose the session token between calls to the site, i.e. I could logon but the next call would fail as if the user had not logged on. After a couple of Twitter conversations it became apparent that it should work. So I decided to take my testing back to basics, so first off can a Silverlight application use ASP session state?

  1. Create a basic Silverlight application – create a Silverlight application with a web project to host it
  2. Create a basic web service – with the web project selected add a new Silverlight WCF service, called SessionTest.svc
    image
  3. Implement some very simple interactions with the Session State

    [ServiceContract(Namespace = "")]

        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

        public class SessionTest

        {

            [OperationContract]

            public void SetState(string value)

            {

                // Add your operation implementation here

                HttpContext.Current.Session["TestState"] = value;

                return;

            }

     

            [OperationContract]

            public string GetState()

            {

                // Add your operation implementation here

                return (string)HttpContext.Current.Session["TestState"];

            }

        }

  4. Add a Service Reference from your Silverlight application to your service, add appropriate using statements to your code-behind.

  5. Create some simple controls in your Silverlight application

    <StackPanel>

        <StackPanel Orientation="Horizontal">

            <Button x:Name="ButtonGetState"  Content="Get State" Click="ButtonGetState_Click" Width="60" ></Button>

            <TextBlock x:Name="TextBlockCurrentState" Width="100"></TextBlock>               

        </StackPanel>

        <StackPanel Orientation="Horizontal">

            <TextBox x:Name="TextBoxNewState" Text="" Width="100"></TextBox>

            <Button x:Name="ButtonSetState" Content="Set State" Click="ButtonSetState_Click" Width="60"></Button>

        </StackPanel>

    </StackPanel>

  6. Add code to the Silverlight application to communicate with the Service

    private void ButtonGetState_Click(object sender, RoutedEventArgs e)

            {

                SessionTestClient client = new SessionTestClient();

                client.GetStateCompleted += (object completedSender, GetStateCompletedEventArgs completedE) =>

                    {

                        if (completedE.Error == null)

                        {

                            TextBlockCurrentState.Text = completedE.Result;

                        }

                    };

                client.GetStateAsync();

            }

     

            private void ButtonSetState_Click(object sender, RoutedEventArgs e)

            {

                SessionTestClient client = new SessionTestClient();

                client.SetStateCompleted += (object completedSender, AsyncCompletedEventArgs completedE) =>

                    {

                        if (completedE.Error == null)

                        {

                            TextBlockCurrentState.Text = "";

                        }

                    };

                client.SetStateAsync(TextBoxNewState.Text);

            }

  7. Run the code, you should see that after you set a value you can retrieve the same value.

So we now know for sure that we can communicate with ASP.net and share the session state with the page. If you make the Silverlight application OOB (select project properties and check the OOB box) you’ll see that it continues to work without any problems. So this is good news, all I have to do now is track down why it isn’t working in my real application.

Canon 350D slant or tilt problem

A problem I seem to be having with my Canon 350D is every now and then I get a nasty tilting, esp. with landscape shots. So this picture was taken by carefully lining the horiz’ focus points with the horizon line. See for yourself what happened…
 
 

Comparing Cameras

I’m trying to learn how to use my Canon 350D to get decent shots but I’m finding it difficult. As a comparison I’ve got two shots of (almost) the same scene at the same time, one is from the Canon 350D, the other from my pocket Sony, any comments as to which you prefer and why the Canon one is worse (guess my favourite) then please say…
[EDIT] The upload process has destroyed the size of the images, I’m looking for another host now…
 
350D –
Camera Model Canon EOS 350D DIGITAL
Shooting Mode A-DEP
Tv( Shutter Speed ) 1/800
Av( Aperture Value ) 3.5
Metering Mode Evaluative Metering
Exposure Compensation 0
ISO Speed 100
Lens 18.0 – 55.0 mm
Focal Length 21.0 mm
Image Size 3456×2304
Image Quality RAW
Flash Off
White Balance Mode Auto
AF Mode One-Shot AF
Parameters Settings Contrast  Mid. High
 Sharpness  Mid. High
 Color saturation  Mid. High
 Color tone    0
Color Space sRGB
Noise Reduction Off
File Size 6976 KB
Drive Mode Single-frame shooting
Sony –
Camera Model Name DSC-T100
Tv (Shutter Speed) 1/640
Av (Aperture Value) 4.5
Exposure Compensation 0
ISO Speed 125
Image Size 2592×1944
Flash On
Color Space sRGB
File Size 1295 KB

What sort of programmer are you?

I know another one of those personality tests but, hey it only take 1 min…
Programming Test result

Your programmer personality type is:

   DLTB

You’re a Doer.
You are very quick at getting tasks done. You believe the outcome is the most
important part of a task and the faster you can reach that outcome the better.
After all, time is money.

You like coding at a Low level.
You’re from the old school of programming and believe that you should have an
intimate relationship with the computer. You don’t mind juggling registers
around and spending hours getting a 5% performance increase in an algorithm.

You work best in a Team.
A good group is better than the sum of it’s parts. The only thing better than a
genius programmer is a cohesive group of genius programmers.

You are a liBeral programmer.
Programming is a complex task and you should use white space and comments as
freely as possible to help simplify the task. We’re not writing on paper anymore
so we can take up as much room as we need.

Pocket Loox n560 PDA

Finally got a modern PDA in the shape of a pocket loox. After a troublesome start, tip – don’t use their own wireless connection tool, I’ve; been on line via g wireless, grabbing mpg’s from my server, remote desktop accessed machines, went for a walk aided by 10 GPS satellites, played some dumb games(!) and…written this blog entry. It’s also so thin and light a huge change from my five year old HP. The wireless access is great, it makes the device independent. Having to use a host PC to get programs from the web was a real pain, the loox is refreshingly simple to use – providing you ignore the terrible 3rd party connection software

Technique vs. Technology

Technique vs. Technology

Over the past few years or so I’ve noticed a phenomenon that I’m calling Technique vs. Technology.When developing software solutions for computers there is always a number of ways of doing something but usually there is a much smaller set of recommended patterns that should be used. However, there are a large number of developers that don’t follow these patterns and produce solutions that have inherent problems. The reason for this is either ignorance or cost cutting, maybe both. Either way it is the end-user or customer that suffers and gives software development a bad name. So what’s the answer? The obvious reply to this is to invest in educating the developer community and to produce software tools to help developers avoid common pitfalls. Yes, to my mind this is the correct way and with the recent surge of concepts like Software Factories it would seem that many others share that opinion too. But the software/hardware industry have another angle, lets use technology to compensate for poor technique and for backwards compatibility. However, lazy (or ignorant – is there a difference?) developers can rely on these features and will never learn or comprehend why they should learn the proper technique. But then again, why should they? So I’ve waxed lyrical for long enough now, how about some examples?

Stored Procedures vs. embedded SQL

 Back in the day Microsoft provided stored procedures for SQL Server with one of the benefits being that the plans are cached and reused. The problem was that when Microsoft released ADO a huge number of developers, using SQL Server, ignored stored procedures and simply issued statements directly to the server. Although ADO should be praised for its easy of use and flexibility it allowed lazy developers to produce grossly inefficient code. Consequently Microsoft spent the next few years defending ADO and repeatedly telling developers to use stored procedures for performance code. Eventually, although I’m sure there’s and official reason for this, they caved and provided statement caching which, IMO, panders to the lazy developer…although I concede there are some advantages to this. This is my first example of technology compensating for the lazy developer but really does it matter?

CSS vs. Table slicing

 Web page design has gone through somewhat of a rocky few years, caused mainly by inconsistencies in browser implementation, producing two basic techniques for page layout; Cascading Style Sheets (CSS) and Table (image) slicing. CSS is the recommended pattern with lots of good points ranging from structure/layout separation, accessibility (see PDA later), downloads efficiencies, etc, etc. However, early browsers (and indeed inconsistencies with modern browsers) prevented the use of CSS. To get around this the table tag set was used to create layouts by slicing images into small chunks that could be placed within equally sliced up tables. However, there are a number of problems with this approach, basically the opposite of what’s good about CSS but for me the important problem is the accessibility. The most obvious of these problems is scaling the text within a table. In the majority of case this simply breaks the page, with text disappearing or the image slicing going horribly wrong and the original dimensions change. But wait, the browsers technology has a trick up its sleeve, zooming. The browser simply zooms the whole page rather than altering any specific Html element/attribute. So I can use tables safe in knowledge that it works on almost every browser and the user will be able to zoom the page…providing they download a nice new browser. Ok it still doesn’t solve all the problems of table slicing but it certainly becomes a strong argument especially when CSS can be troublesome to get right on all the browsers.

CSS vs. PDAs

 Viewing Html on a standard 15″ screen has long since been superseded with all sorts of odd shaped viewing devices. Monitors now come in all sorts of sizes and resolutions, but the really odd sizes are reserved for the smaller screens of handheld devices such as mobile phones or Personal Digital Assistants (PDA). These screens cannot, sensibly, view a screen designed for 800×600+. Step in CSS, with device specific stylesheets you can create a nice layout for the smaller screen whereas those nasty-old table sliced sites look terrible. Well back to the real world. PDA browsers have long since given up waiting for CSS and have taken it upon themselves to use their technology to break up the tables and provide a decent view of the table sliced page. Whereas, many of the browsers don’t understand a hand-held media type and the CSS site looks terrible. So again, it’s all too easy to say, why bother?

Code Optimisations

One of the great aims for software development is that the developers should focus on the logical problem rather than spending their time solving issues with their chosen implementation language. One such area is optimisations. True they can make a big difference but if the developer types if MyString == “” or if MyString.length==0 then this sort of optimisation should really be caught by the underlying compiler. Another classic in the world of .net is the StringBuilder. If I use FxCop it will tell me that I should be using a StringBuilder for string concatentation within a loop. So rather than tell me that, why doesn’t the string concat’ do that behind the scenes? If I really don’t want to use a StringBuilder class I should be able to create a SimpleString type or something! In theory I shouldn’t have to concern myself with such optimisations.

Summary

So here is the real question, why bother spending the time using the “correct” techniques when the the majority of people don’t and therefore the technology ends up compensating for them? Granted they don’t compensate for everything, but will it just be a matter of time before they do?

DVD Piracy warnings, where can I get a copy?

Ok now I loath the idea of people copying films/music/software and therefore discouraging the authors from creating more. However, what I really hate is being forced to watch a (seemingly) 20 min advert telling me that the DVD I’ve rented/bought shouldn’t be copied. So basically I get penalised for buying the DVD whilst the people who buy the pirate DVDs go straight to the film. It almost makes me want the throw my ideals out the window for the sake of saving 20 mins per DVD I watch. So if any of you Blu-ray/HD-DVD executives are reading this, please, please don’t force us to watch mind numbingly dumb anti-piracy trailers or any other sort of advert. Sure keep them on there but don’t hijack the control of the film, let us skip them, otherwise I’ll be tempted to join the back of the queue for those dodgy HD-CAM films!

Trouble with Dell 2007FP

My trusty Diamondtron 17" CRT finally started to give up the ghost. So armed with a great review (for it’s larger brother) I (brashly) purchased a new Dell 2007FP 20.1" LCD.
It arrived the following day (good start) and I unpacked it. Spent the usual 10 min unplugged loads of cables and contorting myself into knots feeding the new cables around the back of my desk. Then it started, my bad luck with the monitor…
1. No power cord
Oh great no power cord, so the last 5 mins of unthreading the CRTs power cord is now a total waste of time since I’m going to be forced to re-use it. Not a big problem but just one of the annoying things
[Edit 4-Sept] Overclockers emailed me apologising for the problem and have promised to ship me a replacement cord.
2. Clear Type halo
Installing it was pretty easy, XP took to it well. The text wasn’t so great, something I’d worried about since at 1600×1200 the text was always going to be small. But I’ve not engaged Clear Type…eeew, a horrible redish halo around the text. Now my 17" Dell LCD at work has exactly the same problem, something I’d put down to as the rubbish bottom of the range ATI card + rubbish Win 2003 ATI drivers. But alas not, my top of the range (well about 3 years ago) 9800XT plus decent XP drivers can’t be at fault here. Surely the various glowing reviews for the monitor would have seen this…
3. Samsung vs Philips
Apparently the guts of 2007FP is manufactured by two companies, Samsung and Philips. However, the real crunch is they use two very different technologies, sure they meet the same spec’s but their implementation is totally different. The Dell forums are saying that its basically a lottery, the Philips is the better image quality with the Samsung probably being faster for the gamer. Although I do play far too many games I really wanted the image quality…guess which version I’ve ended up with? Yep the Samsung. Could this be the reason for the dodgy Clear Type? The forums also went on to say that the rumour was that the press were only ever given the Philips variant, hence the good quality reviews. I feel a tad bit conned.
4. Stuck Pixel
Ah the final straw (I so hope it’s the last problem), a stuck pixel. Even on the huge real-estate of 1600×1200 that ***** pixel screams at me. Hopefully Dell will take it back, lets hope so…maybe I’ll even get a nice Philips IPS version in return too…’cause I’m just that lucky 😉
[Edit 4-Sept]Oh no they won’t. Unless you screen looks like it’s been in a shotgun hunting accident they won’t take it back. Still I have some better news…
[Edit]
Clear Type – Attached a Dell laptop (NVidia chipset) to the screen today to see what the Clear Type looked like. I have to say I think it does a better job. Still no-where near my (now elevated to lovely) Sony 17" SDM-X Black but better than the ATI source. However…the laptop is using the VGA vs my desktop’s DVI source. In theory the DVI should be better but I’ve seen plenty of reports with monitors (esp. Dell) having problems with DVI. Next steps will be to rig up an NVidia DVI source and switch the ATI to VGA.
Stuck Pixel – used some "flashing colour" techniques to wake the pixel up. No joy, I quite like the theory behind the fix, apparently PSP owners have had some joy so I’ll try it out for a bit longer. Strangely the tiny 5×5 flashing square is less distracting than the stuck pixel, I guess at least it looks like it’s doing something!?
[Edit 4-Sept]
Well I swapped the screens over and and it seems to make a huge difference. The trusty Sony SDM-HS75P works a treat using the ATI DVI source, so that takes the pressure off ATI a bit and back onto the Dell. Meanwhile I plug the Dell into the NVidia 6800GT DVI source…well not too bad. A quick application of Microsoft’s Tweak Clear Type and it looks usable. In fact it looked better before I’d even realised I was still running at a lower resolution…that’s the sort of difference the NVidia card makes.
So my conclusions are quite surprising, it seems that the worst thing you can do is pair up a Dell monitor with an ATI card, at least a fairly old ATI card, since I have a similar set-up at work and that’s terrible too then I think it is more than just a coincidence. However, the NVidia card seems unfased by the monitor as does the Sony. So my advice is, if you must use Dell then look at NVidia, if you don’t want to take chances go with Sony. NB. I bought the Sony because it was one of the few I could try before I bought, and the Sony below the HS75P wasn’t great either so my best advice is try it first!