Send Email without waiting for the action to finish execution after Button click ASP.NET - asp.net

In short, remaining in the HTTP context, I would like the user, after clicking on an order completion button, not to wait for the mails to be sent before being sent back to a "thak you page".
I saw that HostingEnvironment.QueueBackgroundWorkItem could help me with this but there is always the risk of it being killed by IIS recycling.
What is the best solution to do this?
I know the best would be to develop a separate console solution but it wouldn't be worth it for 3/4 emails, alternatively I could consider speeding it up by making them asynchronous?
Protected Sub btnConcludiOrdine_Click(sender As Object, e As System.EventArgs) Handles btnConcludiOrdine.Click
If IsValidOrder(Me._cart, msg) Then
If Me._cart.SaveOrder(Me._user, Me._orderCode, Me._lang) then
'Update quantity in db
Dim mail As New EmailBLL
mail.SendOrderNotice(Me._cart, Me._lang) '2 Mails
mail.SendProductNotice() '2 Mails
End If
Else
Response.Redirect("*Error URL*")
End If
End Sub

The way you approach this is as suggested – start a task, or so called new processor thread.
So, what you would do is break out the code – this even works if code behind is for a web form.
So, the first step is to move out the “slow” parts, or the parts we want to run separate.
The main issue is that to start/launch/want/desire/achieve a brand new processor thread?
The sub call CAN ONLY PASS ONE “parameter” and the sub can only accept one parameter!!!!!
I note in your case that routine needs two values.
However, that “one parameter” can be a array of “many” values, or even a collection or whatever. In our case we pass the two values.
So just keep in mind that what you call can NOT update or “use” the values of controls on the form – the instance of that form will go out of scope.
But we can of course PASS the values you need. This will allow that routine to run 100% independent of the web form.
I also VERY strong suggest that if you DO place the sub in the same web page code behind? You should/can mark that sub as shared. Doing so will allow the compiler to get mad at you and spit out errors if that routine say tries to use or update a control value on the form.
However, it is MUCH better is to place this sub in a separate standard code module out side of the web forms code behind.
Regardless of above, we can now re-write the code we have as this:
If Me._cart.SaveOrder(Me._user, Me._orderCode, Me._lang) then
Dim myInfo(1) as object
myInfo(0) = me.cart
myInfo(1) = me_._lng
Call MyUpdateQ(myInfo)
End If
' bla bla lba
Shared Sub MyUPdateQ(p() as object)
'Update quantity in db
Dim mail As New EmailBLL
mail.SendOrderNotice(p(0),p(1)
mail.SendProductNotice() '2 Mails
End Sub
Ok, so far, we not achieved much, but we re-writing to accept the ONE array is KEY here.
So, now now make sure the above runs/works and is all happy.
Now, because we moved out the "work load" to that one routine, it is now a simple matter to start a thread.
Now, Our above code becomes this:
Protected Sub btnConcludiOrdine_Click(sender As Object, e As System.EventArgs) Handles btnConcludiOrdine.Click
If IsValidOrder(Me._cart, msg) Then
If Me._cart.SaveOrder(Me._user, Me._orderCode, Me._lang) then
Dim myInfo(1) as object
myInfo(0) = me.cart
myInfo(1) = me_._lng
Dim MyThread As New Thread(New ParameterizedThreadStart(AddressOf MyUpdateQ))
MyThread.Start(myInfo)
End If
Else
Response.Redirect("*Error URL*")
End If
End Sub
Shared Sub MyUPdateQ(p() as object)
'Update quantity in db
Dim mail As New EmailBLL
mail.SendOrderNotice(p(0),p(1)
mail.SendProductNotice() '2 Mails
End Sub
That is it. Now when you click your button it will wait ZERO time, since the long running routine is now going to run 100% as a separate thread. And this will also mean that when the user clicks the button - the page will respond instant and post back to user will be done. So if that thread takes 6 seconds, or even 25 seconds, the user will not notice this delay.

Just push your sending mail logic in Task and if you are not interested in result don't await it. c# syntax
Task.Run(() => SendEmail());

Related

multiple upload, ajax control

im trying to upload multiple file and save all the files in a data table.
the data table is storing only one file.
Help me to solve, im having error in the else part. dtupload is highlighted
Below is what I have tried:
Private Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Try
dt.Rows.Add(UploadDocPath, UploadDoc)
MsgBox(dt.Rows.Count.ToString)
Else
dt.Rows.Add(UploadDocPath, UploadDoc)
End If
Catch ex As Exception
End Try
End Sub
Well, you in ONE local routine create a table, add a row. And then the routine finishes and all the values, variables now go out of scope. Then that routine will be called again if a 2nd file is up-loaded, and you re-create the table. The variables in that routine (and in fact ANY routine - heck even if this was not asp.net go out of scope when the routine finishes.
At least with a desktop application you could declare the table at the form level (not sub routine level) and then you could add a new row to that temp table variable. But, with asp.net, then your web page is "state less". That means all variables ONLY have their state when code runs. The instant that code is finished, then all state in the code behind is lost.
But I am somewhat perplexed that you would think the data table would persist for each call? Perhaps you only want the var dtUpload to exist in the lifetime of each separate time that routine is called? But, then again you do nothing with the table????
So, for each file up-loaded? That routine gets called.
So, lets assume 5 files are to be up-loaded.
Taking a really wild guess? I would assume we want that table/array to build up over time.
So, we need to ensure that the dtUpload table can "live" beyond a single page cycle and round trip.
So, lets save/place/put/park the dtUpload table that can live "beyond" that one routine.
It really depends on what you want to do with that list after all is said and done?
Since the table is small? Then you could certainly in the forms on-load event create that table with no rows and shove it into say the Session(). Then as each file up-loads you could shove the file name into that array.
So, your code could work like this:
In on-load event only FIRST time, create the dtUpload table. And then shove/save it into the session().
So, our on-load would look like this:
If IsPostBack = False Then
' fist time page load - create our table
Dim dtUpload As New DataTable
dtUpload.Columns.Add("PATH")
dtUpload.Columns.Add("FILENAME")
Session("FileList") = dtUpload
End If
Ok, so when the page loads (first time only), we create the dtTable and THEN save it in the session.
Now, in the file upload done event, grab the table from session, add the row (file + path).
And note HOW we don't have to shove the dtUpload table BACK into the session! (it is now a persisting object in our session).
Ok, so now our single file load event (when done) can/will look like this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object,
e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim dtUpload As DataTable = Session("FileList")
Dim strPath As String = "c:\Test\MyUpload\"
Dim strFile As String = e.FileName
dtUpload.Rows.Add(strPath, strFile)
AjaxFileUpload1.SaveAs(strPath & strFile)
End Sub
So, note how we add the one row to the table. (and we don't as noted have to shove the object back into the session - dtUpload in this case is in effect a object pointing to persisting dtUpload table we placed into Session().
Ok, so, now lets say all 5 files are done.
Well, you now have to decide what you want to do with the dtUpload table you have?
Perhaps we want to display all the files?
Well, keep in mind that the web page does not do a post back.
But, lets assume we now want to display all files.
Drag onto the form a datagrid control.
Drag onto the form a button.
So, we now have this:
Then hit up-load, you get this:
When you click on the the button, you can run this code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.GridView1.DataSource = Session("FileList")
Me.DataBind()
End Sub
And now click on that button?
And you see this:
Now here is a really huge, large, massive, VERY important reason why placed that button on the form. The reason of course is when the ajax upload is all done?
The web page does NOT do a post back. So, that is where the button above comes into play.
By clicking the button, then our code stub runs, we fill the gridview, and then of course the page makes the round trip and re-displays our file list.
Now, we could have the final CLient side ajaxfileupload event click on that button for us, and thus in place of the user clicking that button to continue?
You can have client side code click on that button for you.
So, set the OnClientUpLoadCompleteAll to the js routine:
<script>
function uerror() {
alert('upload error');
}
function myalldone() {
var btn = document.getElementById('<%=Button1.ClientID%>');
btn.click();
}
</script>
So it will now click that button (you could even set style="display:none" for the button. So, now you have a final routine server side, but with a full page post back.

allowing only one instance of page

i have a question about allowing only one pageinstance in all clientsessions. So if a client ask for the unique page and there is already a session with this page. The client which ask for the page should get a messagebox, which say "This page is already in use"
I read about this problem on forums. Many people say "it's impossible to get out if the client have close the browser (including the unique page)".
Is that true about the serverside?
Is there a way to handling this problem?
Is use Asp.net with Vb.net
i hope anyone understand me. My english is bad.
The problem with keeping track of whether the current user is still using the page can be managed by having an UpdatePanel with a Timer which then sets an application variable time every 500ms (or whatever interval you want)
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Application["PageLastUsed"] = DateTime.Now;
End Sub
and redirect users if the page is in use
TimeSpan duration = DateTime.Now - (DateTime)Application["PageLastUsed"];
if (duration.TotalSeconds < 2)
{
Response.Redirect("InUsePage.aspx");
}
See timer info here http://msdn.microsoft.com/en-us/library/cc295400.aspx

WebRequest Async CallBack Code only gets call the first time

I am an absolute beginner on ASP.net (VB.) Please pardon me if the question is too obvious for the experienced members.
I tried to make a simple WebRequest in the async mode in case the target URL takes long to provide the data. In my code below, I just want to see if the callback block (RespCallback) is called correctly every time. If all goes well, lblResult should have the string '123' appended to it every time I click the button which calls the 'GetData' sub.
However, the lblResult only shows 123 after the first click. After the subsequent click, the lblResult only gets appended with '12', as if RespCallback is never called. When I tried to debug this in Visual Studio, the execution actually stepped right into the RespCallback part and the lblResult.Text watch actually shows '123123' but the resulting Web page always shows only '12312'
I am sure I am missing something basic here, but I just don't know what. I was even guessing that it has to do with browser cache (hence the result changes for the second time) but I don't know how to fix that either.
Can someone please help? Thanks in advance.
Jim
Dim myWebRequest As WebRequest
Public Shared allDone As New ManualResetEvent(False)
Private Shared BUFFER_SIZE As Integer = 1024
Public Class RequestState
' This class stores the state of the request
Private Shared BUFFER_SIZE As Integer = 1024
Public requestData As StringBuilder
Public bufferRead() As Byte
Public request As WebRequest
Public response As WebResponse
Public responseStream As Stream
Public Sub New()
bufferRead = New Byte(BUFFER_SIZE) {}
requestData = New StringBuilder("")
request = Nothing
responseStream = Nothing
End Sub ' New
End Class ' RequestState
Public Sub GetData(Sender As Object, Args As System.EventArgs)
lblResult.Text += "1"
myWebRequest = WebRequest.Create(dataURL)
Dim myRequestState As New RequestState()
myRequestState.request = myWebRequest
' Start the asynchronous request.
Dim asyncResult As IAsyncResult = CType(myWebRequest.BeginGetResponse(AddressOf RespCallback, myRequestState), IAsyncResult)
lblResult.Text += "2"
allDone.WaitOne()
End Sub
Private Sub RespCallback(asynchronousResult As IAsyncResult)
lblResult.Text += "3"
allDone.Set()
End Sub
I don't know VB so it's hard to read for me but I'm suspecting GetData is your onClick handler.
First thing that is not right is that you have Shared members. Why your reset event is Shared? It makes all requests use the same object.
Basically Your code with ManualResetEvent won't work because after first allDone.Set(), your object remains set (as long as web application lives). To get "123" every time you should add allDone.Reset() after allDone.WaitOne().
In Your situation web request returns to client before RespCallback is called every time except first call (when your reset event is in non-signaled state).
AutoResetEvent resets automatically. That's why it worked.
But! You can't do this this way. Making your ResetEvent Shared you make all request use the same object. When more than one request will be processed by your application at the same time you will get undetermined behavior.
Remove Shared from your code. Than your code will work (but not asynchronously) without allDone.Reset() and without AutoResetEvent. But it will provide known results (not depending on amount of requests).
About asynchronous call (now that we have code "working"). Well. There is no async request to your web page. allDone.WaitOne() waits until your async webRequest finish. So basically you could just as well do synchronous request.
You need a special pattern for asynchronous web pages. You can read how to do this here.
But i'm not sure it's what you wanted. Do you want your request to be called asynchronously so that it will not use server resources or do you want to display some message to the user (like "Data is being downloaded...") while your web page will remain fully responsible?
If it's the second one you should use AJAX functionality (Like UpdatePanel or using JavaScript directly). You can read about it here.
Couple things to check:
If your label is a fixed width, then it's possible the text is being clipped
If you are using an UpdatePanel, you will need to set its mode to 'Conditional' and call Update() on it in the RespCallback callback method so that the UI gets refreshed with the latest label text value.

asp.net async thread with pooling

I have a long running task that I need to implement on a webpage. What I would like to do is run the task on a separate thread, but have a progress bar on the webpage.
I am struggling to find an easy way of doing this. Here is a very simplified example that I want to do this on. Basically, I want the ResetAll() in a thread, and pool the variable y to update the webpage UI.
Can someone help me?
Protected Sub btnReset_Click(sender As Object, e As System.EventArgs) Handles btnResetLowConductor.Click
ResetAll()
End Sub
Private Sub ResetAll()
Dim y As Integer = 0
While y < x
y += 1
Reset()
lblProgress.Text = y & "/" & x
End While
End Sub
Private Sub Reset()
Threading.Thread.Sleep(200)
End Sub
your lblProgress will not update as long as thread is alive. You will get only final value of y & x i.e when thread is dead. You can store the values of Y & X inside a session variable.
Private Sub ResetAll()
Dim y As Integer = 0
While y < x
y += 1
Reset()
Session("CurrentStatus") = y & "/" & x
End While
End Sub
From Your UI you will fire an asynchronous event using PageMethod i.e
function GetCurrentThreadStatus()
{
PageMethods.GetThreadStatus(function(status){
// success
$("span[id*='lblProgress']").text(status);
});
}
Code Behind : C#
[WebMethod]
public static string GetThreadStatus()
{
return (string)Session["CurrentStatus"];
}
As this is a website, you will probably need to use some sort of ajax method to call back to the server periodically. Here is the basic flow of your program as far as I can see it:
User makes initial call
Spin up new thread to run process and return with a 0% status
Periodically, make a call to the web server via ajax (A GetStatus call that will return the percentage of completion)
If the call is complete, update/refresh the page appropriately
If the call is not complete, then use the returned status
Now, I am not as sure about the details given that this is a web page, but you could try to store the status in the session variable (which may or may not be possible once you have already returned) periodically, and then the GetStatus will just read the most current status. If session does not work, then you will need to persist the status another way (db, file, etc).
Just be careful on how often you store the status. Too often and you slow your process down, and too little and you do not give an accurate representation of the status.
Last, if you can upgrade to .NET 4.0, then this becomes even more trivial using the TPL (Task Parallel Library)
You are confused about how web pages work.
Once the thread is fired and you write the response to the client, you won't be able to continue updating the page as the Thread progresses.
One way to do this sort of thing is using Ajax. Ulhas already showed you a way top do this; all you need to do is have that javascript function he wrote call itself until you get a 100% completion. You can do that using a timer.
Okay, with the help of various websites, I managed to do this.
Here is a sample project. Please let me know if there are any problems with this. I'm no expert, so I would like some feedback!
http://www.mediafire.com/?7vn16vp78rave6a

asp.net global synclock object

is there a way in asp.net to make sure that a certain threaded sub is not run twice concurrently, no matter what?
the code i have now is
Public Class CheckClass
ReadOnly Property CheckSessionsLock As Object
Get
If HttpRuntime.Cache("CheckSessionsLock") Is Nothing Then HttpRuntime.Cache("CheckSessionsLock") = New Object
Return HttpRuntime.Cache("CheckSessionsLock")
End Get
End Property
Sub TryThreads()
Dim thread = New Thread(AddressOf TryLock)
thread.Priority = ThreadPriority.Lowest
thread.Start()
End Sub
Sub TryLock()
SyncLock CheckSessionsLock
DoTrace("entered locker")
For x = 0 To 10000
Next
DoTrace("exiting locker")
End SyncLock
DoTrace("exited locker")
End Sub
End Class
if i run this code on every page then several times the code overlaps. the DoTrace function in the code simply writes the message to a table.
the messages in the table should appear in order (entered,exiting,exited) again and again, but in reality, they don't. i get like entered, exiting,entered,exited,exiting...
this means that the synclock is not complete. is that true?
if so, how can we implement a complete synclock on a block of code, across requests and across sessions?
EDIT: i need this lock, as the real code will be sending emails, according to a list of mailing types in a db. after each mailing type is sent, its marked, then it continues with the next mailing. i cant have in middle of processing, another thread should see this mailing as unprocessed.
please advise
Rather than using the HttpRuntime Cache have you considered using a static variable?
Just as a note (it might be helpful to explain why you want this functionality) your website is not going to be very scalable if this can only be run once at a time.
In C# (sorry, don't know VB syntax) I use this:
private static readonly object Padlock = new object();
It's a field, not a property,
It's static (in VB, that's "shared" if I'm not mistaken) so it's the same throughout the entire application
It's initialised once as soon as you use this class, not when you explicitly use the field.
With your property/cache version, you could have two threads trying to get the lock-object and each creating a different one:
Thread 1 checks the cache and doesn't find the object
Thread 1 is parked
Thread 2 checks the cache, doesn't find the object
Thread 2 creates the object and caches it, retrieves it again and returns from the property
Thread 1 resumes
Thread 1 creates a new object and caches it, retrieves it again and returns a different lock object than thread 2 uses
Any further threads will use the lock object of thread 1

Resources