Out of Sight, Out of Mind: JQuery Targets

JQuery provides a superb way of easily finding and manipulating elements.  But, if you don’t watch yourself, it can quickly become  quite dangerous and easily be broken.  For intance, imagine this file structure, with some example elements listed as its children.

Page
UC 1
- div class=”Target1″
UC2
- div class=”Target2″

and so on.  If the page were to do something like:

$(“.Target2″).find(“div.Child”).css(“display”, “none”);

You can imagine what would easily happen over time.  Some other developer modifies the page and removes that DIV completely because they didn’t even know about it.  As user controls get shared across pages, people may accidentally make a modifications to the user control in other pages, and as such, it breaks the page you were working in.

This is why I’m an advocate for utilizing JQuery plugins or widgets as much as possible.  The UC could create its own widget that registers itself with the page.  The page can then call the UC’s methods or do whatever it needs to do, instead of working with the internal elements directly.  Otherwise, you may find yourself  with broken code later on.  If you don’t like the plugin/widget approach, just try at least to keep all of the JS code that’s related to this user control within the user control’s body, or in a script file where it won’t be easily lost.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  .NET ,AJAX ,JavaScript ,JQuery May 20, 2011

Interacting Between Pages and UserControls in JavaScript

Anyone who develops on the web these days develops with JavaScript.  As applications become richer in capability, they need to rely on the functionality JavaScript has to offer, or seek another solution like Silverlight or WPF.  As ASP.NET web forms or MVC applications grow in size, functionality gets separated into separate classes, pages (views), user controls (partial views), etc.  When it comes to JavaScript, scripts can get separated between script in a page, script in a user control, script emitted from code or embedded JavaScript files, or even dynamically loaded JavaScript.

It’s easy to write JavaScript, but it can be hard to write it in a way that can be easily maintained inside an ASP.NET page that has 10-20 user controls.  One user control may use JQuery to find a control in another user control, and that user control talks to another user control.  It all works because at the time of coding everything was setup with a specific hierarchy.  But as soon as the user adds functionality or changes their mind on certain functionality, the structure changes, leaving the developer taking over the work with an array errors and a whole lot of mess.

Here are some tips to make these interactions across user controls more managable.  First, it may be best to control these interactions through a plugin.  For instance, we can start with a component in the page:

if (typeof(window["$p"]) === “undefined”) {
window["$p"] = (function() {
var ctls = {};

return {
addControl: function(name, ctl) {
ctls[name] = ctl;
}
};
})();
};

Within the user control, the user control can interface with the page by adding itself to the list of child controls of the page.

window["$uc1"] = (function() {
return {
init: function() {
if (typeof($p) !== “undefined”)
$p.addControl(“search”, this);
},

//set of functions to manage features of the user control
};
})();

The samples above would need to be tweaked some but this is a rough implementation.  Anyway, since we have an established hierarchy, the page can drive features within its user controls, or the user control can communicate certain actions and events by referencing the page through $p variable.

Loading Panels

For instance, with a loading panel that appears over the page, the page class can define methods to show and hide the loading panel, as in the following (assuming the display div is styled via CSS).

window["$p"] = (function() {
return {
.
.

showPanel: function() {
$(“#display”).show();
},

hidePanel: function() {
$(“#display”).hide();
}
})();

Events

Sometimes an event in the user control, the page needs to know about the event.  We can use the ASP.NET AJAX events framework via Sys.EventHandlerList component to register and fire events.  We can add events and methods to the user control as in:

window["$uc1"] = (function() {
var evt = new Sys.EventHandlerList();
return {
.
.

add_itemSelected: function(h) {
evt.addHandler(“itemSelected”, h);
},

remove_itemSelected: function(h) {
evt.removeHandler(“itemSelected”, h);
},

_onitemSelected: function(e) {
var h = evt.getHandler(“itemSelected”);
if (h) h(this, e);
},

init: function() {
//Add control event handler
//in event handler, fire _onitemSelected
}

//set of functions to manage features of the user control
};
})();

The page can attach an event handler and receive the bubbled notification.  Or, a callback or observer pattern could be used here too.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  AJAX ,JavaScript ,Web May 16, 2011

EF Drill-Through Properties

When using the entity objects generated by the Entity Framework, it’s tempting to utilize the drill-through properties available.  For instance, suppose you had this code sample (ctx is a reference to the ObjectContext).

var users = from u in ctx.Users

where u.IsActive == true

select u;

foreach (var u in users)

{

var recentPassword = u.UserPasswords.FirstOrDefault(i => i.IsActive == true);

if (recentPassword != null)

{

//Do something

}

}

It’s important to break this down to determine what’s happening with this code, minus the query (which is the simple part).

foreach (var u in users)

Upon looping, this first iteration actually executes the database query behind the scenes.  Simple enough.

var recentPassword = u.UserPasswords.FirstOrDefault(i => i.IsActive == true);

Here is where we have to be careful.  A reference to User.UserPasswords, which UserPasswords is a collection of children of the User entity, loads up all UserPassword objects related to that user, and then after all objects are loaded, the first object is retrieved that’s active.  So for each active user, we are loading all passwords from the database.  If we were to do:

var users = from u in ctx.Users

let rp = u.UserPasswords.FirstOrDefault(j => j.IsActive == true)

where u.IsActive == true

&& rp.IsActive == true

select u;

This statement translates to a SQL query with a subquery, and in this subquery, the passwords related to the user are queried.  All of the filtering has been done before us, and as long as we don’t need to access the UserPasswords directly, then this can suffice.  If we need the most recent record, we could also create an anonymous record:

var users = from u in ctx.Users

let rp = u.UserPasswords.FirstOrDefault(j => j.IsActive == true)

where u.IsActive == true

&& rp.IsActive == true

select { User = u, RecentPassword = rp };

In this scenario, the let statement performs a database subquery.  Each active user is represents by a property in the anonymous class, and we don’t need any future query loading.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  Uncategorized April 8, 2011

.NET Code vs. Custom Code

I recently created an MVP framework (http://nucleo.codeplex.com) that I was in the process of porting to a Silverlight 4 library for a project I’m working on.  As I was linking code to the project, I quickly realized that since the SIlverlight 4 is a subset of the .NET framework, I was running into issues with the custom code I was using, and this spurred off a philosophical debate in my mind: do I worry about creating my own custom components to handle the scenario, or do I refactor and leverage what’s already in the .NET framework?

I could very easily get caught into a whirlwind of wrappers, facades, and my own design of components to handle the situations I was dealing with.  I could also embed “if #SILVERLIGHT” everywhere to handle some of the scenarios I ran into.  On the other hand, if it’s already done for us in a way that requires some sacrifice of features or changes to the core code, is there value in this?  In reality, it depends.  Going to Silverlight, some components available in a web or windows app may not be in the Silverlight framework, forcing us to develop the feature we need anyway.  On some level, this is why developers create custom wrappers, facades, or adapters, because as environments change, certain framework code may or may not be present.  The converse can be true too: as environments change, our custom code could break, and using the framework would have prevented a refactoring.  In some ways, design can be a double-edged sword very quickly.  This of course depends on the type of application; a two-tier traditional web application may not need to be concerned, whereas an n-tier application may need to contemplate what it would take to share the middle layer to a variety of front-ends.

However, an environment change can consist of a change from waterfall to agile development, and as such TDD also becomes a factor in that design, an often reason for developers to approach the design with abstraction in our own code in the first place.  Those that come from an ASP.NET web forms background knows the ASP.NET framework is tightly-coupled with the web and as such is harder to test, unless you resort to wrappers of services, etc.  One of the core features I saught to implement in my framework was wrappers for the various services a developer may use; sure, HttpContextBase base class is nice, but  it tends to be tightly coupled with the web, and as such, a wrapper to expose one small portion of functionality comes in really handy here.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  .NET ,Web March 5, 2011

Entity Framework 4 and Tracing Queries

As you probably know, the Entity Framework 4 feature translates LINQ queries to SQL to execute in the backend.  However, what Entity Framework may render a SQL query that looks much different.  Entity Framework’s SQL query building process may involve the use of subqueries, nested joins, or any other construct.  

 

var ctx = new AdventureWorksObjectContext();

var results = from a in ctx.Addresses
     where a.StateProvince.StateProvinceCode == “PA”
     && a.CustomerAddresses.Count > 0
    select a;

This query, a LINQ query against the AdventureWorks database, queries a collection of Address objects.  Even though the signature of the query is IQueryable<Address>, the underlying constructs actually are an ObjectQuery<Address> instance.  The ObjectQuery is useful for many things; one of those is the ToTraceString method.  This method returns the underlying SQL query that was executed against the database.  It;s very easy to call, as shown below:

var query = results as ObjectQuery<Address>;
this.lblSQL.Text = query.ToTraceString();

 

The underlying SQL query appears below.  Notice how simple the LINQ query structure is setup above.  In the query above, the LINQ query makes it very easy to drill through two primary key references, from Address to the StateProvince and StateProvinceCode tables, as well as a CustomerAddresses subquery.  The query renders as the following:

 

SELECT [Project1].[AddressID] AS [AddressID], 

[Project1].[AddressLine1] AS [AddressLine1], 

[Project1].[AddressLine2] AS [AddressLine2], 

[Project1].[City] AS [City], 

[Project1].[StateProvinceID] AS [StateProvinceID], 

[Project1].[PostalCode] AS [PostalCode], 

[Project1].[rowguid] AS [rowguid], 

[Project1].[ModifiedDate] AS [ModifiedDate] 

FROM 

  SELECT [Extent1].[AddressID] AS [AddressID], 

  [Extent1].[AddressLine1] AS [AddressLine1], 

  [Extent1].[AddressLine2] AS [AddressLine2], 

  [Extent1].[City] AS [City], 

  [Extent1].[StateProvinceID] AS [StateProvinceID], 

  [Extent1].[PostalCode] AS [PostalCode], 

  [Extent1].[rowguid] AS [rowguid], 

  [Extent1].[ModifiedDate] AS [ModifiedDate], 

  [Extent2].[StateProvinceCode] AS [StateProvinceCode], 

  (

    SELECT COUNT(1) AS [A1] 

    FROM [Sales].[CustomerAddress] AS [Extent3] 

    WHERE [Extent1].[AddressID] = [Extent3].[AddressID]

  ) AS [C1] 

  FROM [Person].[Address] AS [Extent1] 

  INNER JOIN [Person].[StateProvince] AS [Extent2] 

  ON [Extent1].[StateProvinceID] = [Extent2].[StateProvinceID] 

) AS [Project1] 

WHERE (N’PA’ = [Project1].[StateProvinceCode]) 

AND ([Project1].[C1] > 0) 

It’s very handy to verify the underlying SQL, using either this construct, or a database profiling tool.

 

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  Entity Framework January 28, 2011

Visual Studio Find References and "var"

I really love the “var” keyword because it simplifies the code.  Var can be switched from one type to another without any potential code changes (as long as the signatures match), and all of this is referenced at compile time.  But i noticed a side-effect with var within Visual Studio.  Right-clicking find all references of a specific type missed a reference to a type because of var.  Instead of actually looking up the type, Find references matches the type by name, and as such, var can be easily missed within the found results.  So while the var keyword makes future code changes a breeze and reduces code, there are some editor-specific fallbacks to it.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

1 comment Posted in  Visual Studio January 15, 2011

Understanding View Events in the MVP Pattern

Being that I’ve been undertaking several Model-View-Presenter projects, I’m writing this post to illustrate the way a view uses an event.  In the Model View Presenter pattern, the primary means a view communicates with the presenter is using events.  Methods of the view can be called from the presenter, but typically I’ve seen mostly events.  An event signals that some action is happening within the system.  The user saved a record, selected an object, cancelled their changes, etc.   These actions translate from a button click, etc. in the UI to the view passing up a corresponding event to the presenter.  The presenter only knows about the view’s events through the view’s interface, which, of course, the view has to implement.  Since the view is required to implement X event, X event can be listened to in the presenter, and this completes the first round of the process.

Be careful that you understand the reasoning for the event; the event is not used solely to serve the presenter.  For instance, if the view attempts to load data on demand solely for pushing data to the view, its not the responsibility of the view to do this necessarily; the presenter is the controller driving what happens during the request; the view is responsible for managing the UI.

For instance, suppose that this happened in the view:

protected override void OnLoadReferenceData(EventArgs e)
{
    var args = new DataEventArgs();
    if (LoadReferenceData != null)
        LoadReferenceData(args);

    //Commence with loading the data here
}

In this example, who is in control of the process?  The presenter is supposed to be in control, but the view oversteps its bounds and starts making demands for its needs.  In this way, we can circumvent the presenter from performing the responsibilities it is supposed to be performing.  This is especially true if we see many On<X> methods, each loading a portion of its data.  Why do I say this?  The presenter can become a data access class, primarily serving the view, rather than controlling the flow of the process, and having the presenter load and push down data at the right time through the model.

Playing devil’s advocate, can there be times when view loading of demand is needed?  Certainly.  Can a view load the data directly from event args, instead of the model.  Sure, however, I would recommend to leave the presenter as the sole responsibility over the process, otherwise the view and presenter may become chaotic to maintain.

So what is essentially the difference between the two?  On one level, its grammar.  A view event named RefreshPage appears differently to the user than LoadData or NeedData.  It can also be by action; if the view fires an event and immediately loads its data from the event args, then what is the presenter really doing?  Is it controlling the process, or is it a data access layer?  Does the view respond to the model passed from the presenter?  This is a proper way for the communication chanel.

Some food for thought.  I would love to hear your opinion.  Please comment using the form below.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  .NET December 24, 2010

Issue with RadComboBox Drop Down

In the interest of standardization, the RadComboBox allows a custom CSS clas to be specified for the dropdown, via the DropDownCssClass property (as if you probably couldn’t figure that one out :-D ).  In an application I’m working on, we have a set of pre-built CSS classes of varying sizes, and we apply styles to the drop down to be consistent.  However, after applying the style, it didn’t quite seem to take affect.  This is because the CSS for the RadCombo looked something like the following:

<div class=”.. Telerik CSS Classes .. MyDropDownClass”>
    <div class=”rcbScroll rcbSlide” style=”… height:380px;”>

I don’t know where it got the 380 px, but then changing my CSS to:

.MyDropDownClass
{
    width: 250px;
    max-height:300px;
}

.MyDropDownClass > rcbScroll
{
    max-height:300px;
}

Did the trick for me.  May need to adjust slightly, as I haven’t fully tested cross browser.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

1 comment Posted in  Web December 20, 2010

Nucleo Presentation and AJAX

In continuing the series on the Nucleo MVP framework, we’re going to look at how easy it may be to use AJAX.  Like the web services proxy generation to the server-side web server, the Nucleo MVP currently supports limited AJAX proxy support (with more support to come).  Using the Nucleo.Web.MVP framework, the project and the BaseWebPresenter presenter class, a client-side proxy can be generated to call server-side static methods first by adding the following attribute:

 [PresenterAjax(EnableWebMethods = true)]
public class AjaxCallbackPresenter : BaseWebPresenter<IAjaxCallbackView>

The EnableWebMethods setting triggers a look for the [PresenterWebMethod] attribute on a static method.  The process would find the following two methods:

 [PresenterWebMethod]
public static void AddItem(string item)
{
 List<string> items = HttpContext.Current.Cache.Get(“Items”) as List<string>;
 if (items == null)
  items = new List<string> { };

 items.Add(item);

 HttpContext.Current.Cache["Items"] = items;
}

[PresenterWebMethod]
public static List<string> GetItems()
{
 List<string> items = HttpContext.Current.Cache.Get(“Items”) as List<string>;
 if (items != null)
  return items;

 return new List<string> { “A”, “B”, “C”, “D”, “E” };
}

The PresenterWebMethod attribute points these two methods as methods to be proxied in client-side JavaScript.  Right now, the methods have to be static; though, I am working on adding to the process the ability to talk to instance methods too.  At runtime, the n$.Presenters collection contains our AJAX presenter, and renders a proxy for the two methods, AddItem and GetItems.  We can see this in the works through the following proxy:

n$.Presenters["AjaxCallbackPresenter"] = (function() {
return {
 AddItem: function(item, successCallback, failedCallback) { .. },
 GetItems: function(successCallback, failedCallback) { .. }
};
})();

The proxy makes a web request to a handler that invokes the corresponding presenter on the server, which happens the following way:

 n$.Presenters["AjaxCallbackPresenter"].GetItems(function (response) {
       $get(“<%= lblOutput.ClientID %>”).innerHTML = response.data.toString();
});

 n$.Presenters["AjaxCallbackPresenter"].AddItem($get(“<%= txtValue.ClientID %>”).value, function (response) {
 updateLabel();
 $get(“<%= txtValue.ClientID %>”).value = “”;
});

And as such, we have client/server integration to the presenter, just like ASP.NET MVC or  web services/page methods.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

3 comments Posted in  Nucleo December 18, 2010

Understanding the Separation of Concerns with the MVP framework

I’ve been using the MVP pattern for a new project and have developed an open-source framework (available here).  I’m not an MVP expert, but I’ve learned a lot about the pattern and UI patterns at a whole.  One important idea about the pattern that I’ve learned is to ensure that the layers are properly separated.  For instance, some of the errors that happen in the framework happen because the proper separation of concerns is violated, which can lead to a harder-to-maintain application, bugs, or application errors.  A good understanding of this separation is important.

The presenter itself is responsible for:

 

  • computational logic generated by business rules
  • validation rules that fire across the domain to ensure some business rule related to other data in the database is in a correct state
  • loading of data that the view will use
  • communicating with other presenters

 

The view itself is responsible for:

 

  • Binding model data to the UI
  • Managing the UI

 

There are some gray areas to evaluate, such as the following:

  • Should the view request data from the presenter via an event?
  • Should the view be reactive to the existence of data in the model, or should code to bind to the view fire after an event happens?

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Add comment Posted in  Nucleo ,Web November 20, 2010

Next Posts Previous Posts


Social Media

Stackoverflow Flair

Search For

Most Viewed