Archive for the .NET Category

Yesterday I cam across an issue while integrating a project in our CruiseControl.Net (CC). We needed a file from a project to be checked out always on the CC server. This is impossible with the current implementation of CC because when it tries to get the latest version from VSS it would crash, because the combination of parameters that CC sends to VSS is such that it cannot ignore locally checked out files.

VSS is actually called using the executable “ss.exe”. This accepts an option for the get command called “-GWS”. The problem is that the configuration section of CC does not support this parameter so we don’t have any way to tell VSS about skipping checked out files.

The solution looks simple although it caused me some headaches. You just have to  create a batch file that calls “ss.exe” with the right parameters. Below is the file:

@echo off

IF %1==history GOTO lhistory
IF NOT %1==history GOTO lget

:lhistory
“c:\Program Files\Microsoft Visual SourceSafe\ss.exe” %*
GOTO lend

:lget
“c:\Program Files\Microsoft Visual SourceSafe\ss.exe” %* -GWS
GOTO lend

:lend

@echo on

So what does this? It looks at the first parameter of the command sent by the CC and if it is “history” then it would just call the “ss.exe” with the parameters received from CC otherwise it would add another parameter “-GWS”. Why the branch? because the history command does not support the option GWS and you’d get errors.

To use this just replace the name of the executable of VSS in your ccnet.config file to use the batch file and not “ss.exe”. Like this:

<executable>c:\Program Files\Microsoft Visual SourceSafe\SS.bat</executable>

Of course this can be further improved and the idea used for other purposes.

Happy integration!

This week I did alot of work with FormView and of course databinding when I encountered strange cases of data not being posted back to the business objects that it was bound to. It did give me a hard time but in the end the answer was simple. Take a look below:


<asp:formview ID=”frmAddress” runat=”server” DataSourceID=”odsAddress”>

     <ItemTemplate>

        <table cellspacing=”10″>

            <tr runat=”server” id=”trMainAddress”>

                <td style=”width:200px;” valign=”top”>

                    <b style=”font-size:large”>Main address:</b>

                </td>

                <td valign=”top”>

                    <asp:Textbox ID=”txtAddress” runat=”server”

                         Text=’<%# Eval(”AddressAsString”) %>‘>

                   </asp:Textbox >

                </td>

            </tr>

        </table>

    </ItemTemplate>

</asp:formview>

The reason was the striked out code at line 4. Because the table row has a runat attribute and an ID,  it is regarded as a server control.

An example on what happens can be easily understood by the syntax change for getting a refference to the textbox txtAddress:


// table row does not have runat and id

TextBox txt = (TextBox)frmLabelOnly.FindControl(“txtAddress”);

 

// table row has runat and id set

TextBox txt =

   (TextBox)(frmLabelOnly.FindControl(“trMainAddress”).FindControl(“txtAddress”));

 

In the case of the row having an id and runat attribute, the formview simply does not see the textbox because it’s on a level below the controls list. and cannot thus gather the information entered by the user and cannot send this data to the dataobject that it was bound to. And of course it can give you a massive headache :)

Cheers.

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

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!

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

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

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

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

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

I always hit a wall when trying to present the user with the possibility to enter a time (in format hh:mm or HH:mm). It ain’t an easy task and the sollutions are countless, but I won’t get into them. Instead I will unleash the power of the DateTimePicker upon you :).

(more…)