Archive for May, 2011

WCF, Entity Framework and N-Tier Solutions – Part 1

Because of a new project at work, I have recently had the opportunity to do my first real WCF based project. It has been a great deal of fun and a learning experience as well. While doing the project of course, I have been doing a great deal of reading and web research. Over the course of the project, two main issues have come up.

1. How do I use WCF with the Entity Framework (Referred to hereafter as EF)
2. How do I use WCF in an n-tier project

So, with the caveat that I still have a lot to learn, so far here is what I have found on the subject.

 

#1 – The Entity Framework

Due to project requirements coming from the client, the Entity Framework needed to be the basis for my database access and it needed to be exposed via WCF so that multiple front end systems could use it. Initially, I was thinking that I could just expose my Entity Framework classes via WCF and be done with it, however in trying that I ran into several problems. Among other things, the Entity Framework would naturally expose a great deal more information that I am comfortable with. This is an issue for two reasons. The first is a matter of security, since the EF basically gives you the ability to perform almost any imagineable operation on your database. Depending on the operations that you want available through publicly viewable web services, that might not be a wise thing to do. Also, because of the sheer volume of methods exposed, you can end up with a lot more information going back and forth over the wire, which can affect performance.

 

#2 – N-Tier Architecture

I don’t think that this would be completely impossible with EF, but at the same time none of the tutorials that I found really demonstrated a good way of doing it. Most of them just wanted to show exactly how WCF and/or EF work using a basic example and were not concerned with showing an implementation of a full project using n-tier architecture and working together (which is perfectly understandable for the purposes of a tutorial). But when you are trying to use EF and WCF for the first time, even if you understand how each works individually, it is not easy to make them work together in an n-tier setting.

 

Solution

The solution to this problem, turned out to be something called “POCOs”. This term was new to me and understanding the concept took some additional reading. But simply put, POCOs stands for “Plain Old CLR Object”. In essence, what this solution involves is downloading and installing a template in Visual Studio that will connect to your EF .edmx file and create simple classes that map to your Entity Framework model and hence to your database. Once the template is created, you can edit and save it, which will in turn rerender your simple classes with the properties that you have specified. At first, I could not wrap my brain around how this worked, but I understand it now and have found it to be an excellent solution.

 
 

I did eventually get this working and I have written another post that explains the process in detail. It is very long and for that I apologize, but if you are trying to accomplish the same thing, perhaps too much detail is better than not enough. To read that post, click here.

Tags: , , ,


Mutually Exclusive CheckBoxListCheckBoxList Mutuamente Excluyentes

ASP.NET provides two useful server controls that allows one to choose from several available options, the CheckBoxList and RadioButtonList controls. The functionality of these controls is very similar and the primary difference is that the CheckBoxList allows multiple items to be selected where as the RadioButtonList only allows one item to be selected. There is one quirk with the RadioButtonList, once a selection is made it cannot be removed, by default. Recently a client asked if we could implement a CheckBoxList that included the the functionality of a RadioButtonList where a given option could be removed, but the options were mutually exclusive. Thanks to jQuery, implementing the desired behavior was relatively easy.

Below is an example of the HTML markup along with the jQuery code that was used.

<form id="frmOptions" runat="server">
<div class="divOptions">
    <asp:CheckBoxList ID="cblOptions" runat="server" class="cbl">
        <asp:ListItem Text="Option 1" Value="1" />
        <asp:ListItem Text="Option 2" Value="2" />
        <asp:ListItem Text="Option 3" Value="3" />
        <asp:ListItem Text="Option 4" Value="4" />
        <asp:ListItem Text="Option 5" Value="5" />
    </asp:CheckBoxList>
    <br />
    <br />
    <h3 class="subHeader" style="margin: 0">Note:</h3>
    <ul id="notes" style="margin-top: 0">
        <li>Clicking on any of the individual checkboxes, clears the previous selection.</li>
        <li>Clicking the same checkbox toggles the selection (default behavior).</li>
    </ul>
</div>
</form>
$(function () {
    // get all the checkboxes
    var $tblChkBox = $("table.cbl input:checkbox");

    // add a click handler to each checkbox
    $tblChkBox.click(function () {
        // get the id of the selected checkbox
        var selectedId = this.id;

        // uncheck all checkboxes except the selected one
        $tblChkBox.each(function () {
            if(this.id != selectedId) this.checked = false;
        });
    });
});

In this example, once the page loads and the document is ready, all the input elements of the checkbox type within the table are located based on the css class “cbl”. Note the checkboxlist renders as an HTML table. A click event handler is then added to each checkbox to clear the other checkboxes and the default toggle behavior of the selected checkbox is maintained.

If you’re new to jQuery, the Getting Started with jQuery tutorials are a good place to start. Rick Strahl also has a great introduction to jQuery article and the Learning jQuery site is excellent with categories/filters based on your skill level.ASP.NET proporciona dos controles de servidor útil que permite elegir entre varias opciones disponibles, los controles CheckBoxList y RadioButtonList. La funcionalidad de estos controles es muy similar y la diferencia principal es que el CheckBoxList permite que varios elementos para ser seleccionados en el RadioButtonList sólo permite un elemento a seleccionar. No es un capricho con el RadioButtonList, una vez que se realiza una selección que no se puede quitar, de forma predeterminada. Recientemente un cliente me preguntó si podíamos implementar un CheckBoxList que incluyó la funcionalidad de la de un RadioButtonList en que una opción dada eliminado, pero las opciones se excluyen mutuamente. Gracias a jQuery, la aplicación de la conducta deseada es relativamente fácil.

A continuación se muestra un ejemplo del código HTML, junto con el código jQuery que se utilizó.

<form id="frmOpcions" runat="server">
<div class="divOpcion">
    <asp:CheckBoxList ID="cblOpcions" runat="server" class="cbl">
        <asp:ListItem Text="Opción 1" Value="1" />
        <asp:ListItem Text="Opción 2" Value="2" />
        <asp:ListItem Text="Opción 3" Value="3" />
        <asp:ListItem Text="Opción 4" Value="4" />
        <asp:ListItem Text="Opción 5" Value="5" />
    </asp:CheckBoxList>
    <br />
    <br />
    <h3 class="subHeader" style="margin: 0">Nota:</h3>
    <ul id="notas" style="margin-top: 0">
        <li>Al hacer clic en cualquiera de las cajas de opciones individuales, se borra la selección anterior.</li>
        <li>Al hacer clic en la casilla de verificación activa o desactiva la misma selección (por defecto).</li>
    </ul>
</div>
</form>
$(function () {
    // conseguir todas las casillas de verificación
    var $tblChkBox = $("table.cbl input:checkbox");

    // agregar un controlador haga clic en cada casilla
    $tblChkBox.click(function () {
        // obtener el id de la casilla seleccionada
        var selectedId = this.id;

        // desactive todas las casillas excepto la seleccionada
        $tblChkBox.each(function () {
            if(this.id != selectedId) this.checked = false;
        });
    });
});

En este ejemplo, una vez que se carga la página y el documento está listo, todos los elementos de entrada del tipo de casilla en la tabla se encuentra basada en la clase CSS “CBL”. Tenga en cuenta la hace CheckBoxList como una tabla HTML. Un controlador de eventos haga clic entonces se agrega a cada casilla para desactivar las casillas de verificación de otros y el comportamiento por defecto de cambiar la casilla de verificación seleccionada se mantiene.

Tags: , , , ,


Debugging MS CRM 2011 IssueDebugging MS CRM 2011 Issue

I encountered an issue while attempting to use the JavaScript “debugger;” statement within a MS CRM 2011 script. If I have JavaScript that executes on the onChange event of a drop down, it seems to freeze my system and I never break into Visual Studio for debugging. The only way I’ve found to recover is to Ctrl-Alt-Delete and select “Log Off”. I usually get lucky and Windows brings up the screen telling me something is holding it up from logging off and I can select “Cancel” and get my system back. Of course there is a chance that it will log me off, so I save everything just in case. And, of course, I never get to step through the code the way that I want to…so I needed a workaround.

The workaround is to simply throw an alert on the line before the “debugger;” statement. For whatever reason that makes everything work just fine.

Hope this helps someone else.

Tags: , , , , , ,