Some stuff about Web and .NET development
RSS icon Email icon Home icon
  • Silverlight 3 : first impressions

    Posted on August 23rd, 2009 Thibaut 1 comment

    Silverlight Having recently started my initiation to Silverlight by completing the workshops of MSDN Silverlight coach and making my first app with this technology, here are my impressions of Silverlight (some specific to version 3 and other ones more general), from a Web/ASP.NET developer point of view :

    • RIA have a much nicer feeling than traditional web apps (even the AJAX-enabled ones), which is faster, smoother, really a better user experience
    • Productivity seems, at first sight, much higher than with ASP.NET. There’s no loss of time with cross-browser compatibility and such concerns. What you see is what you get everywhere. Beyond of that, I was able to get really fast a nice version of my app. For example, a DataGrid comes, in its simplest form (drag & drop from the toolbox) with alternating colors, mouse over effects, column sorting and column resizing. Also, you find interesting controls in the standard toolbox, such as charts, widely used in business apps
    • One of the first thing I wanted to do is create a button. Where’s my Id property ? And the Text one ? Well, it’s actually Name and Content respectively… Name replaces Id in Silverlight, while the Content property allows you, for some controls, to specify other things than text (you can put a video in a button if you want, or a calendar, which is the big difference compared to ASP.NET where you’re limited by the available XHTML tags. As the UI in Silverlight is vector graphics, you’re just limited by your imagination)
    • Some conventions (or habits) are no longer respected. OnFocus and OnBlur events become GotFocus and LostFocus. What about the “On” prefix convention for events ? There’s no more DataSource but an ItemSource, the Margin property is not the same as the CSS one (left, top, right, bottom in Silverlight compared to top, right, bottom, left in CSS). These are little details, among other ones of the same kind, that makes the adaptation time higher than what it would be by taking into account the habits of web and ASP.NET developers
    • There’s no designer in Visual Studio 2008 for XAML edition. After some investigation on the web, it seems that it’s going back with Visual Studio 2010 but in the meanwhile, you gotta use Expression Blend
    • Another big difference is that the code behind of a XAML file (equivalent to the ASPX file in ASP.NET), be it in C# or VB, is executed client side. It’s some never-seen for ASP.NET developers, having associated C# with server side execution. Of course, you must develop accordingly : you’re not gonna open a DB connection with client side code, for example
    • As a consequence with the client side execution of C# (or VB) in Silverlight, ADO.NET has been thrown away. So forget DataSets, DataReaders etc and get used to WCF, .NET RIA Services, …
    • The designer/developer cooperation goes even further with Silverlight, providing separated tools (Expression Blend for the designers and Visual Studio for the developers), allowing to work simultaneously on the same project files and get an instantaneous result from one’s work
    • Silverlight 3 is a milestone release and according to me, the first version that could really be used to develop a full application based on it. A lot of improvement has been done since its first release (that time where the code behind had to be written in Javascript seems far away…)

    Conclusion

    Globally very positive. After a little time of adaptation, I was able to develop a nice looking app with little coding. The result is fast, feels smooth, it’s a real pleasure to use such a web application. This technology has a great potential, most certainly for business apps where too much time is lost dealing with browser concerns (and where SEO isn’t needed). I would most certainly go with Silverlight for these kind of applications by now…

    Don’t hesitate to share your impressions and return of experiences, I’d be interested to hear from you ;)

    Share/Save/Bookmark

  • Silverlight : goodbye XmlDocument, hello XDocument !

    Posted on August 15th, 2009 Thibaut 2 comments

    SilverlightI just started my initiation to Silverlight and noticed while following the workshops of the MSDN Coachs program that a class XDocument was used to parse some Xml. So I thought at first “what’s that new class ? Why didn’t they use XmlDocument ?”.

    Well, simply because it’s gone ! The reason of that, found on the forums of the official Silverlight website, is that because Linq to Xml is the recommended way to work with Xml in Silverlight, so System.Xml.XmlDocument was removed and is now succeeded by System.Xml.Linq.XDocument.

    For those who’re new to Linq to Xml, here’s a quick example of what you can perform with that powerful technique :

    1. The class, using auto-implemented properties

    public class DiggStory

    {

        public int      Id { get; set; }

        public string   Title { get; set; }

        public string   Description { get; set; }

        public string   HrefLink { get; set; }

        public int      NumDiggs { get; set; }

        public string   Thumbnail { get; set; }

    }

    2. Using Linq to Xml

    XDocument xmlStories = XDocument.Parse(xmlContent);

     

    var stories = from story in xmlStories.Descendants("story")

                  where story.Element("thumbnail") != null

                  select new DiggStory

                             {

                                 Id = (int) story.Attribute("id"),

                                 Title = (string) story.Attribute("title"),

                                 Description = (string) story.Attribute("description"),

                                 Thumbnail = (string) story.Attribute("thumbnail"),

                                 HrefLink = (string) story.Attribute("link"),

                                 NumDiggs = (int) story.Attribute("diggs")

                             };

    3. Conclusion

    Advantages of this method is that :

    1. It’s way more elegant than classic XPath strings
    2. You get a collection of strongly typed items
    3. It’s very easy to perform databinding on the basis of the item properties

    Make good use of it ;)

    Share/Save/Bookmark

  • Who’s your coach ?

    Posted on August 4th, 2009 Thibaut 3 comments

    For the french-speaking readers out there, Microsoft has launched the MSDN coachs program. You’ll find tutorials, screencasts and exercises about many topics such as Mobile and Web development, Silverlight, C#, Sql Server and many more. I really like the idea of going back to basics and learning the most important things, thus making effective use of your time. Some sections are still in development but growing every day. There is currently no english version but I guess it will be done in the future.

    Below, an overview of the coachs available for training. Click on the picture to go on the official site.

    MSDN coachs

    Share/Save/Bookmark

  • REMIX 09 : I’ll be there !

    Posted on August 3rd, 2009 Thibaut No comments
    REMIX The REMIX, re-edition of the popular MIX event will take place at Kinepolis Bxl on September 29. This free event will propose two different tracks :

    1. User Experience Track : prototyping with SketchFlow, Surface, creating Silverlight experiences, …
    2. Web Developer Track : Silverlight 3 new features, Expression Blend, …

    And as usual, I’ll post a summary of the event on my blog so don’t forget to check it out. See you there ;)

    Share/Save/Bookmark

  • Implementing the Bing API in a ASP.NET website (part 2)

    Posted on July 22nd, 2009 Thibaut 7 comments

    In my last post, we saw how to get started with the Bing API. But the MSDN code is lacking (intentionally) from the following things that you might find useful :

    • You want to use Bing from a website and not from a console application
    • You want to use Bing to search on a particular website and not the whole web
    • You might want to handle the different kinds of errors/informations the right way
    • Some paging would also be very useful to browse the results
    • And maybe simplifying the code, extracting constants to ease their setup

    That’s what we’re gonna see here by taking a look at my implementation. Let’s see what the code is all about, then we’ll discuss about it. The code will be splitted in several parts, so we can discuss about it step by step.

    1. Extracting hardcoded values into constants

    public partial class SearchResults : Page

    {

        private const string BingApplicationId = "YourAppIDHere";

        private const string WebsiteToSearch = "http://www.thibautvs.com";

        private const int MaxResultsCount = 50; // Max value : 50 (Bing API v2.0)

        private const int PageSize = 10;

        private const string SearchLanguage = "en-US";

        private const bool HighlightText = true;

        private const string BingApiVersion = "2.0";

    First, I extracted all the hardcoded values in the code into constants. That’s way easier to setup the values. I also added one which enables you to easily activate/deactivate text highlighting of the keywords in the search result and the PageSize constant to take into account the paging functionality. From experience, I noticed that the BingService throws a SoapException when the ResultsCount is too large. By experimentation, I noticed that the value must be max 50. You can take a look at the MSDN to get more info about this restriction.

    2. Initializing the search request

    protected void Page_Load(object sender, EventArgs e)

    {

        this.dpgSearchResultsPager.PageSize = PageSize;

        InitializeSearchResults();

    }

    In the Page_Load, we initialize the PageSize of our pager (which is a DataPager bound to a ListView in the aspx page) and call the InitializeSearchResults() method.

    private void InitializeSearchResults()

    {

        using (BingService service = new BingService())

        {

            try

            {

                SearchRequest request = BuildRequest();

                SearchResponse response = service.Search(request);

                DisplayResponse(response);

            }

            catch (System.Web.Services.Protocols.SoapException ex)

            {

                DisplayErrors(ex.Detail);

            }

            catch (System.Net.WebException ex)

            {

                Console.WriteLine(ex.Message);

            }

        }

    }

    Tthe InitializeSearchResults method makes use of the BingService, which implements the IDisposable interface (thus, used here with the using keyword) in order to :

    1. Initialize the search request
    2. Get a search response
    3. Display the response
    4. Handle a SOAP exception, if there is one
    5. Handle a network exception, if there is one

    private SearchRequest BuildRequest()

    {

        SearchRequest request = new SearchRequest();

     

        // Common request fields (required)

        request.AppId = BingApplicationId;

        request.Query = Request.QueryString["keyword"] + string.Format(" (site:\"{0}\")", WebsiteToSearch);

        request.Sources = new SourceType[] { SourceType.Web };

     

        // Common request fields (optional)

        request.Version = BingApiVersion;

        request.Market = SearchLanguage;

        request.Adult = AdultOption.Moderate;

        request.AdultSpecified = true;

        request.Options = new SearchOption[] { SearchOption.EnableHighlighting };

     

        // Web-specific request fields (optional)

        request.Web = new WebRequest();

        request.Web.Count = MaxResultsCount;

        request.Web.CountSpecified = true;

        request.Web.Offset = 0;

        request.Web.OffsetSpecified = true;

        request.Web.Options = new WebSearchOption[]

        {

            WebSearchOption.DisableHostCollapsing,

            WebSearchOption.DisableQueryAlterations

        };

     

        return request;

    }

    Again, the code shown by the BuildRequest() method is autodescriptive. Just a precision about the search query : the code here assumes that you’re passing a keyword to the page via the querystring and in order to restrict the search to a particular website, your query must have the following form :

    keywordToSearchFor (site:http://www.thesitetosearch.com)

    3. Displaying the results

    private void DisplayResponse(SearchResponse response)

    {

        // If no results were found, display message and return

        if (response.Web == null || response.Web.Results == null)

        {

            this.litInformationZone.Text = "No results found.";

            return;

        }

     

        // Otherwise, perform databinding

        this.lvwSearchResults.DataSource = response.Web.Results;

        this.lvwSearchResults.DataBind();

    }

    As a crash occured when I submitted to Bing a request having no result (response.Web.Results having a NULL value), the first thing I do here is to protect the code from that error and warn the user by a message that her search query has no result. The litInformationZone is just a simple Literal object (and thus why I prefixed this “lit”). If the search has results, we perform the databinding with our ListView.

    4. Displaying the errors

    As errors may always occur, we have to handle them properly and display them to the user in a more convenient form than a disgracious exception message. Another lesson that Steve Krug teaches us in his Don’t make me think book is always apologize for the inconvenience to the user and explain to her briefly the error she’s encountered. This is where I started creating my own ErrorPanel UserControl that I used here and can also be reused later, so I suggest you doing the same. This UserControl is reffered in my code as pnlError and has one public property : ErrorMessage.

    private void DisplayErrors(XmlNode errorDetails)

    {

        // Add the default namespace to the namespace manager.

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(errorDetails.OwnerDocument.NameTable);

        nsmgr.AddNamespace("api", "http://schemas.microsoft.com/LiveSearch/2008/03/Search");

        XmlNodeList errors = errorDetails.SelectNodes("./api:Errors/api:Error", nsmgr);

     

        if (errors != null)

        {

            StringBuilder builder = new StringBuilder();

     

            foreach (XmlNode error in errors)

            {

                foreach (XmlNode detail in error.ChildNodes)

                    builder.AppendLine(detail.Name + ": " + detail.InnerText);

     

                builder.AppendLine(Environment.NewLine);

            }

     

            this.pnlError.ErrorMessage = builder.ToString();

            this.pnlError.Visible = true;

        }

    }

    5. Enjoying the final result

    Time to watch some screens about the final result of all this work :

    Search results

    You can see from this picture the paging feature (that we’ll cover more in detail in a future article) and the highlight of the search keywords in the description text. By the way, this is accomplished by replacing the delimiter characters by a span having a specific CSS class. Code to accomplish this is shown below :

    if (HighlightText)

        description = description.Replace("\uE000", "<span class=’highlight’>").Replace("\uE001", "</span>");

    else

        description = description.Replace("\uE000", string.Empty).Replace("\uE001", string.Empty);

    Of course, your website needs to be indexed by Bing in order to perform searches on it. To check if your website is indexed, type “site:yoursiteurl” into Bing (ex : site:http://thibautvs.com). If it isn’t indexed yet, it will propose you to submit the URL so it can index it.

    6. Conclusion

    And this is it ! As you can see, the Bing API is pretty cool and easy to implement (actually, I took me less than 2 hours to get a first, beta running version). And a lot more services such as searching for images, videos, instant answers, mobile web, ads, phone books, using spell checkers or translations, … are also available (more info on the MSDN). Hope you’ve enjoyed this article, don’t hesitate if you would have any questions about that.

    See you ;)

    Share/Save/Bookmark

  • BESUG Silverlight Workshop : I’ll be there

    Posted on July 21st, 2009 Thibaut No comments

    Besug Silverlight

    The next BESUG event, sheduled for September 10th, is going to be a Silverlight workshop. As the beta of Silverlight 3.0 unveiled at the MIX introduces a lot of cool and interesting features, the aim of the workshop is to provide a hands-on session of 2 hours about discovering all of that. During the workshop will be built a Silverlight application and concepts such as out of the browser, animation easing, deeplinking, pixel effects, importing Photoshop files and perspective 3D will be covered.

    You’ll need to bring your own laptop with all the needed softs installed on it (for more info, check out the BESUG event page). As usual, the event is completely free of charge and will take place this time at Boulevart, an interactive production agency. Be sure to register fast cause places are limited to 30 participants !

    See you there ;)

    Share/Save/Bookmark

  • User Experience @ Vitra : I’ll be there

    Posted on May 25th, 2009 Thibaut 1 comment

    User Experience @ Vitra is a mix of demos and informations about Silverlight, Web development, Surface, Windows 7 etc presented by Microsoft and Vitra. The BESUG (Belgian Silverlght User Group) - a group I’ve subscribed for, which organizes conferences about Silverlight in Belgium - will also be present for some talks and demos. This event will start at 7pm and will be held at the 4 different dates and places :

    • 2nd June Antwerpen (Gijzelaarsstraat 20)
    • 4th June Diegem (Woluwelaan 137)
    • 10th June Gent (Vlaanderenstraat 107)
    • 11th June Luik (Rue Matrognard 13)

    I’ve subscribed for the 2nd of June and BTW this is a free event. For more info, take a look at the facebook page of the event.

    See you there ;)

    Share/Save/Bookmark

  • Back from the Techdays

    Posted on March 16th, 2009 Thibaut No comments

    Here is a summary of the sessions I assisted at the Techdays on Wednesday 11th.

    Techdays 09

    Introduction

    • Evolution of software : SOA trend and cloud computing advent
    • Demo of Blend : the graphist and the developer work at the same time on the same project, the graphist makes some modifications and the developer gets the result when launching the app the next time (and vice-versa)
    • Demo of Surface : very impressive, visit the official website to watch the videos. Easy to make apps for surface as that’s WPF with just one lil’ layer onto it
    • Video of Microsoft’s future vision for apps in 2019

    .NET continuum: ASP.NET, AJAX, Silverlight and WPF (by Laurent Bugnion)

    • From the less powerful to the most : ASP.NET, AJAX, Silverlight then WPF
    • Shows how to interact with a WCF service with ASP.NET MVC (postback), ASP.NET AJAX (asynchronous, better UI reaction), Silverlight (only asynchronously, subset of .NET power) and WPF (asynchronous or synchronous, full .NET power)
    • Description of the Model/View pattern
    • Introduction of Dr WPF, a blogger very active in the WPF world

    Silverlight CoreCLR: Bringing the power of .NET to the net (by Andrew Pardoe)

    • Demonstration of the performance of Silverlight, compared to a Javascript application. Chess game, averaging 420,000 nodes per second in Silverlight vs. Javascript at 23,000 nodes per second in the search tree. Complete source code is available for the doubtful guys
    • Anything that can host ActiveX can host CoreCLR
    • Sandboxed execution : one execution domain per Silverlight app. Security increased
    • Same application model between browser and desktop : very easy to port a desktop-WPF app to a browser-Silverlight one
    • Dynamic Language Runtime (DLR) : language interoperability. App written in Python or Ruby can interact with the CoreCLR. Ex : IronPython or IronRuby

    WPF performance & best practices (by Dirk Primbs)

    • First advice about performance : focus on scenario and customer expectations. Do not try all the new visual effects on the same page or it obviously risks to slow down your app
    • The visual tree (containing all the controls and parts of them) can become too large. Use Snoop, a very powerful tool, that enables you to visualize that tree
    • Use optimized controls. For example, the VirtualizingStackPanel instead of the StackPanel, will render its content only when visible (suppose you have a lot of elements, and only a portion of them are visible through scrolling, rendering all of them in your page load isn’t a good solution)
    • Picture processing : try to avoid using large pictures and use caching options such as BitmapCacheOption
    • WPF Performance Suite : great tool for measuring performance of WPF apps
    • Hardware acceleration : 3 tiers (tier 0 : old pc, < DX7, tier 1 : between DX 7 and 9, tier 2 : DX >= 9). App can be set to run at a determined tier to simulate behaviour of less powerful machines and thus tune the perfs of your apps

    Under the hood in Silverlight’s controls skinning framework (by Gill Cleeren)

    • Speaker showed how to create a skin for a button (a purple ellispe with gradient brush)
    • Styling vs. skinning : styling is limited, skinning is completely new look, visual tree and properties
    • Parts & states model : separate logic from visual, contract between coder and designer, supported by Blend. Enables you to add new properties to existing ones on a control
    • Part : the working thing. Eg : a button has no part since the button is itself the part, but in a slider, the part is the little thumb that can be dragged
    • States : the different states of a control, such as mouseover, pressed, etc

    Windows 7 for developers (by Katrien De Graeve)

    • New features for consumers but also for developers
    • Showed the new features for the consumer (the docking features, etc, many articles available on the web about that)
    • Developer point of view : multi monitor support, even when remoting. Problem step recorder : screenshots of every steps of a bug reproduction are taken and then submitted to the developer
    • Compatibility : what works on Vista will work on Win 7 almost for sure

    And that’s all about this very interesting day. See you next year ;)

    Share/Save/Bookmark