Using .aspx pages as an HTML template outside of an ASP.NET 3.5 HTTP request - asp.net

I need to generate a block of HTML for use by an asynchronous operation triggered by an HTTP request (I am calling the Facebook API in response to an HTTP request, with the HTML block as a parameter). I already have an .aspx page that generates the HTML required, and would like to reuse that code.
I see three options, none of which I want to do:
Re-write the functionality currently in the .aspx page into a .NET function that returns the HTML. I don't want to spend the time re-writing it unless absolutely necessary. Also, the .NET code to produce the HTML will be much less maintainable than the .aspx markup to do so (yes, even with XML literals).
When I need the block of HTML, make an HTTP request to the .aspx page on the local server. The inefficiency of this does not concern me, but the design compromise does. Because of how the application is structured, I would have to litter my .aspx code with:
if(localRequest)
{doOneThing();}
else
{doTheOtherThing();}
which I don't want to do.
Create an ASP.NET application host to spit out these chunks of HTML. I'd imagine that this would improve on the efficiency of 2, but not the complexity.
Are there other alternatives? The ideal would be instantiating the .aspx page class and executing it with a mocked up HttpRequest or HttpContext. Can this be done, and is it worth the hassle?

There are two related but distinct parts to this problem:
a) how do you ensure that an asynchronous operation has a valid HttpContext?
b) how can you get the HTML output of an ASPX execution returned as a string?
For (a), it depends on how you're invoking the async operation. Unfortunately, in .NET there are quite a few ways to do async operations. But if you want to propagate HttpContext to the async code, there's only one good option: the Event-based Asynchronous Pattern. Although IMHO the event-based async pattern has some drawbacks (e.g. no "wait" operations, hard to sync multiple threads, need to refactor your code, etc.) it does a really cool thing of integrating cleanly with ASP.NET async pages and ensuring that the right context is set up when your callback gets control.
So in other words, propagating context only works (without doing a lot of extra work, that is) if you're playing by the rules set up for ASP.NET Async Pages. Here's an article on async pages if you're not familiar. Here's another post that is useful. In a nutshell, you split page processing into three stages:
1) set up for long-running operations
2) kick off long-running operations (e.g. to get your expensive data)
3) ASP.NET will call your Page_PreRenderComplete handler once all long-running operations are complete. from here, you can bind your data and render your HTML.
What may make this hard is that often you'll need to re-factor existing code since you need to segregate fetching the data from binding the data.
Now, on to (b) above: once you have context, the other question is how to get your page output into a string. There are a few ways to do this too, but perhaps the easiest is to encapsulate the stuff you want to output into a user control (.ASCX) and then follow the instructions in this blog post: http://stevesmithblog.com/blog/render-control-as-string/. See this post if you need data binding too.

Related

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.

How increase the performance of asp.net application?

Hi
I want to increase the performance of asp.net application when multiple user access my application about 5000 users.
Can we do this
Your ASP.NET application performance depends on various things. You can improve your site's performance by doing various stuff. Your questions is very subjective and of course the answer would be some best practices about improving ASP.NET applications' performance.
I have gathered some tips from the net. Unfortunately, I cannot remember where. Search on any item and you will find many resources that can help you implement it:
Use Cache:
Page output caching.
Page fragment caching.
Data caching.
Avoid frequent trips to database.
Use DB-level paging. Don't retrieve unnecessary data that's not going to be shown in the current page.
Be careful with Session variables. Usually, you should avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.
Select the Release mode before making the final Build for your application.
Set debug=false under compilation: <compilation default Language="c#" debug="false">
Avoid Inline JavaScript and CSS
Use Finally Method to kill resources. (But not in the case of using)
Avoid Exceptions: Use If condition (if it is check proper condition)
Check “Page.IsPostBack”. To avoid repetition code execution.
Use single css file instead of multiple css file.
Use Client-Side Validation. (but not all the time you have to validate even on the server side).
Turn off Tracing unless until required.
Turn off Session State, if not required.
Disable ViewState when not required.
Try to use StringBuilder instead of string.
It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location.
Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.
Avoid using code like x = x +1; it is always better to use x+=1.
Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned. But that depends on you deciding to balance between features/performance.
Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.
Reduce cookie size.
Compress CSS, JavaScript and Images.
Use server side compression software such as Port80s
Make your page files as light as possible. That is try to avoid unnecessary markups, e.g. use div elements instead of tables.
Write static messages in div and make it visible when necessary. This is faster than letting server set Text property of your label or div.
Retrieve necessary data from database at once, if possible. Don't add up to database trip as far as possible. For this, combine the datafields from different tables and select them.
Remove blank spaces from your html it will increase your kb. You can use regular expression to remove white spaces. I will post the code for removing white spaces next posts.
For asp.net 2.0 and higher version use master pages. It will increase your performance.
Use ADO.NET asynchronous calls for ado.net methods. asp.net 2.0 or higher version is supporting your performance. If you are using same procedure or command multiple time then use ADO.NET Prepare command it will increase your performance.
Do IIS performance tuning as per your requirement.
Disable view state for your controls if possible. If you are using asp.net 2.0 or higher version then use asp.net control state instead of view state. Store view state in session or database by overriding the default methods for storing view state
Use Ajax for your application wisely. Lots of Ajax calls for a page will also decrease your performance.
Call web service from java script instead of server side. Use asynchronous calls to call a web method from web service.

Problems with ASP.NET Session State / NInject / OnePerRequest behavior

This is quite a lengthy post, so bear with me. I'm not sure whether it is primarily about ASP.NET Session State behaviour, NInject, application design, or refactoring. Read on and then you can decide... :-)
Background
First, a bit of background. We are working on trying to refactor a large webshop into a more maintainable , structured design. The webshop is currently running on .NET 3.5, but the design is more of a hangover from the classic ASP days. Obviously we cannot tackle everything in one go, so many of the features / technologies / approaches have to be taken as a given. With that in mind...
The app maintains everything to do with the current session (user profile, cart, session choices, etc.) in a context object which is simply a large XML document that gets serialized to and deserialized from the Session as a string. The XML format is also important because the rendering is done via XSLT.
This has led to a number of problems :
It's a kind of God object with far
too many concerns.
It's loosely typed and relies too much on XML manipulation / XPath.
There is no standard way / pattern for retrieving the session xml document or for writing it back. We have a horrible mixture of methods that take the document in as a parameter, modify it and return it, methods that retrieve it themselves, modify it and save it back to session, etc, etc. This has lead to a lot of hard to trace bugs, over-use of serializing /deserializing from the Session, etc.
Our Solution
What we have done is try to introduce a strongly -typed wrapper around the xml document, which breaks it up into different concerns and to manage the lifecycle transparently to the rest of the app.
What we are aiming for is the following workflow:
Beginning of the request, we populate
the session document from the xml
string stored in the session.
The rest of the app interacts with it
only through the strongly typed
wrapper. The whole app uses the same
instance and does not have to worry
about when to retrieve or save the
state back to session.
At the end of the request, the underlying xml document is serialized back to the Session.
Since we are using NInject(v1) as the IOC of choice, we decided to use this to manage the lifecycle of our context object. The context object was wrapped with the OnePerRequest attribute and the dispose method was hooked up to a method that would save the xml document back to Session as a string.
It doesn't work...
We soon encountered a problem that the NInject OnePerRequest module didn't appear to have access to SessionState. The first thing we tried was a hack that we would keep the Session object in a variable to make sure we could still write to it. This appeared to work on a development machine but it became obvious it didn't when moving to out of process state.
It still doesn't work...
We tried inheriting from the OnePerRequest behaviour / module, and adding the IRequiresSessionState marker interface (OnePerRequestRequiresSessionState). However, this was not enough as the method which NInject uses to release references and clean up gets hooked up to the EndRequest method. Session is available in EndRequest but it has already been serialized to the out of process state server so changing something now is not reflected when the session string is retrieved at the beginning of the next request.
We then decided to change the even t to hook up to. We ditched EndRequest and hooked up our OnePerRequestRequiresSessionState "release all" method to the PostRequestHandlerExecute event, which is BEFORE the session data gets serialized out of process.
It works... then it doesn't...
This seemed to work. On a single server and on a web farm. Then we noticed weird behaviour. There seemed to be two different versions of the context and you would randomly switch between them. Add something to the cart, it's not there. Go to browse to another product and the previous product would show up in the cart.
After some tracing, we discovered the culprit: Response.Redirect. Sprinkled throughout the site in literally hundreds of places is Response.Redirect(url);. With this version of the redirect, the execution of the page is stopped immediately. This means that PostRequestHandlerExecute is not fired and the current version of the Context object is not thrown away by NInject... and everything falls apart. New versions are not created properly, etc. EndRequest is fired which is why the normal NInject OnePerRequest module works fine with it, just not our bastardized version that tries to use session state.
Of course, there is an override to Response.Redirect where you can pass a boolean value in to tell it whether to terminate the existing page or continue to execute - Response.Redirect(url,false). Continuing obviously fires our event and everything works but... it continues to execute the rest of the page! This means executing everything that comes after the call to Redirect and we have absolutely no idea what that means (since the existing site expects it to stop).
What next?
So, any suggestions on what to do? So far we've discussed :
Abstracting our redirect behaviour
and going through a central method
that controls the redirect (perhaps
hacking out a way to call the
PostRequestHandlerExecute even t or
maybe a custom Redirect event that
our NInject module can also
subscribe to and clean up).
Seeing if there is a way we can
force the Session object to save in
EndRequest if it hasn't been saved
previously in
PostRequestHandlerExecute, and do
the ninject clean up in EndRequest
Remove our dependency on Session
completely and use another storage
mechanism: DB, document DB,
distributed HashTable, etc. Any
advice? Suggestions we haven't
thought of? Things you've tried
that have / haven't worked?
I think you're on the right track. Here's some thoughts I had:
in addition to the strongly typed wrapper you have, I'd suggest a facade for accessing the context object that returns your wrapper, something like an IContextProvider. that way you can introduce it piece-meal, and then when it's fully integrated, you can refactor the provider without breaking the things that use it. I can't tell, but you might have already done this. it'll also be easier to change your persistence mechanism if you choose to. if you can do this, I would suggest once you get all the dependencies isolated from the context object, change it to not persist as XML. the SessionState will store a binary object much faster, and you can always serialize to XML if you need to do transforms.
I don't think that Ninject is the correct mechanism for what you're trying to do. it's difficult to signal end of the request in Ninject, since garbage collection can't be depended on. have you considered using an IHttpModule instead? you can use the AcquireRequestState and ReleaseRequestState or EndRequest to handle getting/setting the context in Session. only allow the app to get to the context object through the facade.
if you're on a webfarm, you're probably using a database for your Session storage anyway, so putting your context into a DB won't be much different.
Firstly, while it's good to demonstrate you've put in the work, (and I and others may not have replied if it wasn't clear how much you're interested in a resolution)... that's a massive wall of text! Here's a +1 on your way to investing in a bonus for a complete response that talks about the Ninject ASP.NET extensions and how they apply to each individual element of your issue. Having said that, hopefully someone will come along with a real resolution for you.
Even though it's [very] 2.0 specific, Nate's Cache and Collect Post is required reading. While it seems you're pretty au fait with the tradeoffs involved and have debugged deep in, the article is well worth a few reads.
I'd also consider moving to V2 of Ninject - a lot of this stuff has been revised significantly. It's not magically going to work, but represents a mature rewrite based on a lot of learning from V1. Have you read the (V1 or) V2 unit tests for Ninject? They'll show you the low level tools at your disposal in order to realise your goals.
Bottom line for me is that you need to work out a strategy for your state management independent of DI, and then by all means use the container/DI system as a part of the implementation.

Design Decision - Javascript array or http handler

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.

Resources