Community Blogs

Blogs of different SQL/Developers Community Members
Signed in as anonymous | Edit Profile | Sign out | Help
in Search

Weblog :: Boris Ševo

Sporadic posts about my interests, e.g. software development (mostly .NET), technology in general and some occasional rant.
  • Fix for the bug in ComboBox and ListBox WPF JetPack theme

    On Tim Heuer's blog you can find great Silverlight 4 JetPack theme. Thanks to Jonathan Antoine, JetPack is ported to WPF. Using JetPack theme in one of mine projects I found a tiny but very annoying bug, while I was trying to bind ComboBox and ListBox to collection of objects. The same bug is actually an old bug which could be found in some WPF Themes (Whistler Blue is one example).

    If you run the WPF JetPack theme sample code from Jonathan Antoine's blog you probably wouldn't notice this bug, because sample code binds ComboBox and ListBox to list of String objects. Bug can be reproduced only when those controls are binded to collection of objects which aren't strings.
    If you bind ComboBox and ListBox to collection of Dummy objects which have SomeText property and if you set ComboBox's DisplayMemberPath property to SomeText this is what you will get:

    screenshot-of-the-reproduced-bug 

    There are 2 solutions for this problem:

    1. override ToString method in binded object and let the ToString method return value of the property used in DisplayMemberPath
    2. modify theme's XAML code

    First solution is easy but it isn't practical in all cases (what if you need to override object's ToString method in some other way for some other purposes).
    Modifying theme's XAML code is actually very easy because all we have to do is replace lines 1840-1843 in Assets/CoreStyles.xaml:

    <ContentPresenter x:Name="contentPresenter" Content="{TemplateBinding Content}"
        ContentTemplate="{TemplateBinding ContentTemplate}"
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        Margin="{TemplateBinding Padding}" />

    with:

    <ContentPresenter x:Name="contentPresenter"
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
        Margin="{TemplateBinding Padding}" />

    That's it. ComboBox will now bind and work as expected.
    ListBox I couldn't fix the same way - modifying the theme's XAML code. For the ListBox there is even simpler solution and that is to change the way you bind Dummy objects to ListBox. If you take a look at MainWindow.xaml sample code found at Jonathan Antoine's blog you will see that at line 67, ListBox is binded this way:

    <ListBox ItemsSource="{Binding ListOfItems}" Height="135.48" /> 

    ListOfItems is collection of Dummy objects and to bind them correctly and display values of the SomeText properties you need to use the following XAML code:

    <ListBox ItemsSource="{Binding ListOfItems}" Height="135.48" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding SomeText}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    

    Note that you couldn't fix the ComboBox the same way the ListBox is fixed. If you change CombBox's binding the same way I did for ListBox, Combox's items will display correctly but if you set SelectedIndex property to 0 you will see that binding doesn't work. The same will happen if you use SelectedItem instead of SelectedIndex.
    That's it, I hope this will save someone few minutes of work.

    Posted Okt 21 2010, 08:28 by boris.sevo with 2 comment(s)
    Filed under: ,
  • Using templates in applications which follows MVC pattern

    Disclaimer: only purpose of this post is to continue hot Twitter conversation about using expressions which computes something in MVC views. I don't want to say that templates are the bad thing, nor that Tomislav Capan's presentation about Spark View Engine was bad ;).

    Intro: Today at Croatian WebUG, Tomislav Capan had presentation about Spark View Engine for ASP.NET. Overall speaking, presentation was ok and I learned something new, but there is one thing which bothers me in the whole idea of using templates which allows all kind of operations in applications which follows MVC pattern. Here is one example of the View written using the Spark template's syntax:

    <s:for each="var p in Products">
         <p class="${p.Price > 100 ? "highPrice" : "lowPrice"}">${p.Description}</p>
    </s:for>

    What's the problem with the above code?

    Generally speaking nothing (maybe it has some syntax error, but that doesn't matter in the current context). If you need to write something fast and all you want is working code now, then the code is ok. But, if you are determine to follow MVC way of writing applications with clear separation of concerns and you want to make your code easily maintainable and testable (I'm talking about unit tests) then, you are doing it wrong.

    Imagine that, after you have wrote above code, your currency significantly lose on its value. Now, the new business rule is that high price is 500. You need to change your View and change the expression p.Price > 100 to p.Price > 500. Obviously you wrote your View in a wrong way. When the business rule has changed you need to change your View instead of Controller.

    The better way to accomplish the same thing is to write something like:

    <s:for each="var p in Products">
         <p class="${p.PriceImportance}">${p.Description}</p>
    </s:for>

    where PriceImportance is some property or method in Products class which returns strings highPrice or lowPrice based on evaluation of the Price > 100 expression. Expression is written somewhere in some Controller.

    You can now say that I put presentation logic outside of the View. But I didn't. Only View knows what to do with the highPrice and lowPrice values and how those values are represented. Controller even doesn't know what the highPrice and lowPrice are. It doesn't know how their representation.

    View is responsible to represent highPrice. It can represent it with the red color or with the yellow color. If the business rule changes and we have highPrice, mediumPrice and lowPrice where they are represented with yellow, blue and green colors respectively you need to change your highPrice CSS class from background-color: Red; to background-color: Yellow; and everything will work. The important thing is, that this change is done in the View. The business part of the change, the fact that we don't only have high and low price is done in a Controller where expression is changed to Price > 200 ? highPrice : (Price > 150 ? mediumPrice : lowPrice).

    If some other View need to use the same Controller, it can freely represent highPrice as <b>highPrice!</b>!

    At the end, here are my answers on some questions which occured during Twitter conversations about the same topic:

    1. Does Controller depends on View? - in the second solution it doesn't. If you change your view from HTML View where highPrice is name of some CSS class to Silverlight View where hightPrice is key of some XAML style, everything will still work
    2. Can you unit test your business logic? - yes you can in the second solution. In the first solution? I don't think so.
    3. Does Controller knows anything about the presentation? - no it doesn't. View will represent highPrice if it thinks that it need to be represented and it will represent it as HTML, XAML, ...
    4. Why can't Controller just return value (100) and let View represent the value with the help of JavaScript? - because then you just shifted business logic from backend language to JavaScript and you have your business logic in two places -> two places for doing unit testing
    Posted Mai 20 2010, 11:25 by boris.sevo with 2 comment(s)
    Filed under: ,
  • Checking ISO7064 MOD 11,10 or OIB validity

    As you can see here a check digit according to check digit procedure ISO7064 MOD 11,10 has to be attached to blood bag numbers prior to delivery as haemotherapeutic drug. In Croatia the same check digit is used as a personal identification number (also known as OIB). Some hybrid systems based on the same standard are also used in banks and probably on many other places for various purposes.

    There is nothing special in this algorithm, but today I found a blog post by Domagoj Pavlešić where he has provided OIB check validity algorithm written is several programming languages (he even wrote a web service which can be used for free). Although there is nothing wrong with his algorithms, I decided to write my own version of the algorithm because I didn't like his C# version (it's is too long) and because F# version was missing (I love F#) :)

    First the C# version which is shorter because Enumerable.Aggregate method is used instead of for loop:

    private static bool CheckOib(string oib)
    {
    if (oib.Length != 11) return false;

    long oibL;
    int[] digits;
    if (long.TryParse(oib, out oibL))
    digits = Array.ConvertAll(oib.ToCharArray(), c => Int32.Parse(c.ToString()));
    else return false;

    return digits[10] ==
    11 - digits.Take(10)
    .Aggregate(10, (x1, x2) => ((x1 + x2) % 10 == 0 ? 10 : (x1 + x2) % 10) * 2 % 11);
    }

    And then the F# version:

    open System

    let modulo10 x1 x2 = if (x1 + x2) % 10 = 0 then 10 else (x1 + x2) % 10
    let digits s = s |> Seq.map(string >> int) |> Seq.to_list |> List.rev
    let CheckOib (x:String) =
    if x.Length <> 11 then false
    else
    let succ, value = Int64.TryParse(x)
    if succ then
    let l = digits x
    l.Head = 11 - (l.Tail |> List.fold(fun x1 x2 -> (modulo10 x1 x2) * 2 % 11) 10)
    else
    false

    Console.WriteLine(CheckOib "your_oib")


  • Asynchronous programming in F# - Simple FriendFeed client

    The asynchronous programming in .NET is supported through a use of BeginXXX and EndXXX methods. Operations are started by calling the BeginXXX which begins the operation and then returns. The programmer must also call the EndXXX method to be notified that the asynchronous operation has ended. Nevertheless, most programmers prefer to use synchronous over asynchronous programming. In my opinion there are two reasons for that. First is that there are many .NET classes which only have support for synchronous programming and the second is that synchronous programming is generally speaking simpler then asynchronous programming. The catch is in a fact that simpler isn't always the better, because in many case the asynchronous programming model can produce more responsive and more scalable applications.

    There is an interesting MSDN article by Jeffery Richter about implementing the CLR asynchronous programming model, but if you take a look at the code you will see that it's pretty complicated and hardly understandable on the first look. Luckily Microsoft has provided us with F# programming language which has some cool and powerful features. One of them are asynchronous expressions. To demonstrate how they are used, I wrote a simple FriendFeed client for fetching and displaying user's home feed.

    [<AutoOpen>]
    module WebRequestExtensions =
    type System.Net.WebRequest with
    member x.AsyncGetRetResponse() = Async.BuildPrimitive(x.BeginGetResponse, x.EndGetResponse)

    let (!!) : string -> XName = XName.op_Implicit

    type FriendFeedStatus = { Title : string; User : string; Service : string }

    let printTimeline nickName password (url:string) =
    async { let request = WebRequest.Create url :?> HttpWebRequest
    do request.Credentials <- new NetworkCredential(nickName, password)
    use! reqResponse = request.AsyncGetRetResponse()
    use streamReader = new StreamReader(reqResponse.GetResponseStream())
    let! xml = streamReader.AsyncReadToEnd()
    let xmlDocument = XDocument.Parse xml
    let entries = xmlDocument.Root.Elements(!! "entry")

    for entry in entries do
    Console.WriteLine("{0} via {1}: {2}",
    entry.Element(!! "user").Element(!! "nickname").Value,
    entry.Element(!! "service").Element(!! "id").Value,
    entry.Element(!! "title").Value)}

     
    We can see that the code is concise and quickly understandable if we are familiar with the basic F# concepts. We can call the defined function with the following code snippet:

    Async.Start (printTimeline "your_nickname" 
    "your_remotekey"
    "http://friendfeed.com/api/feed/home?format=xml")

    which will start the asynchronous computation in the thread pool and will not wait its result. Beside the asynchronous expressions it's used one more interesting feature. That's the LINQ to XML and Matthew Podwysocki's "!!" operator which he calls "Convert Dammit" operator. This operator is used to implicitly convert a string to a XName (note that there is no need to write this operator in C#).

    Posted Jun 13 2009, 09:21 by boris.sevo with 2 comment(s)
    Filed under:
  • Differences between WPF and Silverlight

    Wintellect published 69 page whitepaper about programmatic differences between Silverlight and WPF.

    I scanned it quickly and I didn't quite read it in details, but it definitely looks like a material worth studying if you are developing WPF and/or Silverlight applications. As a special bonus, at the whitepaper's end, there is a topic about code reuse strategies which looks really interesting knowing that Silverlight is generally considered to be a subset of WPF and that Microsoft is committed to bringing Silverlight and WPF closer together with the each release.

  • Page Speed - Firefox/Firebig add-on for evaluating web pages performance

    Google has realesed new Firefox/Firebug add-on called Page Speed for evaluating web pages performance and to get suggestions on how to improve them. Several tests, based on a web performance best practices, are performed on a front-end code and on a server's configuration.

    page-speed-screenshot

    It's an interesting add-on which combined with YSlow can really help developers in developing optimized, fast loading web pages.

     

    Posted Jun 05 2009, 10:28 by boris.sevo with no comments
    Filed under:
  • NHibernate.LazyInitializationException - failed to lazily initialize a collection, no session or session was closed

    While I was working on some project my goal was to separate all presentation logic from my database access logic and NHibernate API calls so I created facade for creating and disposing NHibernate sessions and querying the database. Everything works fine until I didn't need to display collection of objects in some ListBox control. Suddenly NHibernate's LazyInitializationExceptions started to pop up because my NHibernate session was closed and collection's objects weren't initialized. Because lazy loading is default way of loading collections in NHibernate (which perfectly makes sense because you shouldn't load entities which you don't need) you have 2 ways to prevent above exception's messages to pop up:

    1. prevent lazy loading in your mapping
    2. force NHibernate to initialize collection

    How can you prevent lazy loading in your mapping depends on the way your mapping is realized. I was using Fluent NHibernate so I did something similar to following code snippet:

    public class WorkListMap : ClassMap
    {
    public WorkListMap()
    {
    ...
    HasMany(x => x.Services).Inverse().Not.LazyLoad();
    }
    }

    If you wan't to force NHibernate to initialize collection you can call NHibernateUtil.Initialize method.

    That's all. I hope this can save you few minutes if you ran into the same problem as I was.

  • WPF trick #4 - Binding and Validation

    Validation can also happen while binding is made. This is very useful if the bound objects have built in logic. For example if you have a Product object which has Price property which must be some number bigger the zero you will probably have code similar to this one:

    class Product
    {
        private decimal _price;

        public decimal Price
        {
            get { return _price; }
            set
            {
                if (value <= 0)
                    throw new Exception("Exception from Price setter");
                _price = value;
            }
    }

    If you need to mark invalid input inside some TextBox you can then write something like this:

        <Window.Resources>
    <code:Product x:Key="dsProduct"/>
    </Window.Resources>
    <StackPanel>
    <WrapPanel>
    <TextBox Width="200" Text="{Binding
    Source={StaticResource dsProduct},
    Path=Price,
    UpdateSourceTrigger=PropertyChanged,
    ValidatesOnDataErrors=True,
    ValidatesOnExceptions=True}">
    </TextBox>
    </WrapPanel>
    </StackPanel>
    Posted Feb 05 2009, 10:35 by boris.sevo with no comments
    Filed under:
  • WPF trick #3 - MultiBinding and StringFormat

    One of the new features in .NET Framework 3.5 SP1 is StringFormat support within {{Binding}} expressions to enable easy formatting to bound values.
    So, if some TextBlock control need to be bound to some object's properties (let's call them Max and Min) and the value of the TextBlock's Text property need to be in [Min - Max] format you can then write something like this:

        <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="[{0} - {1}]">
                <Binding Path="Min"></Binding>
                    <Binding Path="Max"></Binding>
                </MultiBinding>
            </TextBlock.Text>
         </TextBlock>
    Posted Jan 20 2009, 02:17 by boris.sevo with 4 comment(s)
    Filed under:
  • jQuery 1.3 released

    New version of jQuery is released today! It includes new (and faster!) selector engine, new way for binding events, new way for browser detection (or should I say feature detection?) and much more.
    Read more about it here.

    (Google is allready hosting it at http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js)

    Posted Jan 14 2009, 09:36 by boris.sevo with no comments
    Filed under:
  • Multiple versions of Firefox on the same computer

    Every good web developer has two responsibilities: check the web application's behavior in multiple browsers and submit found browser's bugs and incompatibilities to the browser's vendor. Having so much browser versions even from a single browser vendor complicates developer's life. Luckily there is a simple way to test your web application in various Firefox versions. If you already have some Firefox version installed on your computer all you have to do is to download a new Firefox version (the newest version from trunk can be found here) extract it in some folder and run it using ProfileManager option (after you have closed all Firefox instances go to command prompt and do something like this: D:\firefoxes\3.2a1pre>firefox.exe -ProfileManager).

    Posted Jan 10 2009, 01:17 by boris.sevo with 1 comment(s)
    Filed under:
  • Anchor is not clickable in Firefox and Safari when it's inside of the div tag which has image as background

    That's one of mine older issues which I was facing few months ago and today, while I was browsing through my pending blog posts, I decided to post few words about it hoping that it will save you few minutes of work if you ran into the same problem as I was.

    So, let's imagine that you want to put some link (anchor tag) inside a div tag which has some image as a background and that your link need to positioned somewhere inside of the image (div's background). Your HTML code will then be something like this:

    <div class="divsCSSClass">
        <a href="Default.aspx" style="left: 133px; position:relative; top: 7px;">
    some_text
    </a>
    </div>

    and your CSS will then be something like this:

    .divsCSSClass {
         background: url('image_name.png');
         width:392px;
         height:45px;
    }

    Above code will work in IE and Opera, but in Firefox and Safari link (anchor) will not be clickable. The solution is extremely simple. All you need to do is to add position:relative; to div's CSS class. CSS will then be something like this:

     .divsCSSClass {
         background: url('image_name.png');
         width:392px;
         height:45px;
         position: relative;
    }
    Posted Dez 11 2008, 04:05 by boris.sevo with 7 comment(s)
    Filed under: ,
  • Using jQuery to prevent form submit when enter is pressed

    I was recently working on a ASP.NET RIA which has a web form with the input field in which users can type some search term and press the search button or hit enter key. Search is invoked by an asynchronous call and done on the server. The text field is placed inside of form tag and because of that, when someone hits the enter key, instead of the desired behavior (asynchronous call), the whole form is submitted to the server. There is more then one possible solution for this kind of problem, but because I was already using jQuery for building the whole application's UI, I fixed the problem with the following elegant jQuery's cross-browser code snippet:

         $(document).ready(function() {
             $("form").bind("keypress", function(e) {
                 if (e.keyCode == 13) {
                    
    search($("#searchTerm").attr('value'));
                     return false;
                }
             });

         });
    Posted Dez 11 2008, 11:51 by boris.sevo with 12 comment(s)
    Filed under:
  • Testing tool for multithreaded applications from Microsoft Research

    Microsoft Research has released CHESS, an automated tool for finding errors like data-races, deadlocks, and hangs in multithreaded applications by systematically exploring thread schedules (it has even discovered bug in PLINQ). Once error is located, CHESS provides a fully repeatable execution of the program leading to the error. Win32 version can be downloaded here (at this time license is only for academic use) and commercial version will hopefully be available soon.

  • Hotfix for WPF designer

    If you are working with WPF you should consider downloading the hotfix which can be found here. If you have Silverlight Tools for VS 2008 SP1 you shouldn't install this hotfix because it already includes it.

    Posted Nov 19 2008, 12:46 by boris.sevo with no comments
    Filed under:
More Posts Next page »
Powered by Community Server (Commercial Edition), by Telligent Systems