I am making a site where users can reply to topics, open topics, etc. and when the user sends a message, I don't want to postback; it's ugly.
I'm using generic handlers right now but I am having some problems with it. Like updating GridView using UpdatePanel when XMLHttpRequest's onreadystate is changing.
I decided to use PageMethods but I also wanted to ask you.
Which is better, faster and more useful: PageMethods or Generic Handlers?
I don't think there would be much difference between the speed of Page methods and HTTP Handlers. However if you're worried about your application's performance, you should benchmark each option and choose what's best for you.
To answer the question, which is better or more useful, basically within the ASP.NET context you have three options, each with their pros and cons:
Page methods - all your code is contained in single Page, which is fine if the code is only used by that page. You should probably implement methods that return page-specific HTML snippets as Page methods. However if we are talking about reusable code, such as "Save Topic" or "Get Topics", you might want to consider externalizing this code elsewhere. I guarantee that as your application grows, you'll need those methods elsewhere in your application end as well.
Generic HTTP handlers - are lightweight, and great for code you need to call often throughout your application. Most often generic handlers are implemented to serve content, and I don't know what the best practice around this topic is, but to me POST ing to a generic handler to save data has a distinct smell. You'll also find that for related functionality (Save, Get single, Get many, etc.) you'll end up with a swarm of handlers, or a handler with a giant switch statement and a fuzzy contract based on query string and POST parameters. I wouldn't recommend this option to implement extensive AJAX application. For small bits and pieces it might suit your needs.
ASP.NET web services (or WCF) - The third option you did not mention in your questions are ASP.NET web services (.asmx). You can easily include them in your existing ASP.NET application without any additional framework dependencies. They offer a good balance between the options 1 and 2. On one hand you get reusability throughout your application, and even outside your application if you so choose, which Page methods cannot provide. On the other hand you can neatly bind together related functionality in meaningful ways, which tends to get messy with generic handlers. You can also interact with the services using SOAP XML, JSON or HTTP POST / Plaintext as needed.
And the wildcard option here is: Use ASP.NET MVC and jQuery. If you're looking to build a lean and mean web application and you generally find postbacks ugly, and you find stuff such as what exactly happens when the xmlhttprequest changes readystate interesting, it might provide you with a better experience overall. Maybe not for this project, but for the next one.
If you mean with generic handlers web service endpoints then you can make the following distinction:
You can use PageMethods if the functionality only needs to be available on that page only
You can use web service endpoints if you want to reuse the functionality.
Personally I practically always use web service endpoints (in my case ajax enabled WCF).
I cannot see why you shouldn't use generic handlers. I think they are best - simple and flexible.
Related
We have an application that uses webforms for some older web app pages, but also contains MVC functionality for some of the newer features. We have some new requirements for downloading files that will have to be processed on the server (not direct links to static files on the web server).
I haven't seen anything to indicate if there is a reason one should use an ASHX handler over just using an MVC controller and operating on the response object and returning EmptyResult() at the end of the action method.
Is there a best-practice for this with MVC? Should ASHX handlers be left for WebForms or is there some benefit they provide over using MVC for this type of file download feature?
The performance of HttpHandler is better since it is more bare-metal than MVC actions (just a few extra steps, but still).
Besides that, I see no reason why you should choose one over the other for performance reasons. MVC has some nice features you might want to use, like caching and authorization attributes.
If you choose to use MVC, use results that are specifically built for file handling, like FileStreamResult or FileContentResult.
Well, an ASHX can be a bit more contained and specific... however, there is something to be said about having all your code and logic in your main application.
There is no technical reason to do one over the other, to my knowledge with MVC nowadays. With WebForms it was harder to stream large files, but with MVC you can do that pretty easily (so you don't have to load the whole file into memory first). Also, given modern Async methods you don't have to worry so much about tying up worker threads and what not for scalability.
It's really up to you. Even if you wanted to separate it into its own module, nowadays it might make more sense to make it an owin module rather than an ashx. It's more about how you want to design your app.
I want to make an ajax call from jQuery to my server. Basically, I want the request to be sent as a POST with a content-type of x-www-form-urlencoded and the corresponding parameters (parameter1=X¶mter2=Y¶meter3=Z). I want the response to be JSON.
The server environment is .NET. I have been experimenting with the three methods below, but have not been able to get one to work quite right.
ASPX - Using an aspx to process and return JSON, I can get it to work, but I need to serialize the JSON myself. This is possible, but I was hoping for something more convenient. Also, correct me if I'm wrong, but I would imagine that aspx pages have a lot of extra overhead involved since they are expected to do more than just execute a method and return simple JSON.
ASMX and WCF - With asmx and WCF, I can get it to return JSON, but only if I send JSON in the request.
What is the best server side "framework" to use for this request / response type? .aspx, .asmx, or WCF? Since I have been able to at least get aspx to work for this, is that even an appropriate approach?
I've seen other products out there that expose an API via a web service and use a name / value querystring request format with a JSON response type, but this seems to be a difficult feat to accomplish in .NET.
You're right that ASPX pages bring extra overhead. Even if you're not using the WebForms framework at all, requests to ASPX pages still must filter through the entire page lifecycle.
If you prefer that sort of low-level approach, reading QueryString parameters and responding with manually serialized JSON, an ASHX HttpHandler would probably be the best solution.
Personally, I prefer ASMX services. Sending JSON parameters in isn't very difficult (and you'll probably end up doing that anyway once you begin sending nested objects or collections, which is a mess via simple key/value pairs), and it's nice to avoid the needless ceremony of deserializing and serializing during every request.
People will tell you WCF is the correct solution since it's newer, but .NET 4's WCF isn't currently a great fit when you're using jQuery. It's not as flexible when dealing with DateTime and Enum types, and it has unwieldy Dictionary serialization. WCF's new WCF Web Api solves those problems though if you want to try something a bit ahead of the curve.
I've used.
.aspx -> just exactly the way you are doing it
.ashx -> similar to the .aspx except less overhead in the page lifecycle.
.asmx & wcf -> what's wrong with passing JSON in the request?
MVC -> return JsonResult. This one is my favorite when I'm not making an entire
API (for that I use WCF), but instead I just need one or two requests
to return JSON. This, of course, assumes that the entire site is
written using MVC, otherwise it would be overkill to install the
framework for just a few calls.
If you are okay going down the WCF route, may I suggest you look at the WCF WebAPI project from Microsoft. This project sits on top of WCF and provides some niceties and simplifications when it comes to client access (.NET code or jQuery Ajax). Here is a walkthrough using jQuery to POST form-urlencoded data. There are other walkthroughs demonstrating other related tasks there as well.
These services can be hosted like any other WCF service, and even hosted right within the same ASP.NET project as the rest of your site.
At this time, the project is in early development and has some "Go-Live" restrictions, but depending on your project needs, this may work out great, it has for us.
I have seen that ASP .Net Code Behind files are really slow. I have used local web services which I call from jquery ajax function and they are fast. But I am still confused? Should i display dynamic data from code behind or web services?
I let my web service return a JSON Object and I assign relevant elements from that JSON object to different html elements like (image, div etc.)
You need to weigh several things..
If you are dealing with a low-traffic, internal web application, perhaps server-side postbacks are the way to go. Often you'll find that there's less code you'll have to write in this case.
If you are working on an external, public, high-traffic web application, perhaps AJAX is the way to go. That way you avoid posting back entire ViewState and running through the full page lifecycle. This may result in more front-end code, but is less load on the web server.
Keep in mind that client-side data binding is a very viable solution these days, with the help of such things as jQuery Templates. So that helps bind data returned from AJAX calls to tables and other elements.
As far as web services go, they are great for when you're sharing data/functionality between different systems. If you don't foresee doing that for this particular application, then perhaps there's no need to over-engineer it - keep it simple with either MVC and Action methods that support AJAX calls out of the box, or get familiar with PageMethods.
I'm sure there are other pros/cons I haven't mentioned, but this is the first thing that came to mind.
ASP.NET classic life cycle and postback is the base of Microsoft Click&Go philosophy. It is not designed to be fast even if it suits in most cases.
AJAX plus Web Services architecture is good way to improve server performances and dynamicity. It may not improve client performances, may increase the network load if bad designed and complicate a website architecture.
Another possible orientation is ASP.NET MVC, where old life cycle and postback is ancient history.
Like Kon said, mixity is probably the best way at the moment : MVC+AJAX or ASP.NET+AJAX where classic client<->server requests are used for common functionnalities and AJAX requests brings dynamicity with small requests for friendly functionnalities.
Note that most users on the planet are using Internet Explorer who have the worst javascript engine on the planet ;)
I think many of us used to face the same question: what's the best practice to port existing web forms App to MVC. The situation for me is that we'll support both web forms and MVC at the same time. It means, we create new features in MVC, while maintaining legacy pages in web forms, and they're all in a same project.
The point is: we want to keep the DRY (do not repeat yourself) principle and reduce duplicate code as much as possible. The ASPX page is not a problem as we only create new features in MVC, but there're still some shared components we want to re-use the both new / legacy pages:
Master page
UserControl
The question here is: Is that possible to create a common master page / usercontrol that could be used for both web forms and MVC? I know that ViewMasterPage inherits from MasterPage and ViewUserControl inherits from UserControl, so it's maybe OK to let both web forms and MVC ASPX page refer to the MVC version. I did some testing and found sometimes it generates errors during the rendering of usercontrols.
Any idea / experience you can share with me? Very appreciate to it.
Background:
This UI project has been created for years and there're 20+ people working on that. Before I start the common master page trial, there're about 50+ web forms pages and only one MVC page. We create new features on MVC, but the old pages keep remaining in web forms.
This situation will keep for a long time, probably because this's a business-driven company so new features are always in a higher priority. This means we need to support both at the same time.
There are several integration problems using ASP.NET MVC master page with web forms pages and user controls. Since the execution pipelines of the two frameworks are not exactly the same it is normal to have some problems.
One of the things I've faced is that web forms uses single interface pattern (it has one <form> tag with runat="server" on the page). In your master page or pages using it you'll have to create this tag yourself if you want to use server controls. Note that this will work for read-only controls. If you need post-back & event handling you'll probably face more problems with event handling and event validation.
Also one trick is to create html helpers that render existing controls to string. You can check this out for more info http://www.abadjimarinov.net/blog/2009/10/29/HowToRenderAspdotNETControlToString.xhtml This is also a partial solution as it will not work with most user controls.
It will be helpful to provide some code or error messages so I can give you more concrete answers. At this level I can only say that the two frameworks are compatible and you can integrate them but this will not be painless and will require some changes in the existing code.
Let me use an analogy
This will sound harsh but will make it easier for me to pass the idea across. Exaggeration helps sometimes because it emphasizes certain things that need to be understood.
Ok. We're using bicycles to get from A to B at the moment. We're considering buying a car but we want to make transition from one to the other as painful as possible. Consider the fact that we enhanced our bike so it uses custom pedals etc. Is it possible that we use these pedals and other enhancements with the new car we're considering?
Essentially it's possible. But without making a huge mess out of it it is definitely not advisable.
Suggested transition is to change pages one by one to use the new technology (new ones of course in the new technology) and not to introduce some MVC functionality to a webforms page. Either MVC or WebForms for a particular user process. Majority of non-UI code can be reused (business services, data access layer code, data/domain model when applicable). But if you're cramming all the code in your code-behinds... Well bad luck for you. If you haven't separated your code you will more or less be repeating code. Unfortunately that's not Asp.net MVC's fault. It's your bad design without SoC.
Don't combine/mix/blend two UI technologies if you're not suicidal. You can go from A->B using either bike or car, but not both at the same time. This means you can have WebForms part of your application and MVC part of it, but not likely on the same page. And this is only possible if you use Web applications not Web sites. Asp.net MVC can't work as a Web site (on demand partial per page compilation).
Re-usability related to my analogy
Bike and car are two UI technologies. What you do or the purpose of you taking the route from A->B is not important. That's business logic. If you're delivering newspapers that's not related to transport. So you can see that other layers can be reused.
Asp.net WebForms vs. MVC
Asp.net WebForms
Server-side controls (web/user) use the event pipeline execution model. Hence they (unless completely presentational nature) have server side events that some code subscribes to. Platform is completely state-full and everything executes in a manner that abstracts the HTTP completely away. Everything looks like you'd be running a desktop application.
Controls usually encapsulate presentation, code (as in server-side and client side script) and style (as in CSS). That's why it's a lot harder to have SoC using WebForms.
Asp.net MVC
This platforms is completely suited for the stateless nature of the HTTP protocol. Every request is completely stateless (unless you store some state data in persistent medium - Session, DB, etc.). There's nothing like an event model. It's basically just presentation of data/information that is able to transfer data to the server (either as GET, POST, DELETE, PUT...). Server side doesn't have any events. It's only able to read that data and act upon it. And return some result (HTML, Script, JSON, ...). No events. No state. No complex abstractions.
Asp.net MVC abstracts away some common scenarios that are related to data. Like automatic conversion to complex object instances and data validation. Everything else is gone.
Asp.net MVC using WebForms
In case you would like to use server-side controls in an MVC application you would be able to put them in your ASPX/ASCX, but they would only be used as pure presentation. You'd provide some data to render. And that's pretty much it. Postbacks wouldn't even work (unless you'd put a submit button on it), because there's no __doPostback client side functionality that would make a POST request to the server. So if there's any server side code that these controls have (even when they didn't initiate a postback) and are related to it's state-full lifetime after they've been loaded, you can say goodbye to them. More or less.
Other than that, you can read a lot about differences between Asp.net WebForms and Asp.net MVC on the internet.
Sharing MasterPages: see this thread.
User Controls:
This is one of the banes of my existence with MVC; in MVC2 and previous revs, there's no direct equivalent to webforms user controls. A sort-of workaround is creating HtmlHelpers - (effectively extension methods to the Html object available in views that return HTML), but that means you'll have to render your HTML in code. Teh suck.
With MVC3 and the Razor view engine, a new class of Html Helpers is available that provides most of the benefits of user controls, including the ability to place them in separate assemblies (and therefore can be used in multiple projects). I'll see if I can dig up an example link, but Scott Guthrie's blog had an example in one of his recent MVC3/Razor posts.
You can do a certain amount of integration between the 2, but you end up with something more complex & less satisfactory from either approach. A comprise in other words.
I've had this same problem in the past & server side includes worked for me. Old school I know & not something I'd generally recommend. But we don't work in an ideal world.
What's the best way to log in ASP.net MVC? I mean any event, I'm currently using NLog but I know there are a lot of possible ways to do it.
I use log4net, its quite good. There are some issues to be aware of, you can learn more about them here. I also recommend Elmah, for me I use it on every project I do, its a prerequisite.
I don't think there is a best framework/tool or standard way in ASP.net MVC. Just do it the way you would in any other framework. When I set up logging, I usually think of it as a resource available to the rest of the application, rather than being tied to a particular tier. This is common, and in fact logging is the standard example given when introducing Aspect Oriented Programming. See:
Logging mentioned in the wikipedia entry on AOP
Another AOP into that uses logging as the example
Depending on what exactly you're trying to log, consider using action filters; a great way to log what page requests are made and for error handling coverage. Non-MVC asp.net apps usually do something in the global.asax, as mentioned here. In fact, even if you use the action filters, which I would suggest, also include some basic error handling in the global.asax 's application_error event; it will fire a little more dependably than the action filters if something really crazy happens.
Other than that, call your logging resource at the point where the stuff happens that's interesting to you. DB or File? Either works, and as long as it's encapsulated in a good method or two, you can always switch that later.