HttpException Request timed out on Ajax Calls - asp.net

I have a web page that has ajax calls on different checkbox selections. At back end web method is called that fills with dataset and returns JSON string response on call. HttpException Request timed out issue is tracked in our error log. This issue is repeating on live server not locally. Almost 100000 users are accessing this page and this is the main page of the site.
I have repeated this issue locally with executionTimeout to set 5 seconds. But on live I can't understand which call is making Httprequest Time Out.
Please suggest if some one has some work around.
Sample code is below:
GetASJSON() -- called by jquery
LoadData() -- called in GetASJSON()
/****
Public Shared Function GetAsJSON() As String -- called by Ajax call from jquery
Dim ds As DataSet = LoadData()
If TotalRecords = 0 Then
ds = LoadData()
Message = "NA"
End If
Dim _serializer = New JavaScriptSerializer()
Dim jSonRes As String = String.Empty
Try
Dim objects As List(Of Object) = New List(Of Object)
Dim i As Integer = 0
For Each row As DataRow In ds.Tables(0).Rows
objects.Add(New With {})
Next
If (objects.Count.Equals(0)) Then
jSonRes = _serializer.Serialize(New With {._Status = "Error", ._Message = "No Arrangement Found"})
Else
jSonRes = _serializer.Serialize(New With {._Status = "OK", ._Data = objects, ._Message = Message})
End If
Return jSonRes
End Function
******/
Private Shared Function LoadData() As DataSet
Dim ds As DataSet
ds = ds = ManagerClass.GetByFilter(param1, param2, param3)
Return ds
End Function

Without having much details about the request timeout value in the live server or knowing what the underlying issue is, you could try to add this to the web.config in your live application which will set the request time out in seconds:
<configuration>
<system.web>
<httpRuntime executionTimeout="300" />
</system.web>
</configuration>
Also, if you are running IIS you can use the Failed Request Tracing. You can set it up to dump traces of any request taking more than X amount of time.

Related

Why can't I consume my webservice more than once?

When I consuming a webservice (asmx) the first time and return a DataTable to my aspx project, everything is ok. However, if I consume the webservice again on that same aspx the previous DataTable object is completely empty. Why is that?
This is my webservice method:
<WebMethod()> _
public Function QueryGeneralText() As DataTable
ds.Reset()
com.Parameters.Clear()
com.CommandText = queryString
com.CommandType = select booksID from Books"
com.Connection = con
conectarBD()
da = New SqlDataAdapter(com)
da.Fill(ds)
con.Close()
Return ds.Tables(0)
End Function
On the aspx.vb section:
Public Sub CreateDatatable()
Dim example1 As DataTable = ws.QueryGeneralText() ' RETURNS DATA
Dim example2 As DataTable = ws.QueryGeneralText() ' RETURNS DATA, BUT EXAMPLE ITS EMPTY
End Sub
It looks like you are using a global ds object - so you function is working on the same resultset.
First time you execute the function it works, nobody else has any results in ds, but next time you already have results there but now your reset drops the results.
If this is true, you might fix it by creating the ds inside the function instead if possible.

How to manitain session values during HttpWebRequest?

In my code I'm sending a HttpWebRequest to a page in my website.
When request sends to this page, It doesn't maintain the Session values.
Below is the code, from where I'm generating the web request:
Public Overloads Shared Function ReadURL(ByVal sUrl As String) As String
Dim sBody As String
Dim oResponse As HttpWebResponse
Dim oRequest As HttpWebRequest
Dim oCookies As New CookieContainer
oRequest = WebRequest.Create("http://localhost:64802/inventory/purchase_order.aspx?id=5654")
oRequest.CookieContainer = oCookies
oResponse = oRequest.GetResponse()
Dim oReader As New StreamReader(oResponse.GetResponseStream())
sBody = oReader.ReadToEnd
oReader.Close()
oResponse.Close()
Return sBody
End Function
Below is the code written on Page_Load of Purchaseorder.aspx.vb:
iDomains_ID = Session("Domains_ID")
iLogin_ID = Session("Login_ID")
sPage = Request.Path
If Request.QueryString.Count > 0 Then sPage &= "?" & Request.QueryString.ToString()
sPage = shared01.Encrypt(sPage, Application("PK"))
If Not User.Identity.IsAuthenticated Or iLogin_ID = 0 Then
Response.Redirect("/login.aspx?page=" & sPage)
Exit Sub
End If
Above code doesn't gets the session values and it redirects to the login page.
So, how i can maintain the session on both pages during HttpWebRequest.
Looking for your replies.
EDIT
I've tried to use CookieContainer class as you can see in above code. But it doesn't work at all.
As an alternative, assuming the calling and called pages are in the same application, you could use the Server.Execute method to load the content of the page without making a separate request to the site:
Public Overloads Function ReadURL(ByVal sUrl As String) As String
Using writer As New StringWriter()
Server.Execute("~/inventory/purchase_order.aspx?id=5654", writer, False)
Return writer.ToString()
End Using
End Function
If I've understood you correctly, you're making a request from one page in your site to another, and you want to send the cookies from the current HttpRequest with your WebRequest?
In that case, you'll need to manually copy the cookies to the CookieContainer:
For Each key As String In Request.Cookies.AllKeys
Dim sourceCookie As HttpCookie = Request.Cookies(key)
Dim destCookie As New Cookie(sourceCookie.Name, sourceCookie.Value, sourceCookie.Path, "localhost")
destCookie.Expires = sourceCookie.Expires
destCookie.HttpOnly = sourceCookie.HttpOnly
destCookie.Secure = sourceCookie.Secure
oCookies.Add(destCookie)
Next
NB: You'll either need to make the ReadUrl function non-Shared, or pass the current HttpRequest as a parameter.
You'll also need to make sure the calling page has EnableSessionState="false" in the <%# Page ... %> directive, otherwise the page you're calling will hang trying to obtain the session lock.
Your code seems like you will need to make a request and a post. The first request will redirect you to your login page. The second will be a request where you post to the login page, which will start the session and (?) store information into the session variables. That post (to the login page) will then redirect you to the page you want.
I used code in this example http://www.codeproject.com/Articles/145122/Fetching-ASP-NET-authenticated-page-with-HTTPWebRe (I tweaked it a bit) to write an application to do this.

jQuery/ASP.NET concurrent Ajax calls

I have a webpage where users can look for clients and select them. After selection they can be send to the webserver through an jQuery Ajax call. On the server database operations and another webservice is called, so this can take a while. That is why I wanted to present a progress bar to the user.
This progressbar is also updated by a Ajax call.
The problem seems to be that asp.net doesn't allow concurrent calls and the session state queues all calls. You can solve this in mvc by setteing the attribute [SessionState(SessionStateBehavior.ReadOnly)]
But I don't find to do this in my page-behind webmethods. Anyway, the worker method is using session state (for security, and updating the session variable for the progressbar).
The progress method is only reading and returning the session variable.
Is there a solution for it, or is another approach necessary?
I am using asp.net 4.
You could set the session mode to readonly at the #Page directive in your markup:
<%# Page Title="Home Page" EnableSessionState="ReadOnly" Language="C#" %>
I have found the solution:
1) The WebMethod only needs to receive the data and start a new thread:
<WebMethod()> _
Public Shared Function importContacts(ByVal contactGuids As String, ByVal campaignGuids As String) As String
Dim paramsList As New List(Of Object)
paramsList.Add(contactGuids)
paramsList.Add(campaignGuids)
paramsList.Add(HttpContext.Current.Session)
Dim th As New Threading.Thread(AddressOf processImport)
th.Start(paramsList)
Return ""
End Function
The Ajax call is ended quickly and on the browser you can start polling for progress.
2) The thread function needs to convert the parameters first, then you can use the session state:
Public Shared Sub processImport(params As Object)
Dim paramsList As List(Of Object) = params
Dim contactGuids As String = paramsList(0)
Dim campaignGuids As String = paramsList(1)
Dim _session As HttpSessionState = paramsList(2)
_session("EmailMarketingDatabase_progress") = 0
...
End Sub
3) The progress WebMethod looks like this:
<WebMethod()> _
Public Shared Function getProgressStatus() As Integer
Return HttpContext.Current.Session("EmailMarketingDatabase_progress")
End Function

Session state lost after HttpWebRequest within AJAX post

I have a bit of strange behaviour in an asp.net web application that involves the session state being lost.
Process
A user logs into the application and the session is set. They then fill out 1 field, and the application then does an AJAX POST to a .asmx web service. Within the web service, I am using a HttpWebRequest to grab data from another server.
This data is then output to the browser.
A few more fields are then filled in, and the data is then again Post to the same web service via an AJAX POST.
Problem
Straight after the HttpWebRequest, I grab the username from a session variable. This works.
On the next AJAX request however, the session no longer exists.
While testing this, I removed the stage at which the HttpWebRequest is called and my session is never lost. So for some reason, the session is removed AFTER my first AJAX POST and before the second AJAX POST only if I am running the HttpWebRequest code.
Code
I am not doing anything fancy in the code. Just doing a simple jQuery AJAX Post
$.ajax({
url: method,
data: params,
type: "POST",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) {
// handle data
},
error: function(xhr,status,error) { }
});
Creating a System.Net.HttpWebRequest and then getting the System.Net.HttpWebResponse out of that.
Then reading a session variable dim username as string = Session(_SESSION_USERNAME).ToString()
I have never noticed this behaviour before when using HttpWebRequest before (not using any AJAX though)
Function Backfill(value As String) As Details
Dim details As Details = Nothing
Dim appSettings As ConfigSettings.AppConfig = ConfigSettings.AppConfig.getConfig()
Dim url As String = appSettings.Settings.BackfillUrl
Dim username As String = appSettings.Settings.BackfillUser
Dim password As String = appSettings.Settings.BackfillPass
Dim expParameters As String = ""
Dim xml As XmlDocument = Nothing
Dim xmlHttp As XMLHTTP = Nothing
Dim nodeList As XmlNodeList = Nothing
Dim node As XmlNode = Nothing
Dim response As String = ""
Dim success As String = ""
'
' REMOVED TO HIDE INFO
expParameters = "<PARAMETERS>" & _
"</PARAMETERS>"
Try
xmlHttp = New XMLHTTP()
xmlHttp.open("POST", url)
xmlHttp.Send(expParameters)
response = xmlHttp.responseText()
xml = New XmlDocument
xml.LoadXml(response)
SaveExperianFile(xml, value)
nodeList = xml.DocumentElement.ChildNodes
node = nodeList.Item(0)
success = node.Attributes.GetNamedItem("success").Value.ToString.Trim
If success.ToLower.Trim = "y" Then
details = SetDetails(xml)
End If
Catch ex As Exception
Finally
If Not xmlHttp Is Nothing Then
xmlHttp.Dispose()
xmlHttp = Nothing
End If
End Try
Return details
End Function
edit
The XMLHTTP Class code can be seen here http://codepaste.net/ymnqsf
edit
Seems as though something strange is happening when I am saving the XMLDocument to my file system.
Private Sub SaveExperianFile(xml As XmlDocument, value As String)
Dim appConfig As ConfigSettings.AppConfig = ConfigSettings.AppConfig.getConfig()
Try
xml.Save(HttpContext.Current.Server.MapPath(appConfig.Settings.SavePath & value & "_backfill.xml"))
Catch ex As Exception
End Try
End Sub
If I don't call this method, then the session is always set.
Question
Do you know what is causing this behaviour?
Can you check if you just loose the session or the whole application is restarted. If you are saving the XML in the virtual directory / web application folder then it might case web application to restart. If many dozen files were added in short succession to each other, that would be a case to restart the App Pool.
just a hunch, but maybe you need to maintain cookies across HttpWebRequests.
have a look at this question for more help.
Http web request doesn't maintaining session

Save changes to Entity model to the database

I'm new to Entity Framework and am expanding an existing codebase. I'm using jQuery to pass the needed info back to the server ajaxy style, so I can't use TryUpdateModel(). Here's the code:
<HttpPost()>
Function UpdateRoster() As JsonResult
Dim model As New Models.ViewModels.PlayerAdmin
Dim jsonString As String = Request.Form("json")
model = Deserialise(Of Models.ViewModels.PlayerAdmin)(jsonString)
For Each playerAdminPlayer As Models.ViewModels.PlayerAdminPlayer In model.Roster
Dim playerToTeam As New DAL.PlayersToTeam
Dim player As DAL.Player = PlayerAdminManager.GetPlayerById(playerAdminPlayer.PlayerId)
player.FirstName = playerAdminPlayer.FirstName
PlayerAdminManager.SaveChanges()
Next playerAdminPlayer
Dim playerAfter As DAL.Player = PlayerAdminManager.GetPlayerById(model.Roster.First.PlayerId)
Return Json(New With {.success = False, .message = playerAfter.FirstName})
End Function
Deserialise is a helper function that converts the incoming JSON string to a vb object.
Things seem to work fine in that player successfully loads from the DB and playerAdminPlayer is the correct object from the JSON string. However, when I call PlayerAdminManager.SaveChanges() (which just passes the call the db.SaveChanges() the result is always 0, even if there is a change (not sure if that is expected).
playerAfter was my attempt to see if changes were actually being saved. It seems to work correctly, in that playerAfter.FirstName is the newly updated first name.
PlayerAdminManager.GetPlayerById(integer) pulls from the DB, so I would think that, since changes are observed in playerAfter, that those changes were saved to the DB. However, when I reload the web page (which pulls from the DB), the old values are there.
Any ideas?
Here are some of the functions I mention:
Function GetPlayerById(ByVal Id As Integer) As DAL.Player
Return Container.Players.Where(Function(o) o.PlayerId = Id And o.IsVisible = True).SingleOrDefault
End Function
Sub SaveChanges()
Dim numberOfChanges As Integer = Container.SaveChanges()
Debug.WriteLine("No conflicts. " & numberOfChanges.ToString() & " updates saved.")
End Sub
EDIT
Container code:
Private _Container As DAL.LateralSportsContainer
Protected ReadOnly Property Container As DAL.LateralSportsContainer
Get
If _Container Is Nothing Then
Dim connStr As New System.Data.EntityClient.EntityConnectionStringBuilder
connStr.ProviderConnectionString = Web.Configuration.WebConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
connStr.Metadata = "res://*/Lateral.csdl|res://*/Lateral.ssdl|res://*/Lateral.msl"
connStr.Provider = "System.Data.SqlClient"
_Container = New DAL.LateralSportsContainer(connStr.ConnectionString)
End If
Return _Container
End Get
End Property
Turns out I was using a non static (shared) Container. I had 2 Manager classes that both inherited from a BaseManager class were the Container was defined. I was executing the query command in one Manager and saving in another.
Doh!

Resources