Archive for the “.NET” Category

Once upon a time in Developer Land, a developer was instructed to build a page that will show the great achievements of the ancients. He diligently started to create a model and used all that he could think of in order to make it good and make its employers proud. He added text and used nice fonts and alignment tags. He used lists to enumerate battles and deeds, and images to depict the stories.

The developer was good in his work and always printed his masterpieces at InternetExplorer’s shop because they were good friends and got to know each other well. And so his latest work got printed there also and it was looking marvelous.

Unfortunately this developer never got to read all 100 Commandments passed down to developers and stopped just short of 57 where it said:

“All tags should be finished by /> or </ …>”

But his friend, the apprentice from InternetExplorer shop knew him well, and if he found a tag not looking like it should he tried to make the best out of it and it was always good.

One day the employers hired a new developer and he was good also, but this one had read the commandments and even though he did not remember them all he had a tool that checked those rules and saw that in his colleague work an <img> tag was missing the end tag and he added it. When printing it at InternetExplorer shop it was looking fine. But there was you see something wrong, as this infamous tag was looking at first like this:

<img id=”imgAchievement” >

but after the second developer with his tool had modified it, it looked like this:

<img id=”imgAchievement” alt=”" />

Now the apprentice at InternetExplorer shop saw this but did not know where is the image that he should put in place and he said to himself that the developer erred and he went about his work and everything was good.

But one day a client said “I don’t like the guys at InternetExplorer shop and I want to use FireFox shop to print” and so he did, but there the apprentice of FireFox was a genius and knew all commandments and when looking at the <img> tag, he saw it was not saying where the image was and so he went about and did what he knew was right and showed there a picture of the whole artwork. But this was not good for the customer and so they tried to fix it but the developer could not speak with the apprentice from FireFox shop because they spoke different languages and only knew what the client said and so they struggled for what seemed to be an eternity.

Then the original developer remembered that a long time ago another client used to print this work at FireFox shop and that there was no problem and so he said “Why don’t we give this customer what I gave the customer from a long time ago ?”. And this was good ’cause the print was fine and wonderful and this because of one tiny thing. The old print had the old <img> tag which the apprentice from FireFox shop saw it was wrong and incomplete and ignored the troublemaker.

But our story does not end here because the new developer was a perfectionist and his proofing tool never failed and when he saw that the model was wrong again he modified it unaware of the troubles it would bring. A while later another client went and used the FireFox shop and the problems were there again. But this one was determined to find out why, and so he took the long journey to the city where FireFox Inc. had shop and through endless discussions and sign languages he found what the problem was, and then he was struck. He did not need that <img> tag, it was not doing anything but trouble and so he removed it and that model was still printed for years to come even on the shop of Safari Inc.

Conclusion

You see young developers we all must abide by the commandments, because by them work also the print apprentices ,and while some learn our habbits and move and make shop in other countries calling themselves FireFox 2 or FireFox 3.0.3 or Internet Explorer 6.1 or 7.0 they all know the commandments. And if we make the model by those commandments we can be sure the prints are as we envision them.

Comments 2 Comments »

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!

Comments No Comments »

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.

Comments No Comments »

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 8 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 »