mscommunity.net

Interactive mscommunity.net online activities
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.
  • 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 svi 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 lip 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 lip 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 vlj 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 sij 20 2009, 02:17 by boris.sevo with 2 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 sij 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 sij 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 pro 11 2008, 04:05 by boris.sevo with 4 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 pro 11 2008, 11:51 by boris.sevo with 8 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 stu 19 2008, 12:46 by boris.sevo with no comments
    Filed under:
  • WPF trick #2 - Alternate background colors for ListView rows

    Prior the .NET Framework 3.5 SP1 was released, if you want to set alternate background colors for ListView rows you needed to write some kind Converter which returnes some kind of Brush. IF you have SP1 installed accomplishing the same functionality is rather trivial job. Here are the code snippets:

    (defining the style)

        <Style x:Key="CustomListViewItemStyle" TargetType="{x:Type ListViewItem}">
    <Style.Triggers>
    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
    <Setter Property="Background" Value="#2C2C2C"></Setter>
    </Trigger>
    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
    <Setter Property="Background" Value="#262626"></Setter>
    </Trigger>
    </Style.Triggers>
    </Style>

    (using the defined style)

        <ListView ItemContainerStyle="{DynamicResource CustomListViewItemStyle}"
    AlternationCount="2">
    ...
    </ListView>
    Posted lis 21 2008, 04:22 by boris.sevo with 5 comment(s)
    Filed under:
More Posts Next page »
Powered by Community Server (Commercial Edition), by Telligent Systems