Unable to send mail asynchronously - asp.net

I'm using a separate class and unique method for sending mail.All my web pages, will call the method to send the mail. But, I'm using Client.SendAsync() to send the mail. The following error occurs while sending the mail asynchronously.
"Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event"
I set Async=true in #page directive, but, as I'm using separate class, so no use of it. Is there any other way to overcome this problem?

Seems you just need to start your async task before PreRenderComplete event; do you mind to post some relevant ASP.NET code?
Also, read this: Running an asynchronous operation triggered by an ASP.NET web page request

This article may be of some help to you:
Fire and Forget Email, Webservices and More in ASP.NET

Setting Async to true is OK if that separated class is declared, instantiated and within the context of the page request.
However you probably need to handle SendCompleted event.
See the sample codes in this MSDN Reference.

Related

Asynchronous event in asp.net webforms

I have the following use case:
A user can filter on my asp.net web project for some data and request the result as PDF. The PDF is generated per request new and returned to the user. I got already everything to run.
But: the processing can take up to two minutes and the user should be able to continue to use the page.
I tried to use a second tab, but both tabs are blocked. Even when I use the PageAsyncTask class and the async attribute. When I use a thread to perform the request, I am truly parallel, but I have no clue, how to interact with the user from inside the thread when the work is done.
How can I send an async request to the server and just get the result on the page, in whatever form, when its finished?
Dave Encosia does a great job explaining how you can do this:
Using jQuery to directly call ASP.NET AJAX page
methods
Using jQuery to Consume ASP.NET JSON Web
Services
3 mistakes to avoid when using jQuery with ASP.NET
AJAX

HotTowel (Durandal really) and SignalR initialisation

So I'm integrating SignalR and HotTowel, although really I think this is a matter of how to integrate with Durandal itself.
The issue is I have obviously multiple views. Some of these views I want to respond to SignalR messages. The question is how to do this integration considering that SignalR events have to be started before I call SignalR's hub start method.
So take the example I have view1 and view2. I want each to do something when a SignalR message is received and in the context of that view (so let's say update the DOM somehow). It's an SPA obviously so calling the SignalR start method for each view seems like a bad idea, so starting SignalR once at boot sounds like the right plan, but at that point my views may not have been loaded, and still how would I ensure that my events have the right context for the page.
This is based on my understanding that all events for SignalR have to be registered before I call start. Any thoughts clever people of StackOverflow?
Edit to expand on the problem
Part of the website involves uploading files for parsing and processing to import into a database. I have created a view where the file is selected and uploaded (using FineUploader) to a WebApiController. The controller does the basic steps of checking the uploaded file and then starts an async task to actually do the parsing and processing, while immediately returning the basic "Yep that uploaded fine" message.
This causes the list of 'in progress' files to refresh and the file appears with an 'Uploaded' status. As the async task occurs, the file is parsed, then processed against a rules system, and then finally imported into another back end data store. As each of these status changes occur, SignalR sends messages to the client to notify them of these changes, and thus update the status against the filename. In order for this to occur I must attach a function to the event as it received in SignalR. That even needs some kind of reference to my view (actually viewmodel) so it can update the correct value.
As SignalR should be started once with a call to hub.Start(), I am trying to do it during the 'boot' phase. However when my SPA starts, that view has not been loaded, and therefore neither has that viewmodel, and therefore my function that is responsible for initialising SignalR can have no understanding of the view/viewmodel it must update.
Examples I've seen on using SignalR show it being used in one view, but that doesn't really work surely if you need it in multiple views (you can't just keep calling hub.start() can you)?
Sorry, if this still doesn't make sense I'll post some code or something.
If you use
$.connection.myHub.on("myMethod", function (/* ... */) { /* ... */ });
instead of
$.connection.myHub.client.myMethod = function (/* ... */) { /* ... */ };
you can add client-side hub methods after calling $.connection.hub.start();

MVC 3/4 HttpModule or ActionFilter

I need to check some stuff (Cookies) for each request coming to my application.
In ASP.NET we've used HttpModule for this task , the question what should be used in MVC ? Some Global Filter , or I can Use HttpModuler as well, is there Any difference in Request PipeLine between MVC and regular ASP.NET ?
MVC is an abstraction over ASP.NET and therefore their "hooks" really depend at which level you want to inject your logic. An action filter will allow you to hook into MVC specific events:
OnActionExecuting – This method is called before a controller action is executed.
OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.
Whereas an HttpModule only allows you to hook into ASP.NET (upon which MVC is built) specific events:
BeginRequest - Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page), synchronize this event.
AuthenticateRequest - If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password), build a module that synchronizes this event and authenticates the user in a way that you want to.
AuthorizeRequest - This event is used internally to implement authorization mechanisms (for example, to store your access control lists (ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so.
PreRequestHandlerExecute - This event occurs before the HTTP handler is executed.
PostRequestHandlerExecute - This event occurs after the HTTP handler is executed.
EndRequest - Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page.
So it really depends on when you need to hook in your event and which events you need.
If the HttpModule worked well for you before then it will continue to with Mvc.
The other parts of your question are quite broad in scope and think you'd be as well reading a good article on asp.net-mvc pipeline and extensibility.
I've done similar things using a global action filter. It works quite well, and keeps your code integrated within your application.
An HTTP module works as well, of course, but this will mean seperating the code from your main application and maintaining it seperately. Unless your code spans multiple sites or is used in multiple applications, or needs to work with web forms sites, then I would use a global filter.

How to kill a javascript async call to a .net webservice?

My javascript code is calling a asp.net webservice, so i have a call to the webservice something like this:
MyWebservice.GetData(param, ResponseReceived, ResponseTimeOut, ResponseError);
When the webservice returns data, ResponseReceived method is called.
However sometimes the user might navigate to another url before the webservice call actually returns, in such a scenario FireFox throws an Error saying 'An error occured oricessubg the request. The server method GetData failed'
So my question is how can i kill the async call when the user navigates to another page or makes another request to the webservice? I know in a normal XMLHttpRequest i could have called Abort method, but not sure how to make it work with the above webservice proxy.
A good practice would be to keep your common functions in a common place, which is accessible from all of your pages.
This would include the OnError function. That way you can safely reference that same function from all of your pages. If you need to provide custom Error Functionality, you can either override this function on your page, or include a handler in your common function, and call if it was assigned.
A good place to put such common function would be inside a root master page, or a shared JavaScript file referenced from root master page.
What is good about this, is that hopefully your OnError function does some logging, so you can get an idea of what fails and how often so that you can design your app accordingly.
Ok I figured out a solution, I can call get_executor() method to get an instance of the XmlHttpExecutor class, on which I can call the abort method. Hope it helps others facing a similar problem.
I'm still eager to find out other solutions.

Extend the exception thrown from ASP.NET when calling a Webservice from JQuery

I'm using JQuery to load controls dynamically in an ASP.NET development environment using JSON and WebServices. Within this solution I have a business logic layer which has a built in validation mechanism (i.e. validating properties and business rules similar to that of CSLA)
When requesting a new control to be loaded dynamically using JQuery and an ASP.NET WebService, I would like to validate the input from the current control against the business logic validation mechanism (i.e. server side validation) and notify the user if there was any problems.
I managed to achieve this, however, when validation fails in the web service I would like to throw a customer exception containing the validation field id's and associated error messages.
In JQuery, I test for this specific ExceptionType and would like to apply the error messages dynamically to the controls listed in the exception type properties. This is where my problem comes in. Even though I created a custom exception with custom properties the exception that is passed to JQuery in JSON format from the WebService is still a standard exception with none of the additional properties listed. I could simply create a JSON formatted string of values in the exception's message property but would ultimately prefer something a little more elegant. Does anyone know how you can override the serialized exception created by ASP.NET for situations such as this...
Thank you in advance...
G
I ran into something very similar a couple days ago - basically there's no way to make ASP.NET generate custom exceptions. This is by design, since returning a specific type of exceptions would
[...] expose implementation
details/bugs to the clients. We could
do something with special exception
type that we let pass through, but its
too late for this release [...]
You could always return different HTTP status codes, and have the browser handle them as custom exceptions - for example, a 500 error would mean one thing, a 401 something else, etc. I think the best solution is to make your method return a string with the exception stack - not elegant, but at least this way the client has all the exception details.
Dave Ward also has info on ASP.NET AJAX service errors.

Resources