Using Microsoft AntiXSS 1.5
This has been out for a while, however I just tried to reference it and forgot where it was located. Microsoft should really make accessing this a lot easier - would have been nice for it to appear in the Add Reference dialog. Anyway, its located at:
C:\Program Files\Microsoft Corporation\Anti-Cross Site Scripting Library V1.5\Library\.Net 2.0\AntiXssLibrary.dll
Then its
using Microsoft.Security.Application;
string pageTitle = AntiXss.HtmlEncode(Request.QueryString["Page"]);
Remember: Always HtmlEncode untrusted text.
Download it from
LINQ to SQL Cheat Sheet
While playing around with LINQ to SQL I decided it could be useful to have a cheat sheet for some common operations. I think I might have to reorder/redesign for the next version to allow more, this will come as I learn more about Linq. I hope you find it useful. Let me know what you think.
Download
PDF : LINQ To SQL Cheat Sheet Version 1.pdf
XPS : LINQ To SQL Cheat Sheet Version 1.xps
DDD5 Agenda
The agenda for DDD5 has been released. http://www.developerday.co.uk/ddd/agendaddd5lineup.asp
Some very interesting sessions, the ones I think I will be attending are:
An introduction to Unit Testing with Mock Objects or Evolutionary Algorithms and the Traveling Salesman
Being lazy is an art form (or: Making your computer work for you) or Team Foundation Server - the answer to all project management problems?
Making Phones Ring in One Line Of Code or An Appraisal of "Object Thinking"
An Introduction to Card Space or Do Design Patterns Make Sense in ASP.NET?
Next Generation Data Access with LINQ or Multithreading patterns or CSS 101 – Moving away from table based layout
Should be a good day.
LINQ Error 'Can't perform Create, Update or Delete operations'
I have been playing around with LINQ to SQL and I was receiving an odd error message when inserting a entity into a table. The error was:
Message: Can't perform Create, Update or Delete operations on 'Table(dbo.DocumentRevisions)' because it is read-only.
Type: System.InvalidOperationException
Source: System.Data.Linq
TargetSite: Void Attach(T)
HelpLink: null
Stack: at System.Data.Linq.Table`1.Attach(T item)
at SqlServer.SqlContentProvider.SaveDocument(Document document) in E:\My Documents\Visual Studio Codename Orcas\Projects\SqlServer\SqlContentProvider.cs:line 53
at SimpleWiki.DAL.Tests.DocumentTests.TestInsertingDocument() in E:\My Documents\Visual Studio Codename Orcas\Projects\Tests\DocumentTests.cs:line 28
I thought I had everything correctly, however I forgot to set a primary key in the table, hence Linq was unable to do anything with the object. So, lesson for the day Linq must have a Primary key for the table :).
DDD5 Registration Open
DDD5 registration is now open for the event on Saturday 30 June 2007.
https://msevents.microsoft.com/cui/EventDetail.aspx?culture=en-GB&eventid=1032342589
One thing I find interesting is that it lists the rooms as "Chicago 1&2/Memphis/Everest 1&2" Five tracks this year?? Would be cool. (NOTE: THIS MIGHT BE A MISTAKE, I DON'T KNOW FOR SURE). The agenda is due soon.
Hope every knows what DDD is by now, if you are unsure visit http://www.developerday.co.uk/ddd/default.asp
What is JavaFX?
In case you haven't heard, on May 8th (2007) Sun announced a new framework called JavaFX Script and also JavaFX Mobile. This is sun's answer to Flex/Flash and Silverlight so I thought I would have a look around and see what it is actually about. On the site, they say "a highly productive scripting language that enables content developers to leverage the enormous popularity of Java to create rich applications and services for deployment on the widest range of platforms". While only Script and Mobile have been announced at the moment, other products are in the pipeline including maybe JavaFX Designer. The timescale for this are planned for a release end of 2007/early 2008, it is currently in preview status.
So what is JavaFX? Well, it has been split into two at the moment - Script and Mobile. Script is built ontop of JRE (Java Runtime) and Swing, which allows it to be cross platform straight out of the box. The code itself is not java, instead it is a declarative syntax allowing for more dynamic features and Sun have clearly stated it is mainly intended for UI development and not business workflow. It can call/be called from Java classes.
JavaFX Mobile is "package aimed at mobile-handset markers designed to make java applications more portable across mobile phones" which was purchased from a 3rd party last year. On the mobile, JavaFX Script applications run ontop of this. This provides a level of abstraction to allow a developer for more cross platform support when developing mobile applications, confuses me a little as I thought the point of Java was to be cross platform so why is another layer required on a mobile?
With this style of run anywhere, when you visit a JavaFX application, the most noticeable thing is that it doesn't run in the browser, infact JavaFX applications are not supported for running in the browser, so no playing video's inline with a website. Instead, they are executed as a separate application which makes them feel more like desktop applications than RIAs which is interesting. Sun are claiming the applications will work in an offline mode which Microsoft have stated isn't in their plans for Silverlight. On my mac, they where downloaded as separate files and saved on my harddrive and I could download them with my wifi disabled.
Once loaded, the applications have the same look and feel as the host OS by default which is really nice and much better than Swing used to be. Now when an application has defined a menu bar (file, edit, help etc) on a Mac it will be in the correct place at the top of the screen by default, while on a Windows machine it will be within the application's window. However, I did notice that everytime I load an application (which has to be signed) I get a Don't Trust / Trust dialog box. Even if I have told it to be trusted, it still asks me next time I load the application. Very annoying, it's like UAC for every application, but this might be just the applications I am running, as they all seem to have a error regarding their certificate, so this might not be the case for all applications in the future.
When creating an application, there is currently no official designer tool which makes it difficult to produce anything advanced. Sun have ported a few applications from Flash to JavaFX for demoing purposes so it can be done. JFX Builder has been released by a 3rd party so tools are on the way. Eclipse and Netbeans (5.5 + 6.0) have downloads available for running the applications, I have used NetBeans 5.5. So lets have a look at some code.
This is the classic Hello World sample. Firstly, it creates a class which we use as our model. We create an instance of that class. We then create a new Frame setting various properties, creating a label and binding it to our instance of the model to return the string. This code displays a Window with the text Hello World and a title Hello World JavaFX (from tutorial on their site).
class HelloWorldModel {
attribute saying: String;
}
var model = HelloWorldModel {
saying: "Hello World"
};
var win = Frame {
title: "Hello World JavaFX"
width: 200
content: Label {
text: bind model.saying
}
visible: true
};
As you can see from this example, JavaFX are pushing the Model-View architecture, allowing the developer to create a model and then binding properties to the models implementation. But the code is simple, short and kind of clean. Moving to a more advanced example
import java.lang.System;
class ButtonClickModel {
attribute numClicks: Number;
}
var model = new ButtonClickModel();
Frame {
width: 200
menubar: MenuBar {
menus: Menu {
text: "File"
mnemonic: F
items: MenuItem {
text: "Exit"
mnemonic: X
accelerator: {
modifier: ALT
keyStroke: F4
}
action: operation() {
System.exit(0);
}
}
}
}
content: GridPanel {
border: EmptyBorder {
top: 30
left: 30
bottom: 30
right: 30
}
rows: 2
columns: 1
vgap: 10
cells:
[Button {
text: "I'm a button!"
mnemonic: I
action: operation() {
model.numClicks++;
}
},
Label {
text: bind "Number of button clicks: {model.numClicks}"
}]
}
visible: true
}
This example is starting to get a little bit more advanced. Firstly, it defines a menu bar - which fits in with the style of the host OS - very nice. Code such as action: operation() {} defines what happens on by default. Not sure how this works when two events? But then I never got that with java buttons. The GridPanel contains all the information, with a button and a label. The mnemonic is the keyboard shortcut for the button. I'm sure you will agree, this code is much better than the traditional Swing code, this provides a much simpler way to create GUIs. It would be interesting to see how the code looks for a large application.
After looking at the Programming Language reference guide. It does have a very dynamic feel as you would expect. Here are a few items which caught my eye
Modifying Arrays
var x = [1, 2, 3]
insert 12 into x; //[1, 2, 3,12]
insert 10 as first into x; //[10, 1, 2, 3,12]
insert [99,100] as last into x; //[10, 1, 2, 3,12,99,100]
There is then code to insert it on a specific element in the array
insert 11 after x[10];
Querying Arrays
var nums = select y
from y in x
where y <> 1; //returns all the numbers which do not equal 1
Java introducing in memory querying of objects. Interesting how they have the select first...
Do Statement
The do statement allows you to execute a block of code in a background thread. Only code within a do block is allowed to execute in another thread.
do { //read IO }
Thats it, very simple threading. There is also do later {} which is asynchronous execution. That is a cool way of handling threads.
Triggers
This allows code to be executed based on some event, such as creation, insert and delete. In the case of it picking up an event, is calls the defined method.
One thing which caught my eye is, "it is illegal to do anything with JavaFX at the moment" as Sun are still discussing licensing terms so at the moment it is only for preview. But thats only like LINQ and Silverlight 1.1 as its not for commercial use.
In summary, It is still a very early preview. I'm sure Java people will be over the moon at this announcement, but for me it's nothing special. The Mobile aspect sounds interesting, as it would be a fix for Java's core problems on mobile devices in the fact that they are not portable. Time will tell, and I will keep an eye on whats going on in the Java world like I do with everything but I'm not about to jump ships. This is a much needed improvement for developing Java GUIs (something which I hate doing) but this just seems like a dynamic wrapper around the core JRE and Swing with a few additional language features. Time will tell...
JavaFX Site: https://openjfx.dev.java.net/
Any posts which I find interesting are being tagged on del.icio.us - http://del.icio.us/ben2004uk/javaFX - this is one of the reason why I really like del.icio.us.
PS: I've noticed that my blog is becoming a bit messy since using the new code formatter. I will try to make sure it looks OK before publishing and stop using line numbers. It just decided to die on me, which is why this post does not contain it. Sorry about this.
Vista Sidebar Gadget using Silverlight
I've wanted to see if this works for a while but really haven't had chance until this weekend. The short answer is Yes it works without a problem, longer answer is Yes but there are some problems (with solutions). The main problem I had was with regard to debugging the Silverlight project, which I will discuss later in the post.
As I'm sure you are aware, a Sidebar gadget sits in the Vista Sidebar application docked at the side of your screen. These are created using HTML, CSS and JavaScript, however I have included Silverlight into that combination. The gadget I created is a Silverlight Video Player Gadget which displays thumbnails of all the videos in a selected folder, and allows you to play them in the sidebar and display them full screen. Not anything overall interesting, but it did bring up a few interesting facts about Silverlight and Gadget development.
The project itself is just the standard template which is part of the SDK and what I discussed in my previous post. If you want to know more about Silverlight, I suggest you give it a read. The only additional item I had to included was the standard gadget.XML which is the manifest file for the gadgets, and must be included.
Silverlight itself works out of the box within the sidebar however there is a problem. By using the default Silverlight host in the sidebar, it will cause it not to be able to be removed from the sidebar, apart from uninstalling the gadget which forces the removal, and not being able to move the gadget around. The fix is to tell the control to be windowLess when creating the host.
1 Sys.Silverlight.createObjectEx({ 2 source: "Scene.xaml", 3 parentElement: document.getElementById("SilverlightControlHost"), 4 id: "SilverlightControl", 5 properties: { 6 width: "130", 7 height: "100", 8 version: "0.9", 9 isWindowless: 'true' 10 } 11 })
The isWindowless property just says if the control should be contained within a window or not, if the control is in a window then it is self contained and the webpage's style/look doesn't affect it. However within it being windowless it is part of the webpage and allows it to be more part of the webpage. Hard to explain (reason why I linked to MSDN). In the case of Silverlight and sidebar, it means that the gadget can be removed and moved while still hosting the Silverlight gadget.
To make sure my control lined up correctly, I set the margins to 0px. I also set the height and width of the gadget itself. This just makes sure you have no white space around the edges and it looks like a normal gadget.
body { margin: 0px; width: 130px; height: 95px; background: Black; }
The XAML for the control is just the standard Silverlight, nothing had to be changed or modified for this to work. The XAML had a MediaElement which is used to display and play the video.
1 <MediaElement x:Name="mediaPlayerControl" Width="130" Height="95" Stretch="Uniform" AutoPlay="False" />
I set this to AutoPlay="False", so when the Source property is set within the JavaScript, it doesn't automatically start playing the video. I had a internal canvas when held the controls for the video, play, stop, previous, next and full screen. I used a storyboard animation to show/hide the canvas, by changing the opacity, which was started from the JavaScript. To hook up the events of when I wanted the controls to appear and disappear, I handled the canvas events for MouseEnter and MouseLeave. The rootElement is the root canvas so this worked well as it always captured the event.
1 this.rootElement.addEventListener("MouseLeave", Sys.Silverlight.createDelegate(this, this.hideControls)); 2 this.rootElement.addEventListener("MouseEnter", Sys.Silverlight.createDelegate(this, this.showControls));
1 showControls: function(sender, eventArgs) 2 { 3 alert("Show Controls"); 4 if(sender.getHost().content.fullScreen != true) 5 { 6 this.control.content.findName("showControls").Begin(); 7 } 8 else 9 { 10 } 11 },
When the full screen button is pressed, it simply calls a function which sets fullScreen = 'true' on the control.
1 mediaFullScreen: function(sender, eventArgs) 2 { 3 alert("Media Full Screen"); 4 this.control.content.fullScreen = 'true'; 5 },
However, to have some more control over this, I hooked up to the onfullScreenChange event which is fired when entering and leaving full screen.
1 this.control.content.onfullScreenChange = "onFullScreenChanged";
This code changes the opacity of items which I do not want to be displayed when in full screen mode, and sets the width and height of the mediaPlayer to the full Screen size then starts playing the video.
1 function onFullScreenChanged(sender, args) 2 { 3 var silverlightControl = sender.getHost(); 4 var controlsPanel = sender.findName("controls"); 5 var border = sender.findName("mainBorder"); 6 7 if (silverlightControl.content.fullScreen == true) 8 { 9 controlsPanel.opacity = 0; 10 border.opacity = 0; 11 } 12 else 13 { 14 controlsPanel.opacity = 1; 15 border.opacity = 1; 16 } 17 18 var mediaPlayer = sender.findName("mediaPlayerControl"); 19 mediaPlayer.width = silverlightControl.content.actualWidth; 20 mediaPlayer.height = silverlightControl.content.actualHeight; 21 mediaPlayer.play(); 22 }
As you can see, this is all standard Silverlight control, nothing special about it being hosted within the sidebar.
Now lets move onto the code to which gets the videos and sets the source for the mediaPlayer.
1 function LoadFiles(dir) 2 { 3 alert("LoadFiles Start: " + dir); 4 5 var oShellItem = System.Shell.itemFromPath(dir).SHFolder.Items; 6 for (var i = 0; i < oShellItem.count; i++) 7 { 8 //Check to see if it is a video file 9 if(!oShellItem.item(i).isFolder) 10 { 11 files.push(oShellItem.item(i).path); 12 } 13 else 14 { 15 LoadFiles(oShellItem.item(i).path); 16 } 17 } 18 alert("LoadFiles End with: " + oShellItem.count); 19 } 20
This function takes in a directory path, and stores a list of the items (files and folders) in oShellItem. It then goes over each item, checks that it is not a folder, if it is is uses recursion to search that directory, and add it to an array Files. I should really have included a check to make sure that they where videos - nevermind.
1 function StartRotator() 2 { 3 alert("StartRotator Start"); 4 var silverlight = document.getElementById("SilverlightControl"); 5 var media = silverlight.content.findName("mediaPlayerControl"); 6 alert(media.CurrentState); 7 8 if(media.CurrentState != 'Playing') 9 { 10 if(increment < files.length) 11 { 12 var item = files[increment]; 13 media.Source = item 14 increment++; 15 } 16 else 17 { 18 increment = 0; 19 var item = files[increment]; 20 media.Source = item 21 } 22 } 23 24 waitTimer(); 25 } 26 27 function waitTimer() 28 { 29 alert("Waiting"); 30 cancelID = setTimeout("StartRotator();", 15000); 31 }
With this code, if the media is not currently playing, it gets an item from the array and sets it as the Source for the control. It then sets a timeout for 15 seconds, once elapsed it will called the function again and display the next video in the array. I save the cancelID for the timeout as when I select the next or previous video, I cancel the timeout before setting the source as otherwise it would call the method unexpectedly again.
1 function Next() 2 { 3 clearTimeout(cancelID); 4 5 if(increment == (files.length - 1)) 6 { 7 increment = 0; 8 } 9 else 10 { 11 increment++; 12 } 13 var item = files[increment]; 14 var media = document.getElementById("SilverlightControl").content.findName("mediaPlayerControl"); 15 media.Source = item; 16 waitTimer(); 17 }
As you can see, the code isn't very complex and is nothing special, however the concepts are important. The code simply uses parts from the Sidebar framework and interacts using JavaScript with the Silverlight control. However, if there is a problem - debugging is a nightmare.
Silverlight hides all Javascript errors, so if there was a problem, the only way of knowing was nothing would display when loading the sidebar. This is why I have alert statements everywhere. However, Sidebar hides all alert dialogs so this doesn't display the problem/state either. What sidebar does offer however, is allow you to write to the debug pipeline.
function alert(msg) { System.Debug.outputString(msg); }
By overriding the alert statement in javascript, I could redirect all messages to System.Debug.outputString. I then used DebugView (SysInternals/Microsoft) to read all the activity from here to find out what the gadget was actually doing - made it easy to debug. Note, DebugView needs to be run as Administrator under Vista.
One other note. As the gadget always needed to be reloaded within the Sidebar to get the latest changes, but sometimes I had to uninstall it (like with windowLess problem) which would delete the files. I developed under my normal directory and used the publish feature of VS to save the files into the correct directory. In my case
C:\Users\Ben Hall\AppData\Local\Microsoft\Windows Sidebar\Gadgets\SilverLightVideoPlayer.gadget\. I could then just drag on the gadget.
In summary, I hope this post helps, it is easy to build Vista Gadgets using Silverlight, just need to be careful about debugging and use DebugView.
Download:
Code @ http://blog.benhall.me.uk/Code/Silverlight/VideoPlayerGadget/SilverlightVideoPlayerGadget.zip
Gadget @ http://blog.benhall.me.uk/Code/Silverlight/VideoPlayerGadget/SilverlightVideoPlayer.gadget
Uploaded onto Popfly @ http://popfly.ms/users/Ben2004uk
DebugView @ www.microsoft.com/technet/sysinternals/utilities/debugview.mspx
NxtGenUG Fest07 Post Event
On Wednesday, I attended NxtGenUG's Fest07 event at TVP. In summary, It was a great event.
Rafal Lukawiecki was one of the main presenters, talking about Vista Security and Software Development Paradigms, which where some of the best talks I have saw before. He has such passion, and is a great presenter. He makes listening to him really interesting and allows you to take everything in yet moves at a fast pace so its full of interesting content. Even his laptop running out of battery didn't put him off. Great speaker, was cool that NxtGen managed to get him.
Daniel Moth and Mike Taulty's talk was also very enlightening and assuming. They split the roles of the presentation, Daniel did the slides while Mike did the demos - worked well. I thought this talk pretty much summed up the whole day, laid back, funny, but also full of content with interesting discussions about various points.
As you would expect from NxtGen, the day ended with a game show - Swaggily Fortunes - the Microsoft Family vs the NxtGenUG Members Family. Nice concept, but more of a reason to though swag at us, it was a good way to end the day on a lighthearted note. Everyone got to leave with a piece of swag, mainly either a book, VS2005 or Vista Home Premium I think - looked to be a lot there, plus a T-shirt or two.
Bad point, could have done with some drinks apart from Coke, tea and coffee. There is only so much you can drink... :)
Silverlight 1.0 Intellisense in Visual Studio 2005
Intellisense is not installed by default in Visual Studio 2005, however can be easily installed. The SDK contains a schema (silverlight.xsd) which defines how Silverlight XAML files should be defined and what is valid, as remember XAML is just XML. All you have to do is simply place a copy of the xsd into your Schema folder, which by default is:
C:\Program Files\Microsoft Visual Studio 8\Xml\SchemasNext time you open Visual Studio, you will have intellisense for your Silverlight XAML. Apart from x:Name which doesn't appear to be liked...but that's only a small point.
First time with Silverlight 1.0
This post is a starting demonstration of how to get started with Silverlight 1.0 for the first time, mainly what all the files are within the default template. Once you have an idea of this, you should be in a position to write your own RIA (Rich Internet Application). I've already discussed What do you need to get started, so I won't go into that again.
I will be using Visual Studio 2005 and Silverlight 1.0, this is because 1.0 has a Go Live license plus I'll cover 1.1 in later posts. After you have installed the bits, you will have a new Silverlight Project Template in VS2005. If it doesn't appear, you need to drop the template in the SDK into your templates folder in My Documents\Visual Studio 2005\. Remember, Silverlight 1.0 only supports JavaScript programming model.
Within the default project, you have all the code for a simple button which when clicked displays a JavaScript alert dialog box, but this includes the core sections of code to solve core tasks. The files are as follows:
Default.html: Page contents, contains the DIV which contains the Silverlight control
Default.html.js: Javascript code to create Silverlight host
Scene.xaml: XAML for the button, includes storyboards as a resource.
Scene.xaml.js: Javascript code for the XAML. Contains code to setup event handlers, and the code for the actual handler itself.
Silverlight.js: Code from Microsoft which detects if Silverlight is installed. This is best just left along.
That's an overview of which files are actually included/required. Let's have a dive into what they actually have inside them and which bits are important.
Default.html
This is the first page which a user sees, by default, and there is two main sections inside this file.
First main section is the references to the various JavaScript files within the files within the solution. By default the following are included:
1 <script type="text/javascript" src="Silverlight.js"></script> 2 <script type="text/javascript" src="Default.html.js"></script> 3 <script type="text/javascript" src="Scene.xaml.js"></script>
The order in which these appear is very important, the reference to Silverlight.js must be first so it can do the detecting of if it is installed or not. When referenced, variables/functions within one javascript file can reference items in the other file, however this does make them tightly coupled and could lean to problems on large applications.
The next section is the DIV and code to create the Silverlight object
1 <div id="SilverlightControlHost"> 2 <script type="text/javascript"> 3 createSilverlight(); 4 </script> 5 </div>
The DIV id is used to locate where to place the control so name this carefully. The createSilverlight() function is within Default.html.js and has the code to create the host and link it to the XAML. This DIV can be anywhere on the page and named anything, however the javascript code will have to change to relate to this name change. If you have two controls, you will need two creation scripts.
Default.html.js
The main function within this file is the createSilverlight() which creates the Silverlight host. Firstly, it creates an object which links to the XAML file, this needs to relate to your own object. The source property relates to the xaml, parentElement relates to the DIV where you want the Silverlight control to be hosted in your HTML. The id will be for the actual ID of the Silverlight control itself, this will be used for referencing in your javascript as you will see later down. Properties then relate to the size and various other properties which you might require. Version 0.9 is currently Beta 1.
1 function createSilverlight() 2 { 3 var scene = new SilverlightJSApplication2.Scene(); 4 Sys.Silverlight.createObjectEx({ 5 source: "Scene.xaml", 6 parentElement: document.getElementById("SilverlightControlHost"), 7 id: "SilverlightControl", 8 properties: { 9 width: "130", 10 height: "100", 11 version: "0.9" 12 }, 13 events: { 14 onLoad: Sys.Silverlight.createDelegate(scene, scene.handleLoad) 15 } 16 }); 17 }
This javascript could do anything you like, for example calling web services or starting an animation in the xaml, with3rd party frameworks such as Altas/ASP.net Ajax client side files supported. Scene.xaml
This file contains your XAML code. This can be development using either Visual Studio 2005/Orcas or Blend 2. Using Blend 1, you have to do a few work arounds for it to work whereas Blend 2 fully supports Silverlight. This also includes the storyboards/animations, when creating a storyboard using Blend 2, there is a tick box which is can be ticked to make the storyboard a resource, I prefer this as its is less code and easier to program against using code-behind.
1 <Canvas.Resources> 2 <Storyboard x:Name="mouseEnter"> 3 <ColorAnimation Duration="00:00:00.25" To="#3DFFFFFF" Storyboard.TargetName="highlightEllipse" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" /> 4 </Storyboard> 5 </Canvas.Resources>
Above is how it looks as a resource, where as below is how it looks without being a resource.
1 <Canvas.Triggers> 2 <EventTrigger RoutedEvent="Canvas.Loaded"> 3 <BeginStoryboard> 4 <Storyboard x:Name="Timeline1"> 5 <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)"> 6 <SplineColorKeyFrame KeyTime="00:00:01.6000000" Value="#66D79B03"/> 7 </ColorAnimationUsingKeyFrames> 8 </Storyboard> 9 </BeginStoryboard> 10 </EventTrigger> 11 </Canvas.Triggers>
If you know XAML, then you shouldn't have a problem understanding this and the contents of the file.
Scene.xaml.js
This file contains some interesting code. As mentioned, this contains the event handlers for the xaml, with the first function being called is handleLoad: function(control, userContext, rootElement).
Control is the Silverlight control itself and you can do things like this.control.content.findName("myControl") to gain access to a controls reference in the XAML file. The rootElement is the root canvas for the control.
For example, to add an event handler to the canvas, you would do:
1 this.rootElement.addEventListener("MouseLeftButtonDown", Sys.Silverlight.createDelegate(this, this.handleMouseDown));
When the MouseLeftButtonDown (onClick) event occurs on the rootElement (canvas), the handleMouseDown function is executed.
1 handleMouseDown: function(sender, eventArgs) 2 { 3 var mouseDownAnimation = sender.findName("mouseDown"); 4 mouseDownAnimation.begin(); 5 },
This asks the sender, the canvas, for the resource mouseDown, in this case a storyboard, and then calls the begin() function on that item which starts the animation. Remember, this is a prototype and so is coded differently than normal javascript, main thing is to be careful with your comers, this follow all the end functions apart from the last.
Silverlight.js
This is provided by Microsoft, and is included in the SDK. There is a lot of code, shouldn't really need to modify it. Just remember to included it in all of your projects and reference it in your HTML. This way you will get a nice image if the user does not have Silverlight installed.
Summary
I hope I have provided you with a good understanding of what everything is within Silverlight. If you have any problems, the best way I found is to look at the default and follow that. Hope this has been of some help for you. Any questions, give me a shout.
Processing Technorati using C# 3.0 and Linq
Following on from my previous post, I wondered how more effective and easily the processing could be done using the new features of C# 3.0 and Linq to XML. And it was...
When creating the code, the first thing to do is bring in the System.Xml.Linq assembly which can be found in C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\ - or at least this is the case with Orcas Beta 1.
We then create a XElement, and pass the URL for Technorati via the static method Load to allow it to download the query response.
1 string url = string.Format("http://api.technorati.com/tag?key={0}&tag={1}&limit={2}excerptsize={3}", technoratiAPI, technoratiTerm, limit, excerptsize); 2 XElement response = XElement.Load(url);
Below is the LINQ to Xml query to process each of the items returned, sorry about the wrapping - code link at the end of the post. The first thing which is required is to state which Descendants are being queried, which in this case is all of the item elements. We then create objects of type Blog like before, however this time we can use the new feature of C# 3.0 called Object Initializers. We then create a sub object of type Weblog for the details of who made the post. This is then stored in the query variable. One point is that you need to include .Value on the Element() as we are using a known object type instead of letting the compiler work it out.
1 var query = from post in response.Descendants("item") 2 select new Blog { Title = post.Element("title").Value, 3 Description = post.Element("excerpt").Value, 4 Created = Convert.ToDateTime(post.Element("created").Value), 5 Url = post.Element("permalink").Value, 6 Weblog = new Weblog { 7 Name = post.Element("weblog").Element("name").Value, 8 LastUpdated = Convert.ToDateTime(post.Element("weblog").Element("lastupdate").Value), 9 Rss = post.Element("weblog").Element("rssurl").Value, 10 Url = post.Element("weblog").Element("url").Value 11 } 12 };
As our method is returning a generic list of Blog objects, we need to export the query to do this. This is done very simply, by query.ToList<Blog>() which causes it to execute the query, and convert the result to a generic collection of type <Blog>.
1 List<Blog> GetTechnoratiPosts() 2 return query.ToList<Blog>();
Once we have it in this format, we can use it the same as we did before, using extractly the same ASP.net code to display the query on the screen.
One more point, as we are using C# 3.0, we can also use the new Automatic Properties feature to cut down the amount of code required to create the simply blog and weblog objects. The code for the blog class is now:
1 public class Blog 2 { 3 public Weblog Weblog { get; set; } 4 public string Title { get; set; } 5 public string Description { get; set; } 6 public DateTime Created { get; set; } 7 public string Url { get; set; } 8 }
Very nice, saves a lot of unnecessary typing.
Hope you find this useful, I think its cool.
Code can be downloaded:
http://blog.benhall.me.uk/code/CSharp/Technorati/TechnoratiLinqToXml.txt
Processing Technorati using C# 2.0
I am currently redeveloping a website and a new feature is being able to connects to Technorati to return a list of all the blog posts tagged with a particular term and display them on the site.
Technorati is a very simple API to connect to using a REST-ful interface. It returns an XML response containing information about the result set and then a collection of items which correspond to the tagged blog posts.
The response looks like this:
<?xml version="1.0" encoding="utf-8"?> <!-- generator="Technorati API version 1.0 /tag" --> <!DOCTYPE tapi PUBLIC "-//Technorati, Inc.//DTD TAPI 0.02//EN" "http://api.technorati.com/dtd/tapi-002.xml"> <tapi version="1.0"> <document> <result> <query>[tag]</query> <postsmatched>[number of posts that match the tag]</postsmatched> <blogsmatched>[number of blogs that match the tag]</blogsmatched> <start>[value of the start parameter]</start> <limit>[value of limit parameter]</limit> <querytime>[duration of query]</querytime> </result> <item> <weblog> <name>[name of blog containing match]</name> <url>[blog URL]</url> <rssurl>[blog RSS URL]</rssurl> <atomurl>[blog Atom URL]</atomurl> <inboundblogs>[inbound blogs]</inboundblogs> <inboundlinks>[inbound links]</inboundlinks> <lastupdate>[date blog last updated]</lastupdate> </weblog> <title>[entry title]</title> <excerpt>[entry blurb with term highlighting]</excerpt> <created>[date entry created]</created> <postupdate>[date post last updated]</postupdate> <permalink>[blog entry URL]</permalink> </item> </document> </tapi>
You make a request to the API using either HTTP GET or HTTP POST requests, this makes it really easy to use within C#, as discussed in a moment. To make a request, you hit the URL http://api.technorati.com/tag?key=[apikey]&tag=[tag] replacing the [apikey] for the API which Technorati provides you, and replace [tag] with the term you want for all the posts to return. There is also some optional fields which can be included to allow you to customize the response, for example limiting how many responses are actually returned (default is 20).
Onto the code, the first task is to construct a string for the URL setting any parameters which you wish to use as the request.
string url = string.Format("http://api.technorati.com/tag?key={0}&tag={1}&limit={2}excerptsize={3}", technoratiAPI, technoratiTerm, limit, excerptsize);
I then use the URL together with the XmlDocument and XmlTextReader to make the request and load the document into memory for processing. The XmlTextReader will deal with making the request to the URL and processing the response, we just need to provide it with the correct URL. I then use a XPath query to select all of the items/blogs returned from the http request and store them in a collection.
1 XmlDocument xmlResultsSet = new XmlDocument(); 2 xmlResultsSet.Load(new XmlTextReader(url)); 3 XmlNodeList xmlResponse = xmlResultsSet.SelectNodes("/tapi/document/item");
We then use a foreach loop to cycle over each blog post in the collection.
foreach (XmlNode post in xmlResponse)
I have created an object Blog to allow me to store the information, this is a set of properties relating to the XML file. Within the foreach body, I create a new Blog object and populate the new object with the information I want from the XML response, if you download the full code method I have also processed the related Weblog.
1 Blog blog = new Blog(); 2 blog.Title = post["title"].InnerText; 3 blog.Description = post["excerpt"].InnerText; 4 blog.Created = Convert.ToDateTime(post["created"].InnerText); 5 blog.Url = post["permalink"].InnerText; 6 taggedPosts.Add(blog);
I then have a generic collection to store all of the Blog items to allow it to be access in the UI, in my case I have bound it to a Repeater control in ASP.net.
List<Blog> taggedPosts = new List<Blog>();
You then have a generic collection of Blog objects which relate to tagged blog posts from Technorati. Very cool and very simple.
Details of the API can be found at http://technorati.com/developers/api/tag.html
Sample code can be downloaded here:
http://blog.benhall.me.uk/code/CSharp/Technorati/GetTechnoratiPosts.txt
http://blog.benhall.me.uk/code/CSharp/Technorati/BlogWeblogObject.txt
http://blog.benhall.me.uk/code/CSharp/Technorati/ASPRepeater.txt
I'm using a new Live Writer plugin I found for code highlighting, I think its cool and a big improvement over the previous plugin I tried. One improvement to it would be to trim whitespace from the beginning of each line, as when copying from VS it keeps the tabs and makes it look a mess. Hope you like it.
http://stevedunns.blogspot.com/2006/08/code-formatter-plugin-for-windows-live.html
My First NXT Robot
Last night I finally got around to playing with my NXT. I just did the simple first robot in 30 minutes (took more like an hour) just to get a good idea of how it fits together.
It was good fun, I now need to reprogram it so it can do something a bit more fun than it does at the moment. Very exciting!
Expect more posts over the next week or so.
London Hack Day
Just had it confirmed to me that I have been invited to the London Hack Day which BBC Backstage and Yahoo are running at Alexandra Palace.
If you haven't heard about this, it sounds like a amazing event. Starting Saturday 16th, doors open at 9am, hacking starts at 2pm until 2pm Sunday. After which there is a band playing until 9pm.
The email / Wiki says to bring a sleeping bag as it is some space to get a little bit of sleep and free wifi!
Sounds like it will be a great event and something a little bit different. Just need to decide what I'm going to 'hack'.
If you want to send more information visit http://hackday.org
Its all over! What a week
This morning I completed the last of my three end of year exams. It's been a long week, had the first exam Monday morning, next Wednesday afternoon and one finally this morning. Lot of work, lot of stuff needed to be remembered. Hopefully it will be all worth it.
So that's it now. It's all over. My degree is finished (unless I failed an exam :S)
Off to the bar now, then onto some Silverlight, Linq, MbUnit and NXT coding!! It's just non-stop!!
I've found del.icio.us!
So I might be a bit slow off the mark on this one, but it's better late than never. I've heard about del.icio.us for a while however never really found why I would want to use it - that is until I actually added the "post to del.icio.us" link into the links menu within IE7.
Now I love the fact that I can add something to my page, tag it, then return to the page and continue browsing. I can then return to my page from any machine and have access to everything I need to read/remember. I think its really cool, or maybe its just the fact that I can tag books I want so I don't forget the ones I want to buy/read.
If you haven't looked at it before, I do really recommend it. Its very cool once you get into it.
SLIDE 7 – Microsoft Web Development for Students
Just received this from Stuart, sounds like a great event just for us students!!
"Interested in web technology? Like BBQs? If you answered yes to both questions then we have the perfect event for you!
On the 18th June we are hosting an event just for students at our head office in Reading. The event will focus on our latest and greatest web technologies and you will get the opportunity to hear about cool stuff such as Silverlight and Visual Studio Orcas. As if that weren’t enough we’re capping the day off with a BBQ down by the lake!
The event is free but over half the places have already gone so check out the link below for more info and to sign up:
http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032340760&Culture=en-GB "
The day is broken into two tracks, one on Intro to Web Development, the other Advanced Web Dev. with a BBQ afterwards. Sounds like a great event, one I had mentioned would be really good to hold. I'll be there, if you want to be there you best be quick as places are going fast!
Tracing LINQ to SQL queries without using SQL Profiler
Been meaning to write this up all week however kept getting distracted.
After watching Anders Hejlsberg Mix07 session on Linq, he was using a feature of Linq to log all of the SQL queries being executed within code instead of using SQL Profiler. This is great if your using SQL/C# Express as this doesn't support running SQL profile and with this code you can see gain a level of understanding regarding the SQL queries. Code has been taken from the session video so all credit goes to him.
This code executes two queries, one to select all the customers, with the CustomerID outputted to the console, while the second query returns the customer with the ID 'ALFKI' and outputs all of their orders. The code has a TextWriter which is associated with the database context's Log property and this stores all the queries executed in a file called log.SQL, in this case is saved to the debug directory.
static void Main(string[] args)
{
TextWriter log;
log = File.AppendText("log.sql");
DataClasses1DataContext db = new DataClasses1DataContext();
//db.Log = Console.Out;
db.Log = log;
var query = from c in db.Customers
select c;
foreach (Customer cust in query)
{
Console.WriteLine(cust.ContactName);
}
log.Write("End of getting all customers query\r\n\r\n");
Customer alfki = db.Customers.Single(c => c.CustomerID == "ALFKI");
foreach (Order o in alfki.Orders)
{
Console.WriteLine("{0}:{1}", o.OrderDate, o.OrderID);
}
log.Write("End of getting all orders for alfki\r\n\r\n");
log.Close();
Console.ReadLine();
}
We could then change the query sightly, and instead of having the SQL query being stored in the file we could redirect it to Console.Out and for it to display on our command prompt. Very cool.
For this, we just point the DataContext.Log property to Console.Out
db.Log = Console.Out;
The output generated for this application is:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
SqlProvider\AttributedMetaModel
End of getting all customers query
SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]
FROM [dbo].[Orders] AS [t0]
WHERE [t0].[CustomerID] = @p0
-- @p0: Input NVarChar (Size = 5; Prec = 0; Scale = 0) NOT NULL [ALFKI]
SqlProvider\AttributedMetaModel
End of getting all orders for alfki
This demonstrates how the queries are saved to the log, but also how it displays the parameter (@p0) being passed into the parameterised query when it is executed. I really think this is a great feature, maybe not for production but definitely for development.
Download the code and SQL output here:
http://blog.benhall.me.uk/code/linq/TraceLinqToSQL/TraceLinqToSQL.cs.txt
http://blog.benhall.me.uk/code/linq/TraceLinqToSQL/TraceLinqToSQLLog.sql.txt
University of Hertfordshire Vista and Office Launch
Today I finally got around to holding my Vista and Office Launch event as part of my role as a Microsoft Student Partner.
The event was a chance for students to see what was new and upcoming within Windows Vista and to find some of the more hidden features, such as being able to filter search results and the ReadyBoost feature.
I felt my presentation went well, although my laptop wasn't impressed with me playing the Halo 3 HD trailer while connected to an external projector on power saving mode. After a quick switch to high performance battery mode it worked like a charm. I really enjoyed the event and it went really well, plus it was good experience at presenting again.
Attendance wasn't amazing, we had 14 people turn up and 9 filled out feedback. The feedback was based on a mark out of five, so it appears everyone had a good time, which is shown in the chart below.
Some of the comments from the forms included:
"Well presented", "Very good, learned a lot, thanks", "Good job on the talk mate" and "Will consider getting Vista in the near future"
I'm sure the attendance would have been better if I had the launch before easter and not just before everyones exams, however with the Imagine cup and coursework the original timing wasnt suitable for me.
I would like to thank Chris Glaister who gave the Office side of the presentation and helped out with the general running of the event and to Microsoft UK for providing the freebies/prizes.
Download PowerPoint slide deck here
Bill Gates' and Steve Jobs' secret love
Huge credit to Phil for blogging this. Just in case you don't subscribe to his RSS and you haven't saw these, thought I would post it again here.
"Bill Gates' and Steve Jobs' secret love
These are from a new Sketch show here in the UK called Ruddy Hell! It's Harry and Paul.
http://www.youtube.com/watch?v=WrhmWkRfyAI
http://www.youtube.com/watch?v=Kwy4R8DfOT4
Enjoy.
Phil."
Very cool.
Silverlight Samples on Orcas VPC / Windows 2003
After downloading and installing all the new bits onto my Orcas VPC, first thing I did was create a new Hello World Silverlight application and set the Canvas to Red. Nothing appeared under intellisense like I was expecting, I'll blog about this later, so I hit F5 and nothing came up.
I then loaded a sample and the same thing happened.
After a moment or two, I realised that Windows 2003 has it's IE security settings set to high, blocking most things happening - which definitely blocks Silverlight from executing either locally or remotely.
Simple fix is to change the security setting in IE (Tools > Options> Security) to 'Default Level' which is Medium. You should then still have a safe browsing experience, together with Silverlight being able to execute.





Social networks
Twitter GitHub SlideShare