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 FilesMicrosoft Visual Studio 8XmlSchemas

Next 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.

Technorati tags:

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 DocumentsVisual 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.

Technorati tags:

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 FilesReference AssembliesMicrosoftFrameworkv3.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() which causes it to execute the query, and convert the result to a generic collection of type .

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

Technorati tags: ,

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"?> 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

Technorati tags: ,

My First NXT Robot

NXT RobotLast 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.

Technorati tags: , ,

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

Technorati tags: , , , ,

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!

 

Technorati tags: , ,

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 queryrnrn”);

  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 alfkirnrn”);
  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]
SqlProviderAttributedMetaModel

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]
SqlProviderAttributedMetaModel

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

Technorati tags: , , ,