LA.NET [EN]

UncategorizedArchive

May 15

HTC has done it again

Posted in Uncategorized       Comments Off on HTC has done it again

For some time now, I”ve been a proud owner of an HTC touch and I”m really happy with it. Anyway, I”ve just noticed that they”ve just released a new model: HTC Touch Diamond. It looks just great! Well, I guess that now I can say that I regret having bought an HTC touch…

Apr 16

[Update: Thanks to Mike for uncovering a bug on the sample. It should be IDummy.Increment and not Dumy.Increment. Thanks Mike and now I think it should compile without any problems.]

In these last days I”ve been reading the C# spec and you can say that I”ve been re-discovering it :,,) If you really think about it, I think that it”s fair to say that most people will only use the basic features of the language. And since many things work as they should (ie, they work in a logical manner), most of us don”t take the necessary time to study the spec.

Let me show you a little example that will help me make a point about this:) Look at the following example and tell me what happens (this example is based on an existing example that is shown on the C# spec):

using System;

namespace CSharpGotchas
{
    public interface IDummy
    {
        void Increment();
    }

    public struct IDummy : IDummy
    {
        public Int32 Counter; 
        void IDummy.Increment()
        {
            Counter++;
            Console.WriteLine(Counter);
        } 
    }

    public class GenericDummy<T> where T : IDummy, new()
    {
        public void Increment()
        {
            var aux = new T();
            aux.Increment();
            aux.Increment();
            aux.Increment();
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var aux = new GenericDummy<Dummy>();
            aux.Increment();
        }
    }
}

I”ve showed this example to several guys I know (I think that most of them had at least 1 year experience in C# programming) and only I knew the correct answer.

btw, if you”ve been using C# and .NET for some time, haven”t read the spec and don”t see anything that might make you think twice before answering, then you should be worried 🙂

Ok, the problem here is what should be printed on the console. Should we get 1, 1, 1 or should we get 1, 2, 3? if Dummy was a class, there really wouldn”t be any problems with the code since you would always be working with a reference element. But since Dummy is a struct, will we have boxing when calling Increment? (Do notice that I”ve implemented the IDummy interface explicitly, making it accessible only through an interface reference).

If you”re thinking that the previous code will print 1, 2, 3, you”re right! Why? well, because the spec explictly says that there are certain cases where it won”t box a struct. One of those cases happens when a struct overrides a method inherited from the System.Object class. Invocation of that method will be made directly over that instance of the struct (ie, you won”t be getting a boxed instance over which the method call is made).

Another place where you don”t get implicit boxing is when you acess a member or variable of a constrained type parameter (that is the case shown on the previous example). On the other hand, if you box the element by casting it to the interface, you”ll always get 1. Here”s an example that shows this:

public class GenericDummy<T> where T : IDummy, new()
{
        public void Increment()
        {
            var aux = new T();
            ((IDummy)aux).Increment();
            ((IDummy)aux).Increment();
            ((IDummy)aux).Increment();
        }
}

btw, I”m curious: did you know this?

Jan 29

The blog is (moving) reopening :,,)

Posted in Uncategorized       Comments Off on The blog is (moving) reopening :,,)

to the weblogs.asp.net site. Since most of the content I write is web related, I think it makes sense to start writing my posts over there. I”m not going to close this blog since I”m not migrating my old posts.

If you want to keep following my blog and you”re consuming my feedburner feed, then you don”t need to do anything since I”ve already updated the feed to point to that blog. If you prefer to check the online version of the site, then you can check it here.

I couldn”t end this post without thanking the guys at msmvps.com for hosting my blog and keeping everything working out smoothly on these last years.

Since things didn”t really go well with my move to the weblogs.asp.net site I”m reopening this blog. Until the end of the day I”ll port my entries on the weblogs.asp.net site to this site (so I”m sorry if this will duplicate the posts on your RSS reader). If you”re already consuming my feed from feedburner, you won”t need to do anything.

Jan 03

Making the DataPager generate a block element

Posted in Uncategorized       Comments Off on Making the DataPager generate a block element

I do really like the new paging model introduced with the new ASP.NET 3.5 version. However, there is one thing I don”t like: the fact that the DataPager control will always generate an inline element (in this case, a SPAN). So, how can we change this default behavior? Well, I see at least 2 options:

  1. create a new derived control and override the TagKey property. From a conceptual view, I believe this is what should be done
  2. DataPager is a Control, so why not re-use our knowledge on how the parser performs its work and just drop a style attribute that sets its display mode to block (which will be automatically copied to the HTML tag that gets inserted in the page)

As I”ve said before, in real code I”d probably go with 1 since it feels more natural and I really don”t like adding style attributes to my HTML. On the other hand, it”s just too damn difficult to resist to something like this:

<asp:DataPager runat=”server” ID=”myPager”   
    style=”clear: both”         
    PageSize=”4″
    PagedControlID=”myList”>
    <Fields>           
        <asp:NumericPagerField ButtonCount=”5″                       
                ButtonType=”Link”
                RenderNonBreakingSpacesBetweenControls=”true” />                     
    </Fields>
</asp:DataPager>

Jan 02

I”ll just start by wishing you all a great 2008!

Now, to what used to be a somewhat philosophical question: should you use this to reference a member of your class in your code? Ex: should you write this.CallInstanceMethod() ? Ok, in pre-C# 3.0, I”d say NO. With the current release, I”m saying maybe! Why? Simple: extensions methods. To call them, you must always pass a reference to the type, which means that if you”re calling an extension method from a class method (which is a scenario that should be very rare, but which is supported!) you must use the this qualifier or you”ll get a compiler error.

Dec 14

IDLogin control: why I''m not using it

Posted in Uncategorized       Comments Off on IDLogin control: why I''m not using it

As you may know, MS has released the Windows Live SDK some time ago. In a recent project, I was asked to use the Windows Live ID authentication on a web application. Well, using it turned out to be really easy, so I”m not going to bore you with the details. A few days after I was asked to use the new Windows Live controls that were supposed to simplify this operation (which, btw, are part of the Windows Live Tools for Microsoft Visual Studio). Unfortunately, the IDLogin control suffers from several limitations. First, the control forces me to use ASP.NET AJAX, which was not a requirement for this project. This is completely wrong since I will not add ASP.NET AJAX to my application just for using the IDLogin control.

Second, even if it lets me set the style properties which can be passed on the url that is assigned to the iframe that is generated automatically by the control, it won”t let me set all the possible attributes for an iframe element. For instance,in my case I needed to use a transparent iframe,which means that I need to set the allowtransparency attribute to true. Since the control doesn”t expose any property which would let me set this attribute nor does it use an iframe as its top tag, there really isn”t any way for me to set this attribute. So, I guess that using the good old iframe in HTML is still the best way to achieve proper integration of the Live ID on an ASP.NET web page…

Nov 22

Making the AuthenticationService.get_isLoggedIn() work correctly

Posted in Uncategorized       Comments Off on Making the AuthenticationService.get_isLoggedIn() work correctly

[Update: this will only happen if you don”t set up the web.config properly. You don”t need to do this – ie, call the RegisterStartupScript – if you add the <authenticationService enabled=”true” /> to the web.config file]

The ASP.NET AJAX platform has some client services which you can use from your client Javascript code to perform some interesting operations. One of those classes is the Sys.Services._AuthenticationService class. Most guys will use the class to authenticate a user without having to perform a postback (ie, they”ll simply call the login method over the “global” Sys.Services. AuthenticationService object that is inserted on the page).

The class has a method (get_isLoggedIn) which should be used for letting you know if the user is authenticated. Unfortunately, the method might not give you the correct answer in all the scenarios because it simply checks the value of the _authenticated field to return a response. Now, If you use the service to login, then everything will work out correctly if you don”t navigate to another page. If you do, things won”t work as expected because the field isn”t updated during page navigation. Here”s a small page that reproduces this:

page A:

System.Web.Security.FormsAuthentication.SetAuthCookie(“luis”, true);
Response.Redirect(“Default.aspx” );

The page creates the authentication cookie and performs a response.redirect. If you put the following code on the default.aspx page:

alert( Sys.Services.AuthenticationService.get_isLoggedIn() );
alert(“<%= this.User.Identity.IsAuthenticated.ToString() %>”) 

You”ll get “false, True”. What we need to do is to ensure that the _authenticated field is correctly filled during page navigation. Fortunately, we can do that rather easily by injecting a script from the server side, with code that looks like this:

protected override void OnLoad(EventArgs e)
{
     base.OnLoad(e);
     ScriptManager.RegisterStartupScript( this, this.GetType(),”authenticated”,
          String.Format(“Sys.Services.AuthenticationService._authenticated={0};”,
                                      this.User.Identity.IsAuthenticated ? “true” : “false” ),
          true );
}

If your page has UpdatePanels, then don”t forget that these rules still apply!

Nov 12

Click to activate gone from IE

Posted in Uncategorized       Comments Off on Click to activate gone from IE

Hurray! Pete has just announced (like in “a few days ago”:) ,,)this on his blog. Good news for the SL ASP.NET controls I”ve kept badmouthing in previous posts…

Nov 05

The var keyword

Posted in Uncategorized       Comments Off on The var keyword

In these last days, I”ve been looking at LINQ. I”m still not sure if this will help me build applications easily or if the new features introduced on the C# language are making it a lot more complex than it should be (when I make up my mind, I”ll let you know :),,). Anyway, LINQ brings us some cool things and that”s why I”m taking a look at it. before delving into LINQ, we should understand the new features of the C# language that support it. Today I”m going to write about the var keyword (there are already several posts on this, so I”m only writing this to use as a future reference).

Basically, the var keyword was introduced to let you declare a variable without defining its type explicitly. The C# 3.0 specification states that this type of declaration is known as implicitly typed local variables. Lets take a look at a quick example:

var myInt = 10;
Console.WriteLine(myInt.GetType().FullName);

If you run the previous sample, you should see System.Int32. So, what”s happening here? Well, when you build your app, the C# compiler will infer the type of the variable from the initialization expression you”re written. It”s really important to keep this in mind: the type of the variable depends on how the initialization expression is parsed by the compiler. Here”s another example:

var myInt = 10.4;
Console.WriteLine(myInt.GetType().FullName);

What do you expect to see when you run this program? will you get a Single (float) or a Double (double)? You”ll get a double because that”s what the literal 10.4 is. If you want to get a single you need to use the f prefix (var myInt = 10.4f;).

From these examples you can already deduce that you cannot use the var keyword without an initialization expression (if you do that, how will the compiler infer the type of the variable?). Other things to keep in mind are (taken from the C# specs):

  • the initializer must be an expression and cannot be an object or collection initializer;
  • cannot use the null value;
  • if the initialization expression contains multiple declarators, they must all be of the same type.

Lets look at same examples:

var myInt = null;

This won”t compile because the compiler cannot infer the type of a variable from null.

var myIntArray = {1, 2,3 };

This goes against point 1 of the previous list. you need to indicate the type of array like this:

var myIntArray = new Int32[] {1, 2,3 };

Not really that complicated, right?

A couple more of observations:

  • I”ve been saying that var is keyword, but it”s nor really a keyword in the traditional sense (when you think about keywords, you normally think about terms with predefined meaning that cannot be reused in a program – for instance, you can not create a variable named class). You can, for instance, introduce a new class called var . If you do that, when you write var myVariable you”re really creating a new variable of type var  (not an implicitly typed local variable);
  • you can use var in foreach cicles and using instructions since the compiler will be able to infer the type of the variable you”re creating.

Well, as you can see from this short presentation, implicitly typed local variables are simple and they really depend on the compiler (not on the CLR). I still haven”t used this new feature on my C# 3.0 projects. But again, I still haven”t written any LINQ aware application…

Oct 22

Protected: Changes on the configuration of WCF to use JSON

Posted in Uncategorized       Enter your password to view comments.

This content is password protected. To view it please enter your password below:

Oct 15

Sometimes, you might need to get a reference to the UpdatePanel which was
“responsible” for the partial postback. It”s important to understant that a
postback will always be started by an existing HTML control and that the panel
will only be used for delimiting the places where a partial postback might
start. It”s also important to understand that you can have a postback without
associating an HTML control with an UpdatePanel (ie, you can start a partial
postback by registering a control with the AsyncPostBackControl method; when you
do this, you”ll have a partial postback when a user clicks that button, even
though the button is not inside the UpdatePanel nor is it set up as a trigger).
ok, having said this, lets suppose you want to get a reference to the
UpdatePanel that “was responsible for the postback” (ie, you want to get the
UpdatePanel that contained the control that started the partial postback or that
is associated with the control through an AsyncPostBackTrigger). The following
code uses method extensions to add a method that will let you get a reference to
that panel (in the cases where that is possible):

[Disclaimer: this code was written without testing so it might not work in
complex scenarios.I might come back to it in the future, but for now I really
don”t have the time to test it in all the available scenarios]

using System;
using System.Collections.Generic;
using
System.Reflection;
using System.Web.UI;

namespace LA.Extensions
{
    public static class
ScriptManagerExtension
    {
        public static UpdatePanel
GetUpdatePanelAssociatedWithRefresh(this ScriptManager manager )
        {

            if( !manager.IsInAsyncPostBack)
            {

                return null;
            }
            UpdatePanel
panel = null;
            Control ctlId =
manager.Page.FindControl(manager.AsyncPostBackSourceElementID);
           
if( ctlId == null )
            {
                return null;

            }

            panel = TryInUpdatePanels(ctlId);
            if( panel ==
null)
            {
                panel = SearchForTrigger(ctlId,
manager);
            }

            return panel;
        }

        private static UpdatePanel SearchForTrigger(Control ctlId,
ScriptManager manager)
        {
            Type pageRequestManagerType
= Type.GetType(“System.Web.UI.PageRequestManager,System.Web.Extensions,Version=3.5.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35”);

            Type scriptManagerType = typeof (ScriptManager);

            Object pageRequestManager =
               
scriptManagerType.InvokeMember(“PageRequestManager”,

                                                BindingFlags.NonPublic |
BindingFlags.Instance |BindingFlags.GetProperty,

                                                null,

                                               manager, null, null);

            List<UpdatePanel> updatePanels =
               
(List<UpdatePanel>)pageRequestManagerType.InvokeMember(

                                        “_allUpdatePanels”,

                                        BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetField,

                                        null, pageRequestManager, null, null
);

            foreach(UpdatePanel panel in updatePanels)
            {

                foreach(UpdatePanelTrigger trigger in panel.Triggers)

                {
                    AsyncPostBackTrigger t = trigger
as AsyncPostBackTrigger;
                    if (t == null)

                    {
                        continue;

                    }
                    if(String.Compare(t.ControlID,
ctlId.UniqueID) == 0 )
                    {
                       
return panel;
                    }
                }
            }

            return null;
        }

        private static UpdatePanel TryInUpdatePanels(Control ctlId)

        {
            if(ctlId is UpdatePanel)
            {

                return (UpdatePanel) ctlId;
            }

            Control parent = ctlId.Parent;
            while(parent !=
null )
            {
                if( parent is UpdatePanel
&& ((UpdatePanel)parent).ChildrenAsTriggers )
                {

                    return (UpdatePanel)parent;
                }

                parent = parent.Parent;
            }
           
return null;
        }
    }
}

 

The following page shows how the previous extension can be used:

<%@ Page Language=”C#” %>
<%@ Import Namespace=”LA.Extensions”
%>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<script runat=”server”>
    protected override void
OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        UpdatePanel panel = manager.GetUpdatePanelAssociatedWithRefresh();

        if (panel != null)
        {
            lbl.Text =
panel.UniqueID;
        }
    }
</script>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>

    <title>Untitled Page</title>
</head>

<body>
    <form id=”form1″ runat=”server”>
       
<asp:ScriptManager runat=”server” id=”manager” />
       
<asp:updatepanel runat=”server” id=”panel” UpdateMode=”Conditional”>

            <ContentTemplate>
                <asp:Button
runat=”server” id=”bt1″ Text=”inside panel” />
                <br
/>
                <%=DateTime.Now.ToString() %>

                <br />
                <asp:Label
runat=”server” ID=”lbl” />
            </ContentTemplate>

            <Triggers>
               
<asp:AsyncPostBackTrigger ControlID=”bt2″ EventName=”Click” />

            </Triggers>
        </asp:updatepanel>

        <asp:Button runat=”server” id=”bt2″ Text=”outside panel” />

    </form>
</body>
</html>

The important thing to notice here is the use of the Import directive so that
the method extension is introduced on the current namespace. As I”ve said
before, the objective of the code is to show what you might have to write to get
the primary panel associated with the partial postback…

Sep 28

Configuring IIS for hosting Silverlight 1.1

Posted in Uncategorized       Comments Off on Configuring IIS for hosting Silverlight 1.1

From time to time there”s always a new post asking on how to configure IIS to host Silverlight content. I”ve already written something about it, but I”d like to point you to a more complete reference which can be found here:

http://silverlight.net/forums/t/479.aspx

Sep 24

C#: Signaling state changes through events

Posted in Uncategorized       Comments Off on C#: Signaling state changes through events

[Update: Paulo was not impressed with this post but he didn”t want to point it out in the comments. Next time, don”t be shy :,,) He thinks I should drop the old sytax and write thread-safe code. As always, he”s right. Let”s be clear: if you”re creating a new EventHandler event type, just use the generic EventHandler<T> type. You”ll write less and achieve the same thing. Another thing: if you”re writing multithreaded apps – for instance, Windows Forms apps – then don”t forget to change the code for add/remove and even the code used for raising the event so that it”s thread safe. There are already several good articles on how to achieve thread safety, so I”ll just redirect you to them.]

The CLR”s event model is based on delegates (this post presents the main features of delegates). Period. So, this may be a good time to refresh your knowledged on how delegates work.

Most types defined by the famework use events to communicate state changes to anyone that might be interested in being notified about that kind of operations. Generally, exposing an event implies that:

  1. you”ve defined a new type that is used to pass aditional information to the objects receiving the event notification. By convention, this type is a class that extends the EventArgs class;
  2. Build a new delegate that follows the pattern void Delegate_Name( object sender, Your_event_args_derived_type e)
  3. Add a member that exposes the event to the outside world

You should also keep in mind that the event pattern introduced by .NET recommends that your class defines a protected virtual method that is responsible for raising the event. By doing this, you can override that method in a derived class and perform some actions without incurring in the (small) performance hit associated with handling the event (this is a technique that is commonly used when handling ASP.NET page events on the page itself – ie, on the code behind file). Lets look at a simple example which generates an event when the age of a person changes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Livro
{
    public class AgeChangedEventArgs:EventArgs
    {
        internal AgeChangedEventArgs(int _age)
        {
            this._age = _age;
        }

        private Int32 _age;

        public int Age
        {
            get { return _age; }
        }
    }

    public delegate void AgeChangedEventHandler(object sender, AgeChangedEventArgs e);

    public class Person
    {
        private Int32 _age;

        public Int32 Age
        {
            get
            {
                return _age;
            }
            set
            {
                if( _age == value)
                {
                    return;
                }

                _age = value;
                OnAgeChanged(new AgeChangedEventArgs(_age));
            }
        }

        protected virtual void OnAgeChanged(AgeChangedEventArgs e)
        {
             if( AgeChanged != null )
             {
                 AgeChanged(this, e);
             }
        }

        public event AgeChangedEventHandler AgeChanged;
    }
    class Start
    {
        public static void Main()
        {
            Person p = new Person();
            p.AgeChanged += PrintAge;
            p.Age = 20;
        }

        public static void PrintAge(object sender, AgeChangedEventArgs e)
        {
            Console.WriteLine(e.Age);
        }
    }
}

As you can see, I start by defining a new EventArgs derived class, which is used to pass the new age to the interesting parties (btw, do notice that this might not be necessary since the object parameter always contains a reference to the Person object that raised the event). Then, a new delegate is defined. The delegate is important because it”ll define the signature of the methods that can handle the event that will be fired by the  class.

Adding the event member is simple: we just need to use the event keyword and choose the delegate we want to “associate” with the event.

As a side note, we could have dismissed the delegate declaration and have used the EventHandler type for setting up the type of the event. This would be a better option for your production code, but i”m a sucker for history and so I”ve decided to do things “a la .NET 1.1” 🙂

As you can see from the previous code, setting up a method to handle the event is really similar to what happened with delegates. Events usage is really simple; what”s interesting (as always!) are their internals. We”ll use the astonishing .NET Reflector tool (probably the best .NET free tool that you should keep in your toolbox) to see what”s going on. we”ll start by looking at what happens when we use the event keyword (I”ll only copy the important bits from the Person class):

.field private class Livro.AgeChangedEventHandler AgeChanged
.eve
nt Livro.AgeChangedEventHandler AgeChanged
{
        .addon instance void Livro.Person::add_AgeChanged(class Livro.AgeChangedEventHandler)
        .removeon instance void Livro.Person::remove_AgeChanged(class Livro.AgeChangedEventHandler)
}

If you dig a little deeped (by selecting the event on the tree), you”ll see that the add_AgeChangedEventHandler looks like this:

.method public hidebysig specialname instance void add_AgeChanged(class Livro.AgeChangedEventHandler ”value”) cil managed synchronized
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldarg.0
    L_0002: ldfld class Livro.AgeChangedEventHandler Livro.Person::AgeChanged
    L_0007: ldarg.1
    L_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
    L_000d: castclass Livro.AgeChangedEventHandler
    L_0012: stfld class Livro.AgeChangedEventHandler Livro.Person::AgeChanged
    L_0017: ret
}

As you can see, the compiler will add a field of type AgeChangedEventHandler and the event will be transformed on a “special property” which delegates to the add_/remove_ methods added by the compiler. At the end of the day, you”ll end up calling Combine when you use the += syntax to set up method to handle an event.

If you”re worried about synchronization issues, don”t be: the add_/remove_ methods are annotated with the synchronized attribute, which means that they”re thread safe (at least in theory, since the I think things aren”t really that safe when you”re using static methods – but that”s a topic for another post, right? :)).

Now it”s the perfect time to say that, unlike what happens with several other features supported by the C# compiler (ex.: enum declarations), you can define your own “event properties” (ie, event declarations can be “customized”). Here”s a quick example (only the important parts are listed here – note that this code is not thread safe!):

private AgeChangedEventHandler _ageChanged;
public  event AgeChangedEventHandler AgeChanged
{
    add
    {
        _ageChanged += value;
    }
    remove
    {
        _ageChanged -= value;
    }
}

protected virtual void OnAgeChanged(AgeChangedEventArgs e)
{
  if( _ageChanged != null )
  {
        _ageChanged(this, e);
  }
}

By now, you must surelly be worried, right? no? then think about the size of your class if you need to expose several events…not a pretty sight, right? for instance, if you think about windows forms or ASP.NET controls, it”s easy to see that they surelly must be bloated, right? WRONG!

If you look at an event that is raised by one of those controls, you”ll see that they use the Events property introduced by the Control base class (and this happens in windows forms and in ASP.NET applications) to save/get the delegates associated to the events. This property can be seen as a dictionary which is used to store the method that is going to handle the event. So, if you had several events on your class, you should change the previous example so that it looks like this:

protected virtual void OnAgeChanged(AgeChangedEventArgs e)
{
    AgeChangedEventHandler handler = (AgeChangedEventHandler) Events[_ageChangedKey];
  if( handler != null )
  {
        handler(this, e);
  }
}

private EventHandlerList _events;
protected EventHandlerList Events
{
    get
    {
        if(_events == null )
        {
            _events = new EventHandlerList();
        }
        return _events;
    }
}

private static object _ageChangedKey = new object();
public  event AgeChangedEventHandler AgeChanged
{
    add
    {
        Events.AddHandler(_ageChangedKey, value);
    }
    remove
    {
        Events.RemoveHandler(_ageChangedKey, value);
    }
}

Some important notes on the previous snippet:

  • you should define a key that uniquely identifies your event in the hastable maintained by the EventHandlerList
  • You no longer have one field per event with this strategy. This means that you”re not wasting space with unused events
  • The code is not thread safe. nor is the EventHandlerList class. So, if this is important to you, don”t forget to drop a few locks on your code (but please, please do pay attention to what and how you lock).
Sep 10

C#: getting delegates

Posted in Uncategorized       Comments Off on C#: getting delegates

Well, today it”s all about delegates! If you”re looking for an intro on the subject, then there”s already several articles out there (this one by Chris Sells is good way to start). This pos tries to explain what happens when you compile a delegate from C# code. Ok, so lets start with a quick delegate definition that I”ll be using in this post to explain how things work:

public void delegate SayHi(string name); 

If you use reflector and look at IL, you”ll see something similar to this:

.class public auto ansi sealed SayHi
    extends [mscorlib]System.MulticastDelegate
{
    .method public hidebysig specialname rtspecialname instance void .ctor(object ”object”, native int ”method”) runtime managed
    {
    }

    .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(string name, class [mscorlib]System.AsyncCallback callback, object ”object”) runtime managed
    {
    }

    .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed
    {
    }

    .method public hidebysig newslot virtual instance void Invoke(string name) runtime managed
    {
    }

}

This is quitesimilar to what happens when you declare an enum. In other words, when the compiler sees the delegate keyword, it generates a new class which inherits from MulticastDelegate (and again, don”t try this in C# because you”ll get a compiler error). Besides the constructor, the compiler also defines three methods:BeginInvoke,EndInvoke and Invoke (the first two are used when you want to perform an async call; the second is the one to call when you”re into synchronous calls).

So, our delegate declaration results in a new class that inherits from MulticastDelegate which, in turn, ends up extending the Delegate class. If we”re really interested in getting under the hood, we should start by seeing what these classes do. The Delegate base class introduces two important fields: _target and _methodPtr. The first field points to the instance of the class over which the method is being called (it”s null when you”re passing a static method). As you expect, _methodPtr identifies the method that will be called when you invoke the Invoke or the BeginInvoke method exposed by the SayHy class (oops, or should I say delegate?).

do notice that the constructor injected by the compiler receives a reference to an object and method that are used to initialize these fields. this might seem odd since you set up a delegate with code similar to this one:

namespace Livro
{
    public delegate void SayHi(string name);
    class Start
    {
        public void SayingHi(string name)
        {
            Console.WriteLine(name);
        }
        public static void Main()
        {
            Start t = new Start();
            SayHi test = t.SayingHi;
        }
    }
}

Well, if we really really wanted to follow the “rules”, we should really have written SayHi test = new SayHi( t.SayingHi ). However, it”s really simpler to just use the previous syntax since the C# compiler can infer the correct code from it.

If you look at the IL generate by this code, you”ll see that the C# compiler translates the previous reference in a call to the constructor, generating values for the expected parameters:

.method public hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 3
    .locals init (
        [0] class Livro.Start t,
        [1] class Livro.SayHi test)
    L_0000: nop
    L_0001: newobj instance void Livro.Start::.ctor()
    L_0006: stloc.0
    L_0007: ldloc.0
    L_0008: ldftn instance void Livro.Start::SayingHi(string)
    L_000e: newobj instance void Livro.SayHi::.ctor(object, native int)
    L_0013: stloc.1
    L_0014: ret
}

Going back to the Delegate class, there”s still time to talk about the Target and Method read-only properties. If you add the following code before the end of the Main method presented on the previous C# code snippet:

Console.WriteLine(test.Target);
Console.WriteLine(test.Method.Name);

You”ll see that you”llg et the following output:

Livro.Start
SayingHi

These properties let you get the reference passed to the delegate (Target) and the MethodInfo object that  describes the method that was passed to the delegate (Method). As you can see, there are many potential uses for these properties (though I”ve never seen anyone use them from a “standard” C# program). Before we tal about the “all important” MulticastDelegate class, lets see what happens when you call the delegate by using what i call the “method call syntax” (using the text variable introduce on the previous example):

test(“Luis”);

L_0015: ldstr “Luis”
L_001a: callvirt instance void Livro.SayHi::Invoke(string)

The important thing to notice is that you”ll end up calling the Invoke method of the class generated by the compiler to represent the delegate.

MulticastDelegate is responsible for introducing the _invocationList field, which is used for keeping a list of methods that should be called when you invoke the delegate. In other words, the class is responsible for letting you call several methods through a single “delegate method invocation”. For instance, if you modify the previous code so that it looks like this:

Start t = new Start();
SayHi test = null;
test += t.SayingHi;
test += t.SayingHi;
test(“Luis”);

and run it, you”ll see Luis twice.

L_000b: ldftn instance void Livro.Start::SayingHi(string)
L_0011: newobj instance void Livro.SayHi::.ctor(object, native int)
L_0016: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
L_001b: castclass Livro.SayHi

btw, in this case Reflector is “cool” (ok, sorry. i meant really cool!) and does translate that code in C# (which i”m putting here so that it”s easier to understand):

Start t = new Start();
SayHi test = null;
test = (SayHi) Delegate.Combine(test, new SayHi(t.SayingHi));
test = (SayHi) Delegate.Combine(test, new SayHi(t.SayingHi));
test(“Luis”);

The Combine method is static and receives two delegates: an existing delegate (or null) and the new one that we want to add to the internal list. Btw, do notice that this method is really defined by the Delegate class. Internally, it ends up calling the protected sea
led CombineImpl instance method, that ends up being overriden by the MulticastDelegate class (which is where the most interesting things happen! ).

The behavior of this method is interesting, to say the least. when one of the delegates is null (this happens, for instance, on the first call of the Delegate.Combine method shown on the previous snippet – notice that test is set up to null when it”s declared), this method isn”t invoked since the Delegate”s Combine method simply returns the other non-null reference that it receives. When that isn”t the case, then the method has to build a new MulticastDelegate which is returned back to the caller and has its _invocationList correctly filled with the values maintaned in both delegates. basically, this means that it has to combine a possible non-null _invocalistList of a delegate with an empty one from the other.

Internally, the method garantees that the new MulticastDelegate”s _invocationList respects the order of declaration. This means that if we have something like this:

Start t = new Start();
SayHi test = null;
test += t.SayingHi;
test += t.SayingHi2; //suppose the class has a SayingHi2 method
test(“Luis”);

Then calling test will call the SayingHi method before the SayingHi2 method. So, now we can assume what happens when you call  the Invoke method of the class you create when you define a new delegate: it”ll simply go through the list and call each method maintained by the existing delegates. btw, do not loose any time looking for the Invoke implementation since these methods are implemented by the CLR itself (notice that they”re annotated with the runtime managed qualifier). If you”re looking into more info about delegates and the way these mehods are implemented, then take a look at this Brad Adam”s post.

As you might expect by now, you can also remove a delegate from a MulticastDelegate”s internal _invocationList by calling the Remove method. In C# you”ll just call the -= operator:

test -= t.SayingHi;

I think that you could still write a lot more about delegates. However, i do believe that this post has presented enough insight on what happens when you use delegates from C# code.  And that”s a  wrap!

Sep 05

Protected: C#: should I use new on value types?

Posted in Uncategorized       Comments Off on Protected: C#: should I use new on value types?

This content is password protected. To view it please enter your password below:

Jul 23

IronRuby''s first source code drop is out

Posted in Uncategorized       Comments Off on IronRuby''s first source code drop is out

And John Lam gives you more info about it here.

Jul 16

Silverlight Astoria client add on

Posted in Uncategorized       Comments Off on Silverlight Astoria client add on

Pablo Castro announced the Silverlight client add on a few days ago. If you”re into Astoria and Silverlight, then go get it!

Jul 12

Silverlight: Beta vs Alpha

Posted in Uncategorized       Comments Off on Silverlight: Beta vs Alpha

Sorry, but to me only the manged version matters :,,) Just for fun i”ve tried porting some of the beta samples to managed code. Against all odds, i”ve ended up enjoying the simplicity of Javascript and I”ve tested different approaches for encapsulating xaml content. When i ported the beta samples, i wanted to do it as quickly as possible.

So, i”ve just copied the xaml and built the rest of the code around those files instead of refactoring the main elements of the top canvas into controls. And you want to know something? I”ve really think that this approach might be a good option if you”re not repeating elements on a canvas (at least on the current version).

Btw, there are really somethings which are a lot easier in javascript than in managed code. For instance, try setting a path in managed code and then see how easy it”s in Javascript…If you take a look at the code i”ve written in managed code, you”ll see that some don”t mimic all the functionalities that exist on beta version”s code (most of them for lack of time).

Jul 03

Silverlight alpha gotchas

Posted in Uncategorized       Comments Off on Silverlight alpha gotchas

[Update: I must have been drinking when i wrote this :,,) It should be local domain because you cannot get objects from a remote host through the BrowserHttpWebRequest]

These 2 just made me loose +45 minutes:

1. if you”re using the BrowserHttpWebRequest to download files from a remote domain, then make sure you”re testing your page from a web server (the internal server that comes with VS works, but you”ll start getting the object is not on the correct state exception -or something like that – if you try accessing objects from a remote host).

2. The same holds true if you”re loading a remote wmv file on a MediaElement.

Not sure if there”s any explanation for these, but it did steel me 45 precious minutes.

Jun 22

31 days of Resharper

Posted in Uncategorized       Comments Off on 31 days of Resharper

Since there”s a new release of this great tool, maybe it”s reread the 31 days of resharper :,,)

May 16

Hosting Silverlight controls on a sidebar gadget

Posted in Uncategorized       Comments Off on Hosting Silverlight controls on a sidebar gadget

What was supposed to be an easy task simply doesn”t work. It seems like I can instantiate the AgControl ActiveX object from a “normal” HTML page but it doesn”t when the page is loaded on the Windows Sidebar. The error is the old “Automation server can”t create object” which really means that the ActiveX can”t be instantiated (which doesn”t make sense since loading it in the IE browser I do get the object instantiated).

I”ve open a thread on the Gadgets forum. If anyone has some advice, please let me know. thanks.

May 10

testing 1, 2, 3

Posted in Uncategorized       Comments Off on testing 1, 2, 3

new post.

May 07

The ASP.NET May bits introduce some Diagnostic related classes that

try to give you some help in logging client exceptions. Dropping the ASP.NET Diagnostics control in an ASP.NET AJAX page adds a reference to PreviewDiagnostics.js file. This file has code that creates a Sys.Preview.DiagnosticsService object (of type Sys.Preview._DiagnosticsService). In theory, the object will automatically handle all errors that aren”t trapped by your code and then it”ll invoke a remote web service which is responsible for notifying the interested parties about that error.

I say in theory because after looking at the code, I think that it doesn”t work in the current release (at least, the web service method calling part isn”t really working). Again, I”m hopping to be wrong :,,)

After using Reflector, I”ve noticed that there”s a new class (DiagnosticsService) which is supposed to be the web service responsible for receinving the exception sent from the client side. I think that the idea is to build a service similar to the authentication/profile service. Unfortunately, i think that currently the WebServiceData class is only able to create authentication or profile web service instances maintained inside a dll. That being the case, it really looks like the web service call won”t really work (maybe that”s why they”ve left the client error callback method empty?).

If you really want to, you can create a local web service with the same name and redirect the methods call to the “real” service that is embedded in the dll. However, doing that won”t do any good because in the current version the class doesn”t do any logging: it just wraps the ExceptionInfo object it receives from the client and then it fires the event OnClientException (real weird name for an event, if you ask me; and I”m still not sure on what”s the purpose of firing an event when an exception is received). So, if you want to log the exception, build the web service and perform the logging yourself.

Besides the server control, the javascript client  class and the embedded web service, there”s still another interesting (hum…maybe promising is a better name for it!) class: DiagnosticsHandler. It seems like the idea is to have a handler that is able to generate some sort of info about the exceptions caught and sent back to the server. Again, the current version doesn”t have anything that lets us do more than speculate since the ProcessRequest method generates some static HTML which really doesn”t do anything useful.

In fact, it seems like the only working feature is the display client method which opens a page and prints the current exceptions maintained by the client object.

Even though i know these are just CTP bits, i”m not sure on what was the purpose of adding these features to these bits. I mean, they simply don”t work. Or did I forgot something?

[Update: after publishing the article, I”ve just noticed that there is a quickstarts page for the Future bits. Well, it”s kind of interesting that I”ve managed to spend 30 mins trying to figure out things when i could just have read the damn docs (mental note: next time, search for the docs before using Reflector! :)). Reading those docs do share some light on how to use diagnostics. I specially enjoyed the “having to wire the static event on the application start event after creating a dummy DiagnosticsService.asmx file”. If you ask me, I really don”t know why don”t dey define a basic “interface” for a web service. If i have to create a dummy asmx file, why not go all the way and build a web service that performs the logging?]

Apr 16

WPF/E is now called Silverlight

Posted in Uncategorized       Comments Off on WPF/E is now called Silverlight

Not sure on when this name changed occurred, but it seems like now WPF/E is known as Microsoft Silverlight. Maybe it”s time to take it seriously and start studying it…

Mar 18

Protected: Does having a CS degree matter?

Posted in Uncategorized       Comments Off on Protected: Does having a CS degree matter?

This content is password protected. To view it please enter your password below:

Mar 04

During the next days, I”ll be writing about the AJAX Toolkit. I”ll start with the client part and then I”ll proceed to the server part. The main objective is to document some of my findings and put them all in a place where i can search them. Today I”m going to write about deferred operations. A deferred operation can be seen as an operation that is scheduled to run sometime in the future. Yes, you can already do this with javascript programming by using the window.setTimeout method. The advantage of using the Toolkit is that you”ll get a class that let”s you start or cancel a deferred operation. Without further ado, let”s see an example. The following page let”s you introduce a name and then call  a method (which you can right away – by using the sync button- or on a deferred way, by using the async button):

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
 <head runat=”server”>
 <title>Untitled Page</title>
 <script type=”text/javascript”>
     var _deferred = null;
     function deferred(name){
           alert( “you”ve sent me ” + name );
    }
    function handleLoad(){
         _deferred = new AjaxControlToolkit.DeferredOperation( 2000, null, deferred );
   }
   function sync(){
          _deferred.set_delay( -1 );
         _deferred.post( $get(“name”).value );
   }
   function async(){
         _deferred.set_delay( 2000 ); //just to garantee that the delay is not overriden by sync method being called previously
        _deferred.post( $get(“name”).value );
   }
   function cancel(){
        if( !_deferred.get_isComplete() ){
           _deferred.cancel();
        }
   }
</script>
</head>
  <body onload=”handleLoad()”>
     <form id=”form1″ runat=”server”>
         <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
             <Scripts>
                <asp:ScriptReference Path=”Threading.js” />
            </Scripts>
        </asp:ScriptManager>
       <div>
        <span>Name:</span>
        <input type=”text” id=”name” />
        <input type=”button” id=”start” value=”sync” onclick=”sync()” />
        <input type=”button” id=”Button1″ value=”async” onclick=”async()” />
        <input type=”button” id=”Button2″ value=”cancel” onclick=”cancel()” />
      </div>
  </form>
</body>
</html>

There are some points worth noticing here:

  • The DeferredOperation constructor receives three parameters: the delay (in ms), the context (over which the a method will be called) and a reference to the callback method;
  • The DeferredOperation class has other important properties. For instance you can decide if an exception that happens during the method execution is thrown (_throwExceptions), you can get the return value of the method (_asyncResult), etc;
  • You can execute the method synchronously (by calling the post method – sort of; more info below) or asynchronously (ie, defer it x milliseconds), by calling the beginPost method.

As you can see from the previous example,I”m calling a “global” method (again,sort of :)) so i”m passing null for my context. One curious thing you”ve seen in the previous code is that for getting a synch method call you can”t only call the post method. you need to garantee that when you call that method, you”ve set the delay property to -1 (yes, if you”ve set it to a different number, you”ll get a deferred method call). Well, I”m not sure about you, but I really don”t like this approach. If you have a XXX method and another beginXXX method, it”s natural to assume that the XXX method is synchronous and that the beginXXX will do the same thing asynchronously. Having to set the delay to -1 is not intuitive.  So, i really expected that calling post would call the deferred method imediately, instead of just starting the timer for the deferred method call…

Another thing you should now is that you can pass a callback method and an error callback method when you use the beginPost method. Those methods will be called after the execution of the deferred method finishes or if the deferred method generates an exception.

Finally, you should note that a deferred method execution can be cancelled by calling the cancel method.

Update: I”ve updated the code and I”ve declared _deferred as a page variable. I deleted it by mistake while arranging the contents in live writer. Thanks Bertrand for pointing this out.

Jan 24

Authentication services: using them from html pages

Posted in Uncategorized       Comments Off on Authentication services: using them from html pages

If you”re using the client authentication services on an ASP.NET page that has a ScriptManager control, then there”s nothing here for you. it”s safe to move on :,,)

On the other hand, if you”re using the client side files and you do need to integrate your page with the authentication of ASP.NET, then keep reading. In the CTP, the client side class initialized itself with the path to the service in the server side. As you know, the service is embedded in the System.Web.Extensions.dll and you can only access it if your request has a specific  path. So, the problem is knowing the path to the service so that you can set your AutorizationService with the correct path.

In the current release, the authentication service only responds to the Authentication_JSON_AppService.axd name and the url must point to the top folder of your web app. For example, if you”ve got an html page at the top of your web folder, you only need to indicate that path. On the other hand, if you have a page inside a subfolder, you do need to make sure that you”re forming the correct path. Here”s an example of initializing the path property of the AuthenticationService object from a page placed inside a sub-folder of the top web folder (note the ../ used in the path):

Sys.Services.AuthenticationService.set_path( “../Authentication_JSON_AppService.axd” );

Jan 02

Having fun with generics – part II

Posted in Uncategorized       Comments Off on Having fun with generics – part II

This is one of those things which might really make you go mad. Ok, let”s start with a non-generic class. What will happen when you try to build a program that has this class:

class Test
{
 public bool TestMethod(string par){ … }
 public bool TestMethod(string par) { … }
}

As you expect, you”ll get an error saying that type test already defines a member called TestMethod since you”ve already defined a method with the same name and the same parameters (both methods expect only a parameter of type string). But what will happen when you build the following class:

class Test<T>
{
 public bool TestMethod(T par){ Console.WriteLine(“T”); return true;}
 public bool TestMethod(string par){ Console.WriteLine(“string”); return true;}
}

Well, not sure about you, but I really thought that the C# compiler would at least throw a warning saying that there might be some problems with the 2nd method definition. Guess what: it didn”t. it compiled without any warnings. So I went on and run the following code:

Test<int> t = new Test<int>();
t.TestMethod(10);
t.TestMethod(“10”);
Console.ReadLine();

It worked as expected and I saw the following in the consolde:

T
string

Perfect! It makes sense. Now, how about this:

Test<string> t = new Test<string>();
t.TestMethod(“10”);
Console.ReadLine();

If you said string, you”re right. In these cases, the method that expects a parameter T will never be called. I expected to get an error saying that the overload method was incorrect, but i didn”t get any. I thought that compilation would run without any problems. It did. At runtime, i was really convinced that i”d get an error; I didn”t. I”ve even added this code to my console app:

Type tp = t.GetType();
MethodInfo[] methods = tp.GetMethods();
foreach( MethodInfo info in methods )
{
  Console.WriteLine(info.Name);
  ParameterInfo[] pars = info.GetParameters();
  foreach( ParameterInfo par in pars )
  {
     Console.WriteLine( par.Name + ” : ” + par.ParameterType + ” – ” );
  }
}

which produces this:

TestMethod
par : System.String –
TestMethod
par : System.String –
GetType
ToString
Equals
obj : System.Object –
GetHashCode

To me, this really looks like a method re-definition and no error. on the other hand, I”m positive that the guys that have designed the compiler are really good (a lot better than me ) and that”s why i think I”m still missing something here. If i discover what,I”ll put it here. If you know why this happens,please end with my misery and add a comment to the post 🙂

 [Update: I think I”ve understood why this happens. It seems like the C# generics specification only requires the method”s signature to be unique prior to the class” instantiation. If this is true, then the previous example makes sense nad works as it should. If I”m wrong, please correct me. thanks]

Oct 31

Mike Weerasinghe has made a good question regarding my previous post about error handling. Mike says that he”s handling errors by using a module which handles the HttpApplication error event. Unfortunately, this will stop working when you use AJAX extensions because the ScriptManager control will handle the error and automatically return a response to the client stopping the event from being propagated to the HttpApplication object. So, if you”re handling the Error event of that class, you won”t be notified about the error and your logging will stop working.

The solution to this is to handle the Error of the Page since the methods that handle it will always be called if you get an exception during a partial postback. Since I think nobody will want to add their logging logic to all the pages and will probably want to keep handling the error from a module, then there”s a workaround which might just work with you. What you need is to handle the PostMapRequestHandler event, which is fired by the HttpApplication object after mapping the current request to a handler. During that event, you can check for the current handler and see if it”s a page. If it is, then you just need to handle the Error event and you should be ready to go. Here”s a sample which shows what you need in order for it to work (I”m pasting the code from global.asax, but it should also work from a module though i haven”t tested that):

protected void Application_PostMapRequestHandler(object sender, EventArgs e)
{
  Page aux = this.Context.Handler as Page;
  if( aux != null )
  {
        aux.Error += new EventHandler(page_Error);
   }
}

void page_Error(object sender, EventArgs e)
{
   //log error as you want
}

By hooking the error event like this, your method will always be called before the one introduced by ScriptManager and you will have access to the current exception. Just don”t clear it because if you do,the ScriptManager”s method will not get the info it need to its work.

Hope this helps…

Update: I was so eager to get a general error handling solution that i”ve just forgot about object lifetime! As my good friend João Paulo said in the comments,my previous solution might be bad if you don”t want to leak resources (and yes, I do believe that you don”t). As he said,  I should remove my event handler so that I don”t keep the page alive. However, there”s a problem with the PostRequestHandlerExecute event handling: though I could be mistaken, but I think it won”t be called due to the way that ScriptManager handles the Error event generated by the page: it calls Response.End after packaging the response which is being sent back to the client. So, removing the method from the event list during the page_Error method might be the best option to this scenario (specially if you know that the page has a ScriptManager control)

btw, thanks for the correction João…and don”t be a stranger! 🙂

Update2: re-reading my previous update made me think that I didn”t explain myself correctly. My previous remarks are only valid for when an exception happens in a page that has a ScriptManager control. If there isn”t an exception, you still should hook a post execute handler event in order to unsubscribe the event handling…