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.
  • 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 no comments
    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 no comments
    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 no comments
    Filed under:
  • WPF trick #1 - Hyperlink control

    Today I needed to create a simple grid which will hold some text information about some products and a few Hyperlink controls which when clicked need to display detailed information about particular product. On my big surprise WPF doesn't have Hyperlink control. This is really weird, but the solution is very simple. All you need to do is to use System.Windows.Documents.Hyperlink in a combination with TextBlock control.

    XAML code for creating Hyperlink 'control' is then something like this:

        
        <TextBlock>
            <Hyperlink>
                <TextBlock Text="Some text">
            </Hyperlink>
        </TextBlock>
    
    Posted lis 21 2008, 10:13 by boris.sevo with no comments
    Filed under:
  • Silverlight 2 now available

    More info here.

  • Silverlight 2 RC0 offline documentation

     You can get RC0 offline documentation here.

  • Geppeto project or what some smart people on FER are doing when they are not teaching the students

    Last year Tomislav Bronzin allready wrote about Gadget-to-Gadget communication project which researchers at FER (Faculty of Electrical Engineering and Computing in Zagreb) were doing for Google. If you are curious in what Gadget-to-Gadget communication evolved, you can take look at this YouTube video and see how will one day some non-skilled end user be able to develop a new gadget for iGoogle platform.

  • ASP.NET AJAX - Why should you prefer web service method calls over page method calls?

    When you are developing some kind of Ajax powered web page and you need to transfer some data back and forth between the web browser and the web server, you have more then one way to do it. One way is to be lazy and do your job quickly using UpdatePanel. This is probably the easiest way, but it's certainly not the best way. There is many posts about performance problems related with UpadatePanel and here is just one of them. If you care about the performance you will transfer your data on some other way. ASP.NET AJAX offers two other ways to do it:

    • calling web service methods
    • calling page methods

    There is also many posts about both of them and some people are saying that you should prefer web services, some are saying that you should prefer page methods and some are saying that they are both the same. So, the questions is who has right? Well, in last few days I tested both of them and come to the conclusion that they are pretty much the same, but when performances are really important, you should definitely prefer web services. There are two reasons for that:

    1. You can execute web service methods asynchronously
    2. In page methods you can't disable session, in web services you can

    Page methods and web service methods are called asynchronously on the client, but on the server they are processed synchronously. This basically means that ASP.NET will pick one CLR thread for every incoming request and will not release it and return it to the CLR tread pool as long as request is processed. If request processing is fast you can live with it. But, if there are many concurrent requests and if requests processing involves relatively long waiting for external I/O operations to complete (for example database queries) you will soon run into problems because there will not be any free CLR threads to process other requests. If you have this kind of problem with the web forms you easily fix it using asynchronous pages. Here is a nice explanation how to do it. But, how can you make asynchronous web services and web methods? I don't know if you can do that with page methods, but in Omar's book you can read how you can do that with web services.

    Asynchronous request processing is the first reason to prefer web service methods calls over page method calls. But, there is also one more reason and it's related with the use of session. Using WebMethod attribute and its EnableSession property you can disable session on the web service method level. You can try to do the same with the page methods, but session will always be enabled and you will always be able to put some data in Session object or pull data from it. That means that session will be loaded on every request which will downgrade performances.

  • Silverlight on mobile phones

    After the "war" between Silverlight and Flash has started on desktop computers, it seems that we have a new battlefield. Yesterday Nokia announced that it will support Silverlight on some of its mobile devices. Does this mean that we can expect to see Silverlight on Android, iPhone and other smartphones? I really hope so.
     

  • Concurrent programming in C# - Parallel.Do method

    This is my first one but certainly not the last one post about the concurrent programming in C#. Free lunch is over
    is an excellent text which shows why concurrent programming matters. If you ever read anything about it, you
    have probably noticed that people talk about it as something hard and complicated. Is it really so hard and
    complicated? Well, in my opinion it depends. It depends about how much concurrent your program need to be,
    what kind of knowledge do you have about this programming model, which libraries are you using for threading etc.
    I have some knowledge about this topic, but it's very far from being profound. Because of that I'm happy that
    there are some smart people in Parallel Computing Developer Center who made an excellent extension
    for .NET - ParallelFX.

    There is a lot in it and there's a lot interesting topics to write about, but because this is my first post, I will start
    with something simple and still very powerful. I will write only about Do method. According to documentation,
    it's a method with following declaration:

    public static void Do(
    params Action[] actions
    )

    This method "executes each of the provided actions inside a discrete, asynchronous task". It doesn't
    finishes until each of provided actions has completed. That means, it will finish when the slowest action finishes. Imagine
    that you have two long running methods called foo and bar. If you call them in sequential manner you will need to
    wait until foo finishes its execution, then you will run bar method and wait until it finishes its execution. If you run
    them in parallel you will only need to wait as much as the longest of this two is executing. Let's see an example.

        class Program
    {
    private static double x = 1000000000;

    private static void foo()
    { for (double i = 0; i < x; i++) ;}

    private static void bar()
    { for (double i = 0; i < x; i++) ;}


    static void Main(string[] args)
    {
    Stopwatch watch = new Stopwatch();

    watch.Start();
    // *** sequential
    foo();
    bar();
    watch.Stop();

    Console.WriteLine("Not parallel: " +
    (watch.ElapsedMilliseconds / 1000.0).ToString() +
    "s");

    watch.Reset();
    watch.Start();
    // *** parallel
    Parallel.Do(() => foo(), () => bar());
    watch.Stop();

    Console.WriteLine("Parallel: " +
    (watch.ElapsedMilliseconds / 1000.0).ToString() +
    "s");
    }
    }

    The time which you get running the above program will depend about your computer CPU. On my computer
    (Core Duo, 2.33GHz) I get:
    Not parallel: 8,769s
    Parallel: 4,595s
    So, with a help of just one line of code we have a multithreaded program!

    That's all for the first time. It was just a little introduction. When I learn more about ParallelFX I will write again.

  • Inline text editing control in ASP.NET AJAX

    Inline text editingInline text editing is a technique which I really like. It can be used on various places, displaying updatable widget title or displaying updateable user status are just two of them. Still, it can be very confusing to the users if they aren't enough familiar with the application they are using. To make it more user friendly, I added few features (dynamic CSS changing, mouse cursor changing and tooltip) which purpose is to suggest the users that there is something more behind the plain text which is initially shown to them.
    Control is implemented as ScriptControl and all the logic behind it is made with JavaScript using ASP.NET AJAX framework (full source code and a test web page are provided at the end - you will need VS2008 to build it). It doesn't extend any ASP.NET controls ("TextBox" and "Label" are generated on the fly) and it allows you to get and store updated text on the persistent medium (database for example) using .asmx web services.
    In source code you can see how to:

    • build an ASP:NET AJAX control with embedded .js file
    • use ASP.NET AJAX DOM extensions
    • dynamically invoke web services to asynchronously communicate with the server
    • process various DOM events like keypress, mouseover, mouseout, click and blur

    To use this control you only need to add one line of code in your .aspx page.

    <inlEdit:InlineEditing ID="InlineEditing1" runat="server" TextId="100" 
    ServicePath="WebService.asmx" GetMethod="Load"
    SaveMethod="Save" CssClass="lblClass"
    LabelHoverCssClass="lblHoverClass"
    TextBoxCssClass="txtbxCssClass"/>

    This is just a first version. Potential improvements are:

    • add a button next to "TextBox" do the same what pressing enter key does
    • show progress indication when retrieving and updating text
    • add MaxLength property (handle pasting and various keys)
    • any other improvement

    Source code (tested in IE7, FF2.0.0.12 and Opera 9.26.)

  • Using enter in TextBox control to submit the form with multiple Button controls

    Hitting enter after you have typed something in some TextBox control is something natural to most users, but it
    makes life of the ASP.NET developer more difficult. If you don't know about what I'm talking here is a simple
    example. Imagine that you have a simple web form with two text fields and two button controls. The first text field
    and the first button are used for searching the web site and they are placed somewhere near the top of the page.
    The second text field and the second button are used for some totally different purpose and that's filtering the
    entries displayed on the form.
    The important thing to remember is that both buttons, when clicked, are causing postback and that first button is
    rendered before the second button. So, when enter is pressed inside the first text field, web site will be searched.
    So far so good. But let's suppose that user has typed something in the second text field. If enter is pressed while
    mouse cursor is inside the second text field, user will expect that the form entries will be filtered. But that isn't going
    to happen! The first button will do the submit and web site will be searched once again.

    Described behavior I found in IE7 and Opera. Firefox is immune to this problem. To understand why is this happening
    we need to look at the code. Here is the code of the simple web form which will demonstrate the problem:

        <head runat="server">
    ...
    <script language="javascript" type="text/javascript">
    function Submit(id, e) {
    var isEnter = window.event == null ?
    e.keyCode == 13 :
    window.event.keyCode == 13;
    if(isEnter)
    document.getElementById(id).click();
    }
    </script>
    <script runat="server">
    protected void btnSearch_Click(object sender, EventArgs e)
    { lit1.Text = "I'm searching"; }

    protected void filterBtn_Click(object sender, EventArgs e)
    { lit1.Text = "I'm filtering"; }
    </script>
    </head>


    <form id="form1" runat="server">
    <asp:Literal ID="lit1" runat="server"></asp:Literal>
    <br />
    <asp:TextBox ID="TextBox1" runat="server" onkeypress="Submit('btnSearch', event)" />
    <asp:Button ID="btnSearch" runat="server" onclick="btnSearch_Click" Text="Search" />
    <br />
    <asp:TextBox ID="TextBox2" runat="server" onkeypress="Submit('filterBtn', event)" />
    <asp:Button ID="filterBtn" runat="server" onclick="filterBtn_Click" Text="Filter" />
    </form>

    The interesting part isn't the web form source code then the generated html. Here it is only the important part:

        <input name="TextBox1" type="text" id="TextBox1" 
                  onkeypress="Submit('btnSearch', event)" />
    <input type="submit" name="btnSearch" value="Search" id="btnSearch" />
    <br />
    <input name="TextBox2" type="text" id="TextBox2" onkeypress="Submit('filterBtn', event)" />
    <input type="submit" name="filterBtn" value="Filter" id="filterBtn" />

    Both buttons are generated as submit buttons and that's what is causing the problems. When you press enter while you
    are typing inside the second text field (TextBox2) default button will do the submit. Default button, if explicitly not
    specified, will be the first rendered button (in this case this is the btnSearch). You can change the default button by
    setting the form's defaultbutton attribute to id of some other button, but this won't fix the problem. The solution is to say to
    ASP.NET that is shouldn't render buttons which type is submit. Instead it should render regular buttons. We can do that
    with the help of UseSubmitBehavior property. All we need to do is to set it to false. The markup will now look like this:

        ...
    <form id="form1" runat="server">
    ...
    <asp:TextBox ID="TextBox1" runat="server" onkeypress="Submit('btnSearch', event)" />
    <asp:Button ID="btnSearch" runat="server" onclick="btnSearch_Click"
    Text="Search" UseSubmitBehavior="false" />
    <br />
    <asp:TextBox ID="TextBox2" runat="server" onkeypress="Submit('filterBtn', event)" />
    <asp:Button ID="filterBtn" runat="server" onclick="filterBtn_Click"
    Text="Filter" UseSubmitBehavior="false" />
    </form>

    Generated HTML now looks like this:

        ...
    <input type="button" name="btnSearch" value="Search" id="btnSearch"
    onclick="java_script:__doPostBack('btnSearch','')"/>
    ...
    <input type="button" name="filterBtn" value="Filter" id="filterBtn"
    onclick="java_script:__doPostBack('filterBtn','')"/>

    That's it. When you press enter inside TextBox1 btnSearch will do the submit, and if you press enter inside the TextBox2
    btnSearch will do the submit.

    Posted vlj 13 2008, 08:52 by boris.sevo with 6 comment(s)
    Filed under:
  • Internal DSLs, fluent interfaces and extension methods in C#

    This is one of my longest blog posts and because of that I will start with a short list which describes what I will cover in this post:

    • internal DSLs
    • fluent interfaces
    • method chaining
    • extension methods

    Few weeks ago I found Neal Ford's session material about Building DSLs in Static and Dynamic Languages. This is a material from one No Fluff Just Stuff symposium - Great Lakes Software Symposium which is as far as I can see a really great conference with a tones of interesting sessions. (You can also found a lot of interesting materials at Neal's Conference Slides & Samples section.)

    Internal DSLs and Fluent Interfaces

    If you take a look at a NFJS web page you can see that they have a book called a NFJS anthology. Old copy (2006) of this book has a topic DSLs and Language-Oriented Programming by Neal Ford. In this topic Neal wrote:

    A domain-specific language is a limited form of computer language designed for a specific class of problems. ... Two types of DSLs exist: internal and external. An internal DSL is a internal domain-specific language written "on top" of the underlying syntax of your base language. If Java is your base language, then an internal DSL written in Java uses Java syntax to define the language.

    (more info about DSLs: Martin Fowler's DSLReadings)

    External DSLs were clear to me before, because sometimes when you are faced with a problem from a specific domain, building a whole new language can really help you to express this problem. If you are building an external DSL you are building a language with a syntax which is diffrent then your base language syntax. Hence, you need to build a lexer and parser for your external DSL.
    But, the purpose of internal DSLs wasn't so clear to me. I was asking myself why on hell would I like to build another language "on top" of my base language? Well, the answer lies in something which is called fluent interface (Martin Fowler's original bliki entry coining the term). The term fluent interface and internal DSL are in many ways synonyms. The whole concept can be reduced to a single sentence from a Martin Fowler's text:

    The API is primarily designed to be readable and to flow.

    So when you are designing an API to be fluent you are building a code which intent is to look like a well-formed sentences. The best way to describe this is probably by example. Imagaine that you have a following two classes:

        public class Appointment
    {
    private string _name;
    private DateTime _startTime;
    private DateTime _endTime;

    public string Name
    {
    get { return this._name; }
    set { this._name = value; }
    }

    public DateTime StartTime
    {
    get { return this._startTime; }
    set { this._startTime = value; }
    }

    public DateTime EndTime
    {
    get { return this._endTime; }
    set { this._endTime = value; }
    }
    }

    public class AppointmentCalender
    {
    private List<Appointment> _apponitments;

    public AppointmentCalender()
    { _apponitments = new List<Appointment>(); }

    public void Add(Appointment app)
    { _apponitments.Add(app); }

    public string Print()
    { ... }
    }

    If we want to remember that we have a dentist in 5 days from 4PM to 6PM in non-fluent way we will probably do something like this:

    	//"dentist" in 5 days from 4PM to 6PM
    AppointmentCalender appCalender =
    new AppointmentCalender();

    Appointment app1 = new Appointment();
    DateTime dt1 = new DateTime(DateTime.Now.Year,
    DateTime.Now.Month,
    DateTime.Now.Day + 5,
    16, 0, 0);
    app1.Name = "dentist";
    app1.StartTime = dt1;
    app1.EndTime = dt1.AddHours(2);
    appCalender.Add(app1);

    Or if you think that this setters are requiring to much work you can write appropriate constructor and then you have something like this:

    	DateTime dt1 = new DateTime(DateTime.Now.Year,
    DateTime.Now.Month,
    DateTime.Now.Day + 5,
    16, 0, 0);
    appCalender.Add(new Appointment("dentist", dt1, dt1.AddHours(2)));

    Although the second example is conciser then the first one, initialization of dentist's start termine is still extremely ugly. The constructor saved us from some work but without a deeper look at constructor's implementation it's hard to say what is the meaning and purpose of all its parameters. In first example we didn't have this problem because from setter's names (Name, StartTime and EndTime) it was clear what exactly the code is doing. From above two examples we can see that we have two candidates which need to be more fluent. First we will make initialization of the DataTime object more fluent and then we will do the same with the initialization of the Appointment object.

    How to make your API more fluent?

    Before C# 3.0 was introduced if you want to make your API more fluent you were limited to the method chaining. In method chaining you are making the modifier methods return the host object so that multiple modifiers can be invoked in a single expression. Although, this is something which can help you a lot while building the fluent interface, it is also bringing one bad habit in your API about which you can read more in the next section. In C# 3.0 there is a new concept called extension methods. There is many info about extension methods on a web and if you don't know what they are you can find more info about them on Scott Guthrie's blog post New "Orcas" Language Feature: Extension Methods. Here I will just give a short definition from this Scott Guthrie's post:

    Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

    For us, extension methods are specially usefull because they can help us make DataTime more fluent. We can accomplish this by extending DateTime CLR type with few methods. Here is the code which is doing exactly that:

        public static class DataTimeExtMethods
    {
    public static TimeSpan days(this int number)
    {
    return new TimeSpan(number, 0, 0, 0);
    }

    public static DateTime fromToday(this TimeSpan ts)
    {
    DateTime dt = new DateTime(DateTime.Now.Year,
    DateTime.Now.Month,
    DateTime.Now.Day);
    return dt.Add(ts);
    }

    public static DateTime at(this DateTime dt, int hour)
    {
    return new DateTime(dt.Year, dt.Month, dt.Day, hour, 0, 0);
    }

    public static int pm(this int hour)
    {
    if (hour > 0 && hour < 13)
    return hour + 12;
    else
    throw new ArgumentException("Wrong hour value");
    }
    }

    Now we can write something like this:

    	DateTime dt = 5.days().fromToday().at(4.pm());

    Writing 5.days().fromToday() before extension methods were introduced, were impossible because there was no way to extend a value type like integer. This kind of syntax is something natural to dynamic-typed languages so in Groovy it is possible to write 5.days.fromoday.at(4.pm). Because the use of extension methods isn't limited to value types only, we can also extend Appointment class with them. Nevertheless let's see how we can make Appointement class more fluent with a help of method chaining.

        public class Appointment
    {
    ...

    public Appointment Having(string name)
    {
    this.Name = name;
    return this;
    }

    public Appointment From(DateTime date)
    {
    this.StartTime = date;
    return this;
    }

    public Appointment To(DateTime date)
    {
    this.EndTime = date;
    return this;
    }

    public Appointment At(DateTime date)
    {
    this.StartTime = this.EndTime = date;
    return this;
    }
    }

    Now if we have a dentist in 5 days from 4PM to 6PM and birthday party in 17 days we can write:

    	AppointmentCalender appCalender = new AppointmentCalender();

    //fluent way
    DateTime dt = 5.days().fromToday().at(4.pm());
    appCalender.Add(new Appointment().Having("dentist").
    From(dt).
    To(dt.AddHours(2)));

    appCalender.Add(new Appointment().Having("birthday party").
    At(17.days().fromToday()));

    Pros and cons

    As we can see from above examples fluent interfaces can make your code more human readable. The price of this readability is more effort in API construction. The simple ("primitive") API of constructors, setters and additional methods is easier to write but harder to read. Better readability isn't worth the effort in all cases. In my opinion there are two places were better readability is worth the effort in time and thinking and that are library and framework construction.

    Effort in time and thinking isn't the only negative side in building fluent APIs. In method chaining we are using modifier methods which are returning the object which they modify although the common convention is that modifier methods are void (Command query separation). The use of extension methods is also bringing some potential problems. To ensure that you can't hijack or subvert the intended behavior of existing methods CLR will always prefer an instance method over an extension method. Although this is a good thing it also causes one problem known as versioning problem.

More Posts Next page »
Powered by Community Server (Commercial Edition), by Telligent Systems