Design Decision - Javascript array or http handler - asp.net

I'm building a Web Page that allows the user to pick a color and size. Once they have these selected I need to perform a lookup to see if inventory exists or not and update some UI elements based on this.
I was thinking that putting all the single product data into multidimensional JavaScript array (there is only 10-50 records for any page instance) and writing some client side routines around that, would be the way to go for two reasons. One because it keeps the UI fast and two it minimizes callbacks to the server. What i'm worried about with this solution is code smell.
As an alternative i'm thinking about using a more AJAX purist approach of using HTTP handlers and JSON, or perhaps a hybrid with a bit of both. My question is what are your thoughts as to the best solution to this problem using the ASP.Net 2.0 stack?
[Edit]
I also should mention that this page will be running in a SharePoint environment.

Assuming the data is static, I would vote option #1. Storing and retrieving data elements in a JavaScript array is relatively foolproof and entirely within your control. Calling back to the server introduces a lot of possible failure points. Besides, I think keeping the data in-memory within the page will require less code overall and be more readable to anyone with a more than rudimentary understanding of JavaScript.

i'm against Ajax for such tasks, and vote (and implemented) the first option.
As far as I understand, you won't create Code smells if the JS part is being written by your server-side.
From a user point-of-view, Ajax is an experience-killer for wireless browsing, since any little glitch or mis-service will fail or simply lengthen the interaction by factors of 20(!).
I've implemented even more records than yours in my site, and the users love it. Since some of my users use internet-caffee, or dubious hotel wifi, it wouldn't work otherwise.
Besides, Ajax makes your server-vs-client interaction code much more complex, IMO, which is the trickiest part in web programming.

I would go with your second option by far. As long as the AJAX call isn't performing a long running process for this case, it should be pretty fast.
The application I work on does lots with AJAX and HttpHandler, and our calls execute fast. Just ensure you are minimizing the size of your JSON returned in the response.

Go with your second option. If there are that few items involved, the AJAX call should perform fairly well. You'll keep your code off the client side, hopefully prevent any browser based issues that the client side scripting might have caused, and have a cleaner application.
EDIT
Also consider that client side script can be modified by the user. If there's no other validation occuring to the user's selection, this could allow them to configure a product that is out of stock.

Related

ASP.NET AJAX Progress Indication with Async Server Calls

I know this question has been asked before..a lot in fact. But I can't seem to get the wheels turning on this thing. To be honest I'm a bit lost on mating client side and server scripting and the examples I've seen are either far to simplistic or way above my head.
Goal:
My goal is to take a long running process I've writtin in VB.NET on the server, which happens to be loop based, and calculate a percentage complete (I know the range of the index values) and relay that back to the user by some means.
Idea:
As the loop iterates I want to pass back up to the client an integer of percent complete or poll it from the client.
What I've done:
Is very limited, I have little to no experience here, I've been doing a lot of googling and I've played with the UpdatePanel and UpdateProgress controls from AJAX a bit, but this method so far seems to lean towards an idicator, like GIF.
As always any help is appreciated, and if I can answer any questions I will.
Have you considered using an inline frame (iFrame) to host your long running process and report back status to the client via the Response object of the long running .aspx page?
If so, then I suggest you read Easy incremental status updates for long requests.
The example uses a button as the display for the progress after the user clicks it, but you could direct output to another DOM element if you wish.

Mustache.js vs Mustache.net. What is faster?

I'm developing a web-site with ASP.NET 4.0. Some pages need to get data from the server via AJAX requests (for instance, a list of items, sorted or/and filtered by a parameter). And there I can see two options for templating:
1) AJAX handler get data from database and templates it with Mustache. Returns html code ready to display to the end user.
2) AJAX handler get data from database and sends it as JSON. Javascript code formats data with Mustache on the client-side.
My question is what will perform faster?
I don't think your question can be answered without testing, but I'm not sure the difference would be really significant. However, raw speed notwithstanding, I would go probably for option 2:
HTTP traffic will certainly be lighter with your JSON-formatted data rather than a complete HTML output (this is generally better),
The data can still be handled dynamically on the client side
If your website is designed as a "web application", with an emphasis on client-side processing, this is the way to go. But on the other hand, if you think of your output as something mainly static, it is probably simpler to keep all the work on the server side.

Google Geocoding Recommendation

I am looking into utilizing Google Maps API to do some geocoding. I want to implement client side geocoding, to remove the possibility of request limitation.
I need to do some fairly complex logic on the result set, and I would prefer to do that in C# as it is a ASP.NET MVC application. However part of that logic is possibly makeing subsequent follow up requests and that again would require JavaScript.
So, my first thought is to make a service in my application to pass JSON results to and certain return types to trigger the subsequent request. That seems a little convoluted and want to know from the community if this seems like the best approach and if there are any libraries/third party tools that can help handle this situation.
I've an app that does something similar, with the complexity somewhat decoupled by using standardized events (within this app, not a W3 standard or anything)
Client uses native geolocation, SimpleGeo and Google Loader to guess where the user is and AJAX's that to the server.
Server uses client data, MaxMind, and user preferences to decide where to treat the user as being.
Server response is generic event data (as JSON response) that is converted by a generic AJAX response handler into one or more events triggered against the body element.
Depending on the page, various listeners are bound to the events and or namespaces (see jQuery namespaced events) and they handle the updated location events, e.g., getting different weather data, changing local search results
Some of those listeners in turn trigger other AJAX requests, the responses to those may also carry generic events to triggered...
This way there's no sequential code I have to write, i.e., I can add or remove behaviors (simple or complex) without changing anything else. jQuery Events are all I use, really nothing much to it after you decide how you'll pattern things.
Let me know if that's interesting to you and you want me to expand or clarify a part of it.
You may want to try this API:
http://code.google.com/apis/maps/documentation/geocoding/
It's far more REST like - no Javascript required. May work better with C#
In the end I found the best solution was to do as I stated in my question. Pass the JSON object to controller, do work, then return. Worked pretty well.

ASP.NET MVC 2 - best implementation of status / update / generic message delivery and JavaScript modal display

For an MVC 2 app that relies on many partial views and almost exclusively uses Ajax for POSTs/GETs, what would be the best way to implement the setting, passing, retrieval and display (using a JavaScript modal) of these messages?
My forms all POST (by way of jQuery $.ajax) to actions that return partial views (html) that are used to update a in the "success:" part of the $.ajax function.
I was hoping for some sort of mechanism in the master view that could "listen" for any messages that any of these partial views might be "delivering"--through their ViewData, for instance.
Thanks.
Edit:
After lots more searching, I found similar people trying to achieve the same thing as me, but none of the questions had a good answer. This one states the question best.
Your "master view" wouldn't be able to have a mechanism like what you're thinking of simply because you're asking it to be aware of potential data that could be given to it based on a possible user interaction.
What I think #cottsak is trying to say is to have delegate functions in your JS code that handle error and success events. Thus you can have 100 Ajax requests but only 2 functions actually handling the response. Within these functions you'll have to normalize the way you deal with the responses so that you don't have to write conditionals for specific forms for example. This might require normalizing your forms to have identical structures and base functionality and differ only on their input content.
For example I use "Wizards" in some of my sites that deal with modal forms:
<div class="Wizard">
<form>
<!-- Any and all possible content -->
</form>
</div>
All my forms of course differ on the actual inputs they have, but they're all normalized in the sense that there's dedicated elements in them for messaging and such. Every single form however is controlled by the same JS with a few exceptions for special scenarios.
You should take a look at the Dropbox web interface. Get yourself a free account and use the interface for 10 mins - copy, move, delete a file. The messaging and validation system is great. And it's largely ajax on their site too. Perfect example of the user experience you want it sounds like.
As for the technical implementation, i have been thinking about this for some time:
I'd use a broker system on the client for which all page ajax requests go through. This way all responses can be collated within a single function (/object, however you design it) and thus the responses too. It's obviously the responses that are key so that Error messages and Status messages can be handled in the same place and rendered to the user in a uniform way.
Server side it wouldn't be too hard. I'd suggest that you have a graceful degradation solution to those actions that return JSON or other ajax responses, in that they can function (and return Error/Status messages) without the client having JavaScript enabled.

Best Practices for Passing Data Between Pages

The Problem
In the stack that we re-use between projects, we are putting a little bit too much data in the session for passing data between pages. This was good in theory because it prevents tampering, replay attacks, and so on, but it creates as many problems as it solves.
Session loss itself is an issue, although it's mostly handled by implementing Session State Server (or by using SQL Server). More importantly, it's tricky to make the back button work correctly, and it's also extra work to create a situation where a user can, say, open the same screen in three tabs to work on different records.
And that's just the tip of the iceberg.
There are workarounds for most of these issues, but as I grind away, all this friction gives me the feeling that passing data between pages using session is the wrong direction.
What I really want to do here is come up with a best practice that my shop can use all the time for passing data between pages, and then, for new apps, replace key parts of our stack that currently rely on Session.
It would also be nice if the final solution did not result in mountains of boilerplate plumbing code.
Proposed Solutions
Session
As mentioned above, leaning heavily on Session seems like a good idea, but it breaks the back button and causes some other problems.
There may be ways to get around all the problems, but it seems like a lot of extra work.
One thing that's very nice about using session is the fact that tampering is just not an issue. Compared to passing everything via the unencrypted QueryString, you end up writing much less guard code.
Cross-Page Posting
In truth I've barely considered this option. I have a problem with how tightly coupled it makes the pages -- if I start doing PreviousPage.FindControl("SomeTextBox"), that seems like a maintenance problem if I ever want to get to this page from another page that maybe does not have a control called SomeTextBox.
It seems limited in other ways as well. Maybe I want to get to the page via a link, for instance.
QueryString
I'm currently leaning towards this strategy, like in the olden days. But I probably want my QueryString to be encrypted to make it harder to tamper with, and I would like to handle the problem of replay attacks as well.
On 4 guys from Rolla, there's an article about this.
However, it should be possible to create an HttpModule that takes care of all this and removes all the encryption sausage-making from the page. Sure enough, Mads Kristensen has an article where he released one. However, the comments make it sound like it has problems with extremely common scenarios.
Other Options
Of course this is not an exaustive look at the options, but rather the main options I'm considering. This link contains a more complete list. The ones I didn't mention such as Cookies and the Cache not appropriate for the purpose of passing data between pages.
In Closing...
So, how are you handling the problem of passing data between pages? What hidden gotchas did you have to work around, and are there any pre-existing tools around this that solve them all flawlessly? Do you feel like you've got a solution that you're completely happy with?
Thanks in advance!
Update: Just in case I'm not being clear enough, by 'passing data between pages' I'm talking about, for instance, passing a CustomerID key from a CustomerSearch.aspx page to Customers.aspx, where the Customer will be opened and editing can occur.
First, the problems with which you are dealing relate to handling state in a state-less environment. The struggles you are having are not new and it is probably one of the things that makes web development harder than windows development or the development of an executable.
With respect to web development, you have five choices, as far as I'm aware, for handling user-specific state which can all be used in combination with each other. You will find that no one solution works for everything. Instead, you need to determine when to use each solution:
Query string - Query strings are good for passing pointers to data (e.g. primary key values) or state values. Query strings by themselves should not be assumed to be secure even if encrypted because of replay. In addition, some browsers have a limit on the length of the url. However, query strings have some advantages such as that they can be bookmarked and emailed to people and are inherently stateless if not used with anything else.
Cookies - Cookies are good for storing very tiny amounts of information for a particular user. The problem is that cookies also have a size limitation after which it will simply truncate the data so you have to be careful with putting custom data in a cookie. In addition, users can kill cookies or stop their use (although that would prevent use of standard Session as well). Similar to query strings, cookies are better, IMO, for pointers to data than for the data itself unless the data is tiny.
Form data - Form data can take quite a bit of information however at the cost of post times and in some cases reload times. ASP.NET's ViewState uses hidden form variables to maintain information. Passing data between pages using something like ViewState has the advantage of working nicer with the back button but can easily create ginormous pages which slow down the experience for the user. In general, ASP.NET model does not work on cross page posting (although it is possible) but instead works on posts back to the same page and from there navigating to the next page.
Session - Session is good for information that relates to a process with which the user is progressing or for general settings. You can store quite a bit of information into session at the cost of server memory or load times from the databases. Conceptually, Session works by loading the entire wad of data for the user all at once either from memory or from a state server. That means that if you have a very large set of data you probably do not want to put it into session. Session can create some back button problems which must be weighed against what the user is actually trying to accomplish. In general you will find that the back button can be the bane of the web developer.
Database - The last solution (which again can be used in combination with others) is that you store the information in the database in its appropriate schema with a column that indicates the state of the item. For example, if you were handling the creation of an order, you could store the order in the Order table with a "state" column that determines whether it was a real order or not. You would store the order identifier in the query string or session. The web site would continue to write data into the table to update the various parts and child items until eventually the user is able to declare that they are done and the order's state is marked as being a real order. This can complicate reports and queries in that they all need to differentiate "real" items from ones that are in process.
One of the items mentioned in your later link was Application Cache. I wouldn't consider this to be user-specific since it is application wide. (It can obviously be shoe-horned into being user-specific but I wouldn't recommend that either). I've never played with storing data in the HttpContext outside of passing it to a handler or module but I'd be skeptical that it was any different than the above mentioned solutions.
In general, there is no one solution to rule them all. The best approach is to assume on each page that the user could have navigated to that page from anywhere (as opposed to assuming they got there by using a link on another page). If you do that, back button issues become easier to handle (although still a pain). In my development, I use the first four extensively and on occasion resort to the last solution when the need calls for it.
Alright, so I want to preface my answer with this; Thomas clearly has the most accurate and comprehensive answer so far for people starting fresh. This answer isn't in the same vein at all. My answer is coming from a "business developer's" standpoint. As we all know too well; sometimes it's just not feasible to spend money re-writing something that already exists and "works"... at least not all in one shot. Sometimes it's best to implement a solution which will let you migrate to a better alternative over time.
The only thing I'd say Thomas is missing is; client-side javascript state. Where I work we've found customers are coming to expect "Web 2.0"-type applications more and more. We've also found these sorts of applications typically result in much higher user satisfaction. With a little practice, and the help of some really great javascript libraries like jQuery (we've even started using GWT and found it to be AWESOME) communicating with JSON-based REST services implemented in WCF can be trivial. This approach also provides a very nice way to start moving towards a SOA-based architecture, and clean separation of UI and business logic.
But I digress.
It sounds to me as though you already have an application, and you've already stretched the limits of ASP.NET's built-in session state management. So... here's my suggestion (assuming you've already tried ASP.NET's out-of-process session management, which scales signifigantly better than the in-process/on-box session management, and it sounds like you have because you mentioned it); NCache.
NCache provides you with a "drop-in" replacement for ASP.NET's session management options. It's super easy to implement, and could "band-aid" your application more than well enough to get you through - without any significant investment in refactoring your existing codebase immediately.
You can use the extra time and money to start reducing your technical debt by focusing new development on things with immediate business-value - using a new approach (such as any of the alternatives offered in the other answers, or mine).
Just my thoughts.
Several months later, I thought I would update this question with the technique I ended up going with, since it has worked out so well.
After playing with more involved session state handling (which resulted in a lot of broken back buttons and so on) I ended up rolling my own code to handle encrypted QueryStrings. It's been a huge win -- all of my problem scenarios (back button, multiple tabs open at the same time, lost session state, etc) are solved and the complexity is minimal since the usage is very familiar.
This is still not a magic bullet for everything but I think it's good for about 90% of the scenarios you run into.
Details
I built a class called CorePage that inherits from Page. It has methods called SecureRequest and SecureRedirect.
So you might call:
SecureRedirect(String.Format("Orders.aspx?ClientID={0}&OrderID={1}, ClientID, OrderID)
CorePage parses out the QueryString and encrypts it into a QueryString variable called CoreSecure. So the actual request looks like this:
Orders.aspx?CoreSecure=1IHXaPzUCYrdmWPkkkuThEes%2fIs4l6grKaznFGAeDDI%3d
If available, the currently logged in UserID is added to the encryption key, so replay attacks are not as much of a problem.
From there, you can call:
X = SecureRequest("ClientID")
Conclusion
Everything works seamlessly, using familiar syntax.
Over the last several months I've also adapted this code to work with edge cases, such as hyperlinks that trigger a download - sometimes you need to generate a hyperlink on the client that has a secure QueryString. That works really well.
Let me know if you would like to see this code and I will put it up somewhere.
One last thought: it's weird to accept my own answer over some of the very thoughtful posts other people put on here, but this really does seem to be the ultimate answer to my problem. Thanks to everyone who helped get me there.
After going through all the above scenarios and answers and this link Data pasing methods My final advice would be :
COOKIES for:
ENCRYPT[userId's]
ENCRYPT[productId]
ENCRYPT[xyzIds..]
ENCRYPT[etc..]
DATABASE for:
datasets BY COOKIE ID
datatables BY COOKIE ID
all other large chunks BY COOKIE ID
My advise also depends on the below statistics and this link details Data pasing methods :
I would never do this. I have never had any issues storing all session data in the database, loading it based on the users cookie. It's a session as far as anything is concerned, but I maintain control over it. Don't give up control of your session data to your web server...
With a little work, you can support sub sessions, and allow multi-tasking in different tabs/windows.
As a starting point, I find using the critical data elements, such as a Customer ID, best put into the query string for processing. You can easily track/filter bad data coming off of these elements, and it also allows for some integration with e-mail or other related sites/applications.
In a previous application, the only way to view an employee or a request record involving them was to log into the application, do a search for the employee or do a search for recent records to find the record in question. This became problematic and a big time sink when somebody from a related department needed to do a simple view on records for auditing purposes.
In the rewrite, I made both the employee Id, and request Ids available through a basic URL of "ViewEmployee.aspx?Id=XXX" and "ViewRequest.aspx?Id=XXX". The application was setup to A) filter out bad Ids and B) authenticate and authorize the user before allowing them to these pages. What this allowed the primarily application users to do was to send simple e-mails to the auditors with a URL in the e-mail. When they were in a big hurry, they were in their bulk processing time, they were able to simply click down a list of URLs and do the appropriate processing.
Other session related data, such as modification dates and maintaining the "state" of the user's interaction with the application gets a little more complex, but hopefully this provides a starting poing for you.

Resources