Archive for the “.NET” Category

I have a side project on reflection where I try to reproduce Lutz Roeder’s Reflector in such a way as to allow me to inspect several issues within my projects. This has led me to research into all kinds of issues from MSIL to C# code model and Reflection, the latest one becoming one of my favorite topics from .NET technologies.

My lattest hurdle was to overcome the devious “FileNotFoundException” when trying to resolve a type which is not in the main loaded assembly for reflection.

What happens? Let’s suppose you load an assembly which you want to inspect using reflection. You would use something like:

Assembly assembly = Assembly.LoadFile(path);
Type[] types = assembly.GetTypes();
MethodInfo[] methods = types[0].GetMethods();
ParameterInfo[] parameters = methods[0].GetParameters();

Then you start the usual work of gettting the types and then get the methods of one of the types and then of course try to see something like the parameters of one of the methods. Ain’t reflection great?

NO. Not if you don’t know how to use it. Because when you hit the line where you want to load the parameters of a method, the application will crash with a “FileNotFoundException” when the dll inspected is not in the same directory as the executable that is loading that assembly. Why the hell is that happening. Well I scoured the net for an answer and all where giving partial responses but none were actually giving me a sollution.

Let’s consider the following.

namespace A
{
   public class C1
   {
   }
}
 
namespace B
{
   public class C2
   {
      public void MyMethod(A.C1 param1)
      {
      }
   }
}

And let’s consider that the namespaces A and B are declared in separate projects and thus result in two different dlls and the project that defines namespace B references the project that defines namespace A.

Now you want to load the “B.dll” to inspect the parameters from method “MyMethod” and you use the code I described above. Here the runtime will fail because he does not have a definition of the class C1, only of the class C2 which he already loaded and he will try to load the dll from the current directory (the directory of the running assembly – not A or B, but you program which inspects B). If the “A.dll” is not located there he will try in GAC and if that fails he will throw an exception. How do you fix this? Well you have the choice to copy the “A.dll” in your running directory or registed in GAC but hell, it is not nice and sometimes not possible.

What you can do is to instruct the application domain to call a custom method defined by you when he needs to load an assembly.

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly ass =
    Assembly.LoadFile(AppDomain.CurrentDomain.RelativeSearchPath + args.Name.Substring(0, args.Name.IndexOf(“,”)) + “.dll”);
return ass;
}
 

What I told the domain here is to call tyeh CurrentDomain_AssemblyResolve method and there I made an assumption. When you compile the namespace B, in it’s debug directory the dll of namespace A is also copied. So if you load the assembly of namespace b from it’s debug directory, in the same directory we will have also the assembly of A. So we will load the assembly from there

Simple and effective. This approach solves also the error “Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.”

Cheers

Comments 9 Comments »

Today I want to talk about a strange issue and my workaround.

Scenario: you have an UpdatePanel and a button outside it. You want upon an asyncronous postback to execute some custom javascript on the button outside the UpdatePanel. Normally this would be done by inserting a javascript from codebehind, either by using ClientScriptManager.RegisterScript or by adding a literal control which is actually a simple script. Well, this does not work during asyncronous postbacks, or at least not as it normally should.

The document.GetElementById is returning always null when calling from an updatepanel with an ID of an element outside the updatepanel. So how to run that javascript?

Subscribe a javascript function to the EndRequest event of the PageRequestManager:

<script language=”javascript” type=”text/javascript”>
   function EndRequestHandler()
   {
      
document.getElementById(‘myButton’).style.visibility = “visible”;
   }
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
</script>

What this does is to define a function and then set it to be executed after successfully asyncronous postback.

Cheers!

Comments No Comments »

Since the Microsoft Ajax was released, a lot of ASP.Net developers began using UpdatePanel for streamlining their applications and indeed the WWW starts to seem a little bit more fluent nowadays.

Unfortunately UpdatePanel is not used always in the right places or in the right way, some applications begin to feel clumsy and slow and you’re thinking WHY?! Below I compiled a small list of tips and tricks on how and where to use an UpdatePanel.

  • In web.config use this:

<system.web.extensions>
    <scripting>
        <scriptResourceHandler enableCompression=“true” enableCaching=“true”/>
    </scripting>
</system.web.extensions>
This will improve script handling by adding compression and caching

  • When deploying to a live server use: <compilation debug=“false”> 
  • Don’t use AJAX to update the complete page by putting everything in a UpdatePanel. You want to save time and raffic when running the web page. Never update parts of the web site that can be changed using JavaScript and DHTML (DOM).
  • Have in mind that there are a couple of visitors that have JavaScript disabled or using a web browser with an older or less JavaScript implementation like the most mobile devices have. What does your visitor see if everything is disabled? I don’t recommend to have the full web site available as a JavaScript disabled version!
  • Cache the same requests on client-side web browser or implement any caching on the web server.
  • Remember that the page lifecycle is the same also during an asyncronous postback. That means that the Page_Load for example is executed also during an asyncronous postback. The IsPostback will be true in an asyncronous postback also.
  • Set the UpdateMode to “conditional” in the update panel

There are more,  feel free to add your own

Comments 1 Comment »

Hi,

Yesterday I was asked a simple question about using a separate browser window for selecting a value and then using the selected value in the main browser window. I’ve done this before but I realized that for a novice web programmer it is not trivial especially when you are accustomed to the ASP.Net programming model.

Let’s consider the following scenario. You are editing an order for buying some books. You enter your name, address, and other information in the textboxes, but you are then required to select the book you are searching for. The problem the programmer is facing is that on one hand he has alot of books in the database (let’s say 5000 items), which means that it would be overkill to fill a dropdown with those names and hard for the user to select from it (too many options), on the other hand ussually he does not have the space to put a complex search in place. So the most ideal situation is to put a separate window that opens on command and where the user can use a more complex algorithm to search for the book he wants. Ok, this is not a very good example as in real world you first select the book, add it to cart and then go to the checkout and fill all remaining data. Still let’s say this is ok for the sake of the demonstration.

So, we have a main window and from there we must open a second window where the user selects some data, then the selected data must be passed back to the main window. Well, ASP.Net does not offer something out of the box for this as the Asp model is based on a single window. So what you can do with asp is to redirect the page to a search window and then upon selecting the desired value redirect it back to the main window and put the values there (you can pass the values either through the Session object or QueryString). This unfortunately requires some extra programming and also might be a little bit difficult for the user to understand.

Thus we get the the javascript sollution. User clicks on a button, a new browser window opens, user makes selection, the new browser window closes and the selection is put in the main window. Below you can find an example and some explanations.

This is the main window:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”master.aspx.cs” Inherits=”_master” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Master window</title>
   <script language=”javascript” type=”text/javascript”>
      function openChildWindow(tagetControlId) 
      {
         var s= “child.aspx?id=”+tagetControlId;
         window.open(s,“”,“width=400,height=200,status=no,toolbar=yes,menubar=no,location=no”);
         return false;
      }
   </script>

</head>
<body>
   <form id=”form1″ runat=”server”>
      <div>
         <asp:TextBox ID=”txtResult” runat=”server”></asp:TextBox>

         <asp:Button ID=”btnOpen” runat=”server” Text=”Open child” OnClientClick=”openChildWindow(‘txtResult’)” />
      </div>
   </form>

</body>
</html>

This is the child window:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”child.aspx.cs” Inherits=”child” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >

<head runat=”server”>
   <title>Child window</title>
   <script language=”javascript” type=”text/javascript”>
       function Done()

      {
          p = window.opener.document; //parent window
          target = p.getElementById(GetElementFromQuery(location.search.substring(1),“id”));

          target.value = document.getElementById(“txt1″).value+“|”+document.getElementById(“txt2″).value;
          window.close();
       }
       function GetElementFromQuery(url, name)

       {
         x = url.split(“&”);for (i=0;i<x.length;i++)

         {
             if (x[i].split(“=”)[0] == name)

             {
                return x[i].split(“=”)[1]

             }
          }
          return “”;

        }
   </script>

</head>
<body>

   <form id=”form1″ runat=”server”>
      <div>
         <asp:TextBox ID=”txt1″ runat=”server”></asp:TextBox>
         <asp:TextBox ID=”txt2″ runat=”server”></asp:TextBox>
         <asp:Button ID=”Select” runat=”server” OnClientClick=”Done()” Text=”Close”/>
      </div>
   </form>

</body>
</html>


So, let’s summarize. In the main window, which I called master, you have a textbox where we want to put the results and a button which when pressed we want to open the child window. Observe that we use the OnClientClick instead of OnClick since we will be calling a javascript function and there is no need to go to the server (Reminder: OnClientClick is fired before OnClick and in the javascript code of the OnClientClick if we return false, the OnClick will not be fired anymore).

The javascript function called on the click event is “openChildWindow” which has as parameter the id of the control that will receive the selection made in the child window. In the method we construct the URL of the child window where we will pass the id as a query string, then we use the window.open to open the child in a separate browser window.

In the child window we have 2 textboxes from where we will take the selection. When the user presses the button, the “Done” function will first retrieve the opener object, which is a handle to the window that oppened the child window (this is normally null, unless the window was opened as a result of a window.open call). then we retrieve the html object from the opener window that has as id the string passed as query string. we use a separate function for that, which will search within the query string the keyvaluepair with the specified key and retrieve the value (we used “id” as we sent it like this from the master window). Afterwards we set the value of the target element with the values from the two textboxes and close the window.

This is highly extensible as the child window can host a normal ASPX page and the results can be multiple and returned in various locations within the master page (just use more keys in the QueryString).

That’s it for now. Feel free to adapt the above code to your needs and post any questions you might have.

Edit: You can find also a more detailed example here

Comments 3 Comments »

There are quite a lot of us who have a lot of papers on their desks with notes, tasks, observations. And there are those who use notepad alot to store usefull information on the project. Still it’s not easy to do this organization tasks when programming as it makes you either leave the development IDE or take your hands of the mouse and keyboard.

Why don’t we have a way to make quick notes within Visual Studio 2005. Well we actually do, although I have not seen any using it. Just go to the View menu and select Task List. A dockable window will come in front and you can dock it somewhere, I dock it in a group of windows below the code, so that it is easy accessible. How do you use it, well, just double click on the first available row in the list and enter your comments/tasks there.

For example, you have a task which is actually containing 7 inner tasks/functionalities. At some point you have to hardcode a variable so that you can go faster to another task and at some point you have to get back and correct this. This happens. No, no, don’t shake your head! you did it at some point. The problem is that you will likely forget this. Well, add a task like “Correct the hardcoding on file myfile.cs line 44″. At some point you will check that list and you can see what you still need to do and well … do it. Then just mark the task as completed (checkbox on the same line left side), or delete it.

No more yellow stickers and endless blocknotes :)

Cheers

Comments No Comments »

Hi guys,

It’s been a while since I wrote a post here and that’s not because of a lack of good ideas but from a lack of time :)

What I want to talk about today is about an issues with MS.Ajax and IFrame’s. To be more precise, UpdateProgress and IFrames.

When a page contains an IFrame and both the page and the IFrame contain an UpdateProgress control, when an Ajax callback occurs, the Ajax engine tries to link the UpdateProgress control to the panel that contains the progress image.The problem is that you have two UpdateProgress controls and on the second one you would get an error in the  MicrosoftAjax.js file, more exactly in this function:

Sys.UI.Control = function Sys$UI$Control(element)
{
   /// <param name=”element” domElement=”true”></param>
   var e = Function._validateParams(arguments, [{name: "element", domElement: true}]);
   if (e) throw e;
   if (typeof(element.control) != ‘undefined’)

       throw Error.invalidOperation(Sys.Res.controlAlreadyDefined);
  
Sys.UI.Control.initializeBase(this);
   this._element = element;
   element.control = this;
   this._oldDisplayMode = this._element.style.display;
   if (!this._oldDisplayMode || (this._oldDisplayMode == ‘none’))
  {
      this._oldDisplayMode = ”;
   }
}

The red code is where it crashes. So what is the sollution for this ? : use a single update progress, maybe in the masterpage if you have such thing.

 Cheers

Comments No Comments »

There are quite some articles on this small issue but what I would like to post here is a more special situation.

This error occured while building a website in Visual Studio 2005 (the website was actually a port from an older Visual Studio 2005 WebSite Project). I could simply not find out why this error occured. It seemed that the compiler was building an object having a method or member with the same name as the class representing the page. In the codebehind file one could not pinpoint the problem, and then a coleague pointed out: “The form id has the same name as the class!”.

There you have it: in a ASP.Net 2.0 Website do not give the form object of a page the same id as the name of the page! otherwise you’ll get an error.

Comments No Comments »

I was busy these days optimizing code for speed. What I found is no less than mind boggling. Using the right constructs one can speed up pieces of code tremendeously (read this like: a code that runs 10 minutes can be optimized sometimes to run in 10 seconds).

Tips:

Try to get data from the database in a single run. This is an old one but it seems people tend to forget this.

Carefull with the binding. With the advent of persistance frameworks, getting data from the database and binding it to controls became easy. Unfortunately due to design sometimes this gets in our way. For example, we have a business object called Person and which has a property homeadress of type Adress. In normal frameworks, the homeadress object is loaded only when it’s needed. So, we get a list of persons and bind this to a grid. And we say that one of the columns is actually a property of adress (person.homeadress.streetname). During binding, for each person, a call is made to the database to load the homeadress object and retrieve it’s streetname property. Thus for a 10 persons list we have 11 calls to the database (1 for retrieving the list of persons and 1 for each person to get the adress object). Try to avoid this !!! Use simple ADO objects of modified business objects instead.

Avoid find using predicates on lists. Searching using predicates is very nice and somehow natural but for large lists (1000+), the search time is high. Try using dictionaries for fast retrieval of elements.

Avoid List<T> and use Dictionary<T,Y> when making caches. This is an odd one, i did not digg deep into this problem but it seems that when creating a cache (parse a list, add the items) and afterwards accessing elements, for the same amount of data and the same logic, a dictionary was 10 times faster.

Use explicit casting when possible. The most common scenario is when we have a DataReader and we try to read data from it. If we know the first column is a string we could do it like datareader[0].toString() or (string)datareader[0]. And now the milion dolar question, what’s faster … take a wild guess :) . Also, don’t do int.Parse(datareader[0].toString()) if you know there’s an int, use (int)datareader[0].

… more to come here

Comments 4 Comments »

About one year ago I wrote a small library which had as sole purpose the interpretation of the MethodBody.

What if this usefull for? Well using standard reflection mechanism from .NET one can find out from an Assembly what modules are inside, what types (classes, interfaces, enums, etc) and for each one can get the definition of the methods, fields and so on. Unfortunately when you get to retrieve the body of a MethodBase you stumble into a deadend. Microsoft does provide just a single method that can help: MethodBase.GetMethodBody. This returns an array of bytes that represent the body of the method. How in the nine hells can this be interpreted? We might want to know if a certain method is called from another method. By looking at an array of byte this task is dauting.

Still, if one looks at Lutz Roeder’s Reflector one can see that you can interpret this and even retrieve actual C# code from it. I managed to do something similar and the library I mentioned is a lightweight tool that creates a set of Intermediate Language instructions from the body of a method by looking at that array. I won’t get into details here because it is described pretty well in the codeproject article posted by me: http://www.codeproject.com/csharp/sdilreader.asp.

Check it out

Comments No Comments »

Mnemonics – quick access keys that appear as underlined letters on buttons or menus and which are accessed by pressing the ALT key and the corresponding letter (the one underlined).

Read the rest of this entry »

Comments 2 Comments »