SpriteHand
Module Border
  Andy's Blog
Module Border
Author: host Created: 3/6/2006 9:55 PM
Adventures in .NET

LINQ to SQL CRUD
By Andy Beaulieu on 3/28/2008 12:42 PM

I'm seeing a lot of buzz around LINQ to SQL lately and how it can help to quickly create a Silverlight 2 data app.

I'll be giving a talk around this at the upcoming Code Camp 9 in Waltham, MA, and I wanted to share how I am doing basic CRUD operations in LINQ to SQL, as I've seen this question come up a few times.

You may remember my Silverlight 1.1 Alpha demo app, "Andy's Fridge." I'll be using a similar Beer Database which has a very simple schema containing Beers and Brewers like so:

It's important to note that the RowVersionId columns in the diagram are Timestamp columns. This will allow LINQ to SQL to generate more efficient Update statements, based on the unique Row Id (timestamp) instead of Where clauses with lots of logical "AND's" for each original value.

So, given that schema is like that above, our CRUD operations for the Beer entity would exist in our web service like so:

public class BeerService : IBeerService

{

 

    public List<Beer> GetAllBeers()

    {

        DataClassesDataContext db = new DataClassesDataContext();

        var beers = from b in db.Beers

                    orderby b.BeerName

                    select b;

 

        return beers.ToList<Beer>();

    }

 

    public void SaveBeer(Beer beer)

    {

        DataClassesDataContext db = new DataClassesDataContext();

 

        if (beer.BeerId > 0)

        {

            // this is an update

            db.Beers.Attach(beer, true);

        }

        else

        {

            // this is an insert

            db.Beers.InsertOnSubmit(beer);

        }

        db.SubmitChanges();

    }

 

    public void DeleteBeer(Beer beer)

    {

        DataClassesDataContext db = new DataClassesDataContext();

        db.Beers.Attach(beer, false);

        db.Beers.DeleteOnSubmit(beer);

        db.SubmitChanges();

    }

}

 

Note that I piggybacked the SaveBeer method to do either an Insert operation or Update operation, based on whether or not a primary key is available in the passed entity.

I guess until ADO.NET Data Services (Astoria) and the Entity Framework are officially available, we will have to settle with LINQ to SQL for Data Access! But I don't think we will be waiting long :)

What can we look forward to with Astoria and the EF?

  • no need to write tedious web service methods for CRUD operations like shown above
  • serialization of Parent and Child records (LINQ to SQL cannot pass related child records across the wire with parent rows)
  • Access to other Database Providers other than SQL Server.
  • The ability to flexibly map Conceptual model elements such as class properties to Physical columns in the database (LINQ to SQL provides only a 1-to-1 mapping)
Comments (1)

When in Beta, Not all Locales are Created Equal?
By Andy Beaulieu on 3/18/2008 4:11 PM

I ran into an odd Silverlight Beta 1 problem after releasing the latest version of "Sort the Foobars" - the game worked fine for me in testing, but shortly after putting it up on this site I received several comments about it crashing in different locales, like Russian and French (you can see those comments here)

The exception looked something like this:

Silverlight error message
ErrorCode: 4002
ErrorType: ManagedRuntimeError
Message: System.Exception: Défaillance irrémédiable (Error 0x1709. Debugging resource strings are unavailable. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=mscorrc.dll&Key=0x1709 0x8000FFFF (E_UNEXPECTED)) at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(IntPtr oPtr, UInt32 iPropertyId, String s)
at MS.Internal.XcpImports.SetValue(IntPtr oPtr, UInt32 iPropertyId, Object obj)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean isSetByStyle, Boolean isSetByBuiltInStyle)
at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)

So the first question is, how do you set up your development machine to test the other locales? It turns out this part is easy - go to Control Panel/Regional Settings and set the language to, say Russian.

After doing that, I found that this was the line of code that was dying:

   this.SetValue(Canvas.LeftProperty, X)

Not much to that… “this” is a UserControl and (here is the key part!) “X” is a float. So apparently, setting the left property to a float is bad outside of en-us J 

I added a Convert.ToDouble(X) in there and it seems happy now:

   this.SetValue(Canvas.LeftProperty, Convert.ToDouble(X))

So the moral of the story? I think that the different behavior is hopefully because this is still a Beta release of Silverlight... Because we would really hope for consistent behavior between Locales! But on the other hand, you still need to be careful with setting Dependency properties to types that they aren't suited for!


Comments (3)

Calling an .asmx Web Service in Silverlight 2
By Andy Beaulieu on 3/17/2008 6:14 PM

I wanted to share a couple of tips for calling web services from a Silverlight client.

If you are just beginning to useWeb Services from a Silverlight 2 Client, Tim Heuer has a good introductory post here.

Getting the Binding Url
A lot of the web service samples will show the binding created with a hardcoded Uri such as this:

WebServiceSoapClient webSvc = new WebServiceSoapClient(binding, new System.ServiceModel.EndpointAddress("http://localhost/MyWebService.asmx"));

The problem being of course that the EndpointAddress is hardcoded to localhost, and you may not know what server you will ultimately deploy to. You could add the Uri as a configuration setting, but there is a more flexible way.

Chances are, your web service is hosted on the same web server that your Silverlight application downloads from. So when you create your Web Service binding, you can determine the Url for you service to bind to based on the current browser Uri:

public static string GetUrlForResource(string resourcePage)
{
    string webUrl = System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString();

    string containerPage = webUrl.Substring(webUrl.LastIndexOf("/") + 1);

    webUrl = webUrl.Replace(containerPage, resourcePage);

 

    return webUrl;

}

... So the method above, when passed a resource string such as "MyWebService.asmx" will return a full Url for a page that is in the same virtual directory as the silverlight app.

When binding, you can then use this utility method like so:

// get the full url of the Web Service
string
webServiceUrl = GetUrlForResource("WebService.asmx");

System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();

WebServiceSoapClient webSvc = new WebServiceSoapClient(binding, new System.ServiceModel.EndpointAddress(webServiceUrl));

webSvc.HelloWorldCompleted += new EventHandler<HelloWorldCompletedEventArgs>(webSvc_HelloWorldCompleted);
webSvc.HelloWorldAsync();

Keep an Eye on MaxReceivedMessageSize
If your web service is returning a lot of data, you may blow out the default max message size for a return. If this happens you will get an exception like so:

An exception of type 'System.ServiceModel.CommunicationException' occurred in System.ServiceModel.dll but was not handled in user code

Additional information: [MaxReceivedMessageSizeExceeded]

To remedy this, you can up the MaxReceivedMessageSize attribute of the binding like so:

System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();

// if you are getting a LOT of data back, you will need to up Message Size
binding.MaxReceivedMessageSize = int.MaxValue;

Comments (5)

Sort the Foobars for Silverlight 2 Beta 1
By Andy Beaulieu on 3/16/2008 9:32 AM

I have updated "Sort the Foobars" to Silverlight 2 Beta 1... Have fun sorting!

Comments (7)

David Laribee on Hanselminutes
By Andy Beaulieu on 3/14/2008 7:53 AM
Just wanted to give a shout out to David Laribee, who is featured on Hanselmintues this week speaking about ALT.NET! For people who frequent our local CNY .NET Developer Group, Dave has donated his time to speaking at the group and his company, XClaim Software, has a developer presence right here in Syracuse.
Comments (0)

MIX08 Show Off! Event
By Andy Beaulieu on 3/8/2008 11:50 PM

Woohoo - the video that Bill Reiss and I created for the MIX08 Show Off! Event took second place! The video showed off some demos and games we created using the Farseer Physics engine created by Jeff Weber.

Details are here, and the video should be posted at visitmix.com "soon"...

UPDATE 3/12/08: It looks like the videos still haven't been posted on visitmix.com, so I figured I would encode it myself and throw it up on Silverlight Streaming... Here it is, enjoy. Also, if you are interested in seeing the First Place winner, Crayon Physics, you can see that here.

ANOTHER UPDATE: I just learned that the rest of the videos are up, you can see them here.

Comments (0)

Tunnel Trouble - Silverlight 2 Beta 1 Scroller
By Andy Beaulieu on 3/6/2008 8:08 PM

I am sitting in on a presentation at MIX, “Silverlight as a Gaming Platform” by Joel Neubeck and Scott McAndrew of TerraLever. They created a very cool scrolling puzzle game using Silverlight 2 Beta 1, named Tunnel Trouble, which is currently available on Miniclip.com. Miniclip is probably the most popular casual games site on the internet. I don't think Miniclip is allowing the game to be found through their search function yet, so I'm not even sure they will keep the game accessible...

 

The game is a tile-based scroller inspired by Valve’s Portal (part of the Orange Box), in which a beaver needs to rescue his children in an underground maze. The designers used TileStudio to design the tile-based levels. Very cool!

Comments (0)

Using HitTest Method in Silverlight 2 for Collision Detection
By Andy Beaulieu on 3/6/2008 12:03 PM

Prior to Silverlight 2.0 Beta 1, there was no method provided in the framework for determining if two UI elements were colliding. So if you wanted collision testing, you had to pretty much brew up your own. But there is now a HitTest method provided on the UIElement class. This method returns a list of elements that intersect with a Point or Rect. Not particularly helpful out of the box, and also not a very fast operation, but using this new HitTest method we can do some fair collision detection.

 

[TRY THE DEMO]  [DOWNLOAD SOURCE]

 

If you try the demo above (Silverlight 2 Beta 1 Required), you can use the mouse to move the ship around the asteroid. Notice that a collision is only detected when the ship's outer path element collides with the asteroid's path element.

 

This was done using the method below, which can be used to determine if two UI Elements are colliding. Remember that the HitTest method is very slow so we always want to do a quick Rectangle Intersect collision test first before doing a per-pixel HitTest. Once intersection rectangle is found, the code simply loops through pixel-by-pixel to see if both elements in question share a HitTest on the same x,y pixel…

 

private bool CheckCollision(FrameworkElement control1, FrameworkElement controlElem1, FrameworkElement control2, FrameworkElement controlElem2)

{

    // first see if sprite rectangles collide

    Rect rect1 = UserControlBounds(control1);

    Rect rect2 = UserControlBounds(control2);

 

 

    rect1.Intersect(rect2);

    if (rect1 == Rect.Empty)

    {

        // no collision - GET OUT!

        return false;

    }

    else

    {

        bool bCollision = false;

        Point ptCheck = new Point();

 

        // now we do a more accurate pixel hit test

        for (int x = Convert.ToInt32(rect1.X); x < Convert.ToInt32(rect1.X + rect1.Width); x++)

        {

            for (int y = Convert.ToInt32(rect1.Y); y < Convert.ToInt32(rect1.Y + rect1.Height); y++)

            {

                ptCheck.X = x;

                ptCheck.Y = y;

 

                List<UIElement> hits = (List<UIElement>)control1.HitTest(ptCheck);

                if (hits.Contains(controlElem1))

                {

                    // we have a hit on the first control elem,

                    // now see if the second elem has a similar hit

                    List<UIElement> hits2 = (List<UIElement>)control2.HitTest(ptCheck);

                    if (hits2.Contains(controlElem2))

                    {

                        bCollision = true;

                        break;

                    }

                }

            }

            if (bCollision) break;

        }

        return bCollision;

    }

 

  

}

 

Comments (8)

Silverlight 2 Beta 1 Available
By Andy Beaulieu on 3/5/2008 7:26 PM

The download for Silverlight 2 Beta 1 is now available (follow the link and scroll to the bottom of this page).

Silverlight 2 Beta 1 adds tons of functionality over the Silverlight 1.1 Alpha, and as expected will break a lot of the Alpha 1.1 samples that are out in the wild. I was lucky enough to participate in the early Beta builds for Silverlight 2 and have posted updated versions of several of my Silverlight 1.1 Alpha games and demos. Just follow the links in the details to the right of this page. To hopefully help some folks out, I would like to share some of what I learned while converting my Alpha 1.1 projects to Beta 1. Having written a lot of Alpha 1.1 code, I was quite daunted by the sheer number of changes.

 

To start, if you take a look at the Silverlight 2 Help File, there is a section called “Breaking Changes Silverlight 2” which is a good starter which covers a lot of the common issues.

 

A lot of credit for these fixes goes to the Silverlight Insiders group I was involved with, and the beta support forums.

 

New DispatcherTimer instead of Empty Storyboard

Prior to Silverlight 2.0 Beta, there was no proper timer class available – instead, we needed to fake a timer using a Storyboard. But Beta 1 now includes a DispatcherTimer class, which makes creating custom timers cleaner (for things like a Game Loop):

 

            _timer = new DispatcherTimer();

            _timer.Interval = new TimeSpan(20);

            _timer.Tick += new EventHandler(_timer_Completed);

 

Why aren’t my Sound Files Playing in Silverlight 2.0?

 Thanks to Adam Kinney and Bill Reiss for the answer to this one. When migrating my Silverlight 1.1 Alpha code, it seemed none of my .wma sound files would play. Instead, I would get a MediaError – AG_E_UNKNOWN_ERROR when my application loaded. Checking the HTTP Request statuses shows that the request is looking for the WMA files in a location relative to ClientBin. This is due to how the new Silverlight Project Template packages things up for deployment.

 

So to correct this, you have two choices: (1) place your sound files relative to ClientBin or (2) Set your sound files’ Build Action to Content, and then refer to them with a root reference “/folder/file.wma” such as below:

 

                MediaElement newSound = new MediaElement();

                newSound.Source = new Uri("/sounds/explosion1.wma", UriKind.Relative);

                newSound.AutoPlay = false;

                _parentCanvas.Children.Add(newSound);

 

Why am I Getting an HTTP 404 Error on my Silverlight XAP file?

Make sure you add the appropriate MIME data types to your web server. Additionally you need to add xaml and dll mime types (if you did not for Alpha 1.1 as of yet)

 

What am I getting “An item with the same key has already been added” – Error in xaml if more than 1 element has the same xmlns: attribute”?

Previous builds of Blend placed addition xmlns attributes on named UI elements. You need to search for any xmlns attributes in your XAML and delete them.

 

Why I am I getting “User Control does not support Canvas as content”?

Be sure that the base class you are inheriting from is inherited from UserControl and not just “Control” or another class.

  

What happened to the BrowserHost class?

BrowserHost,  which used to exist in System.Windows.Interop, is now missing. Instead, you can use:

System.Windows.Application.Current.Host.Content.Resized += new EventHandler(Content_Resized);
System.Windows.Application.Current.Host.Content.ActualHeight
System.Windows.Application.Current.Host.Content.ActualWidth

What happened to HtmlPage.Navigate and HtmlPage.DocumentUri?

System.Windows.Browser.HtmlPage.Navigate is now on the HtmlWindow class, accessible via:

System.Windows.Browser.HtmlPage.Window.Navigate

 

… and also the current browser Document’s Uri can be found at:

System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsolutePath 

 

What happened to MouseEventArgs and KeyboardEventArgs?

MouseEventArgs is now MouseButtonEventArgs
MouseEventHandler is now MouseButtonEventHandler
KeyboardEventArgs is now KeyEventArgs. Also, there is now an enumeration, System.Windows.Input.Key, which you can use instead of integer values for key codes.
KeyboardEventHandler is now KeyEventHandler

What happened to my MediaEnded Event Handler?

Events such as MediaEnded no longer use EventHandler and EventArgs. Instead they now use RoutedEventHandler and RoutedEventArgs. Example:

theSound.MediaEnded += new RoutedEventHandler(theSound_MediaEnded);
void theSound_MediaEnded(object sender, RoutedEventArgs e)
{
}

Why are some Generic Collections missing?

Some Generic and non-Generic Collections removed to save some space: http://blogs.msdn.com/bclteam/archive/2007/06/26/non-generic-collections-to-be-removed-from-silverlight-inbar-gazit.aspx


What happened to Rect.Intersect and the other Rect class utility methods?

Some Rect methods were moved to save space. However, you can use the following method in place of Rect.Intersect: (Also note that there is a new HitTest method which can be coerced into doing collision detection between two paths).

 

rect1.Intersect(rect2);

if (rect1 == Rect.Empty)

{

// No collision!

}

else

{

// Collision!

}

Why can’t I install Silverlight Beta 1?

When installing, I get the following error:

 

An Error Has Occurred:

Silverlight Tools cannot be installed because one or more of the following conditions is true:

 

1. Visual Studio 2008 RTM is not installed.

2. The Web Authoring feature of Visual Studio is not installed.

3. A previous version of the Silverlight Runtime is installed.

4. A previous version of the Silverlight SDK is installed.

5. The Visual Studio Update KBXXXXXX is installed.

6. A previous version of Silverlight Tools is installed.

 

To continue, please install or uninstall the …

 

This is usually due to the KBXXXXXX update. To find and remove this update, go to Add/Remove Programs and check the “Show Updates” checkbox at the top of the dialog. Then scroll down to “Microsoft Visual Studio 2008 Professional Edition – ENU” and you should see the KB install there.

Comments (0)

See you at MIX?
By Andy Beaulieu on 2/25/2008 10:11 AM
Bling

I'm very excited to be going to MIX next week! There will be a lot of great news surrounding Silverlight 2.0 Beta 1, and I'm looking forward to meeting some fellow Silverlight geeks in person.

I also got together with Bill Reiss and created a video for the Show Off Event on Thursday night, which centers around Silverlight and the Farseer Physics engine. Ok, we might end up on the cutting room floor, but it was a fun endeavor for sure.

Comments (2)

Module Border Module Border
Module Border
  Blog_List
Module Border
Module Border Module Border
Module Border
  Subscribe
Module Border

RSS

Module Border Module Border
Module Border
  Diversions
Module Border

DESTROY ALL INVADERS
A scrolling shooter game where the objective is to destroy the invading UFO's flying over a neighborhood of your choosing. Imagery provided by Microsoft Virtual Earth. Created using Silverlight 2.
PLAY IT

INFO AND CODE



SORT THE FOOBARS
A game where you need to sort the good foobars from the bad ones. Created using Silverlight 2 and the Farseer Physics engine.
PLAY IT

MORE INFO



POLYGON PHYSICS DEMO
A demo showing polygon physics where the user draws physics objects with the mouse. Created using Silverlight 2 and the Farseer Physics engine.
PLAY IT

MORE INFO



SILVERLIGHT ROCKS!
Destroy the asteroids before they destroy your ship! Created using Silverlight 2.
PLAY IT

INFO AND CODE



FISH GAME
A simple game of harpoon-the-fish. Written using the AJAX Sprite Toolkit.
PLAY IT

INFO AND CODE

Module Border Module Border
Module Border
  Search_Blog
Module Border
Module Border Module Border
Module Border
  Blog_Archive
Module Border
Module Border Module Border
Copyright (c) 2008 andy.beaulieu.com - Login