ASP.Net page methods execution time monitoring - asp.net

could anybody advice me, are there any approaches to calculate the methods execution time in asp.net page?
ASP.Net Trace doesn't suit me since it ignores ajax partial postbacks though just they are the tight place.
I have the page event which for some unknown reason executes slowly. Since the logic and event execution chain is rather complicated, I still unable to merely determine the culprit in debugger.
I'd like to measure the execution time of each method throughout the page, but I still see no way but insert redundant code lines (like timeBegin = DateTime.Now.... timeEnd=DateTime.Now = timeBegin etc) in the beginning and ending of each method. It seems to be ugly approach, does anybody know how to do it automatically? Are there tools which measure the methods execution time available?

I am not 100% sure the below works in all cases. So far it does though. Note that Context.Session.Item("CURRENT_WEB_USER") is where I store the current user, and is therefore not readily available as part of the asp.net session variables.
The code hereunder is in replacement of Global.aspx that allows both full page timing and timing of developer code.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_AcquireRequestState(sender As Object, e As System.EventArgs)
If HttpContext.Current Is Nothing Then Return
If HttpContext.Current.Session Is Nothing Then Return
If TypeOf HttpContext.Current.CurrentHandler Is Page Then
If Not Context.Items.Contains("Request_Start_Time") Then
Dim MyPage As Page = HttpContext.Current.CurrentHandler
AddHandler MyPage.Init, AddressOf PageInitEncountered
AddHandler MyPage.Unload, AddressOf PageUnloadEncountered
Context.Items.Add("Request_Start_Time", DateTime.Now)
Dim User As String = Context.Session.Item("CURRENT_WEB_USER")
Context.Items.Add("Request_User", User )
End If
End If
End Sub
Sub Application_ReleaseRequestState(sender As Object, e As System.EventArgs)
If HttpContext.Current Is Nothing Then Return
If TypeOf Context.CurrentHandler Is Page Then
Dim Page As Page = Context.CurrentHandler
Dim StartDate As Date = Context.Items("Request_Start_Time") : If StartDate = Nothing Then Return
Dim EndDate As Date = Now
Dim StartProc As Date = Context.Items("Page_Init")
Dim EndProc As Date = Context.Items("Page_Unload")
Dim User As String = Context.Items("Request_User")
LogEntry(StartDate, EndDate, StartProc, EndProc, User, Context.Request.Url.ToString)
End If
End Sub
Public Sub PageInitEncountered(sender As Object, e As System.EventArgs)
Context.Items.Add("Page_Init", DateTime.Now)
End Sub
Public Sub PageUnloadEncountered(sender As Object, e As System.EventArgs)
Context.Items.Add("Page_Unload", DateTime.Now)
End Sub
Public Sub LogEntry(StartDate As Date, EndDate As Date, StartProc As Date, EndProc As Date, User As String, PageURL As String)
System.Diagnostics.Debug.WriteLine(" (" & LogEntry.RequestMs & " - " & LogEntry.DurationMs & ") (" & User & ") " & PageURL)
End Sub

This may not be what you are looking for, but RedGate has a product called Performance Profiler that does exactly that. They do have a 15 day trial so you can even download it and try it out on your current issue. IMHO, it's worth every penny.

You can use asp.net performance counters and other things also. But that will not measure a page speed but they will measure a over all application performance.

Related

Filtering SQL Query using predefined filters

I've pasted my code below. What I'm trying to do is filter a set of data using the day. The 'day' field is stored as the abbreviated day name, so "thu" for Thursday etc. This works perfectly fine, except once you've changed the date filter to something else, the option for the current day doesn't work.
For example, today is Sunday. When the page loads, it filters out all listings that are not for Sunday, as it should. On a small group of LinkButton controls, if you click any other day of the week, it will change and show the option for the selected day, again, as it should do. However, when you try and set the filter to Sunday again, or click the "today" button, it won't change.
Based on my code, can anyone see what is wrong? If it is of any help, my data is on a remote SQL server.
VB Code:
Dim DateVal As Date = DateTime.UtcNow()
Dim DateName As String = DateVal.ToString("ddd")
Protected Sub btnMon_Click(sender As Object, e As EventArgs) Handles btnMon.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Mon"
End Sub
Protected Sub btnTue_Click(sender As Object, e As EventArgs) Handles btnTue.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Tue"
End Sub
Protected Sub btnWed_Click(sender As Object, e As EventArgs) Handles btnWed.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Wed"
End Sub
Protected Sub btnThu_Click(sender As Object, e As EventArgs) Handles btnThu.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Thu"
End Sub
Protected Sub btnFri_Click(sender As Object, e As EventArgs) Handles btnFri.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Fri"
End Sub
Protected Sub btnSat_Click(sender As Object, e As EventArgs) Handles btnSat.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Sat"
End Sub
Protected Sub btnSun_Click(sender As Object, e As EventArgs) Handles btnSun.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = "Sun"
End Sub
Protected Sub btnAll_Click(sender As Object, e As EventArgs) Handles btnToday.Click
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = DateName
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
SqlDataSource1.SelectParameters("FiltDay").DefaultValue = DateName
End Sub
TSQL (If it helps)
SELECT Schedule.SlotID, RIGHT('00' + CONVERT(VARCHAR(2), Schedule.StartHr), 2) + ':' + RIGHT('00' + CONVERT(VARCHAR(2), Schedule.StartMin), 2) AS StartTime,
Schedule.ProgrammeID, Schedule.Day, RIGHT('00' + CONVERT(VARCHAR(2), Schedule.EndHr), 2) + ':' + RIGHT('00' + CONVERT(VARCHAR(2), Schedule.EndMin), 2)
AS EndTime, Programmes.ProgrammeName, Programmes.Description, Programmes.PresenterID, Presenters.PresenterName, Presenters.PhotoURL
FROM Presenters CROSS JOIN
Programmes CROSS JOIN
Schedule
WHERE (Schedule.Day = #FiltDay)
maybe it is not 100% related to your issue but you should not handle the datasource initialization on the event of a different control.
your need is to fill the sql parameter so you should handle the Selecting event of the datasource.
on click of your buttons set the proper value for your variable DateName and on selecting of the datasource fill the sql parameter using your variable.
acting this way you can easily spot the actual value fed into the call and identify the issue.

Jump to Page in C1PrintDocument

I have a form in my application that is used for previewing a report. It has a C1Ribbon at the top which contains navigation buttons, and a C1PrintPreview displaying in a PreviewPane.
I want the navigation buttons in the ribbon (first, previous, next, last), as well as a text box in which to enter a specific page number, to navigate through the preview of the report accordingly. So far, all the documentation and samples I've found have dealt only with adding hyperlinks directly to the report itself...so I'm having a hard time adapting it to my use.
Below is what I have so far...I don't get any build or run-time errors, it just doesn't do anything.
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Dim nextPage As C1LinkTargetPage = New C1LinkTargetPage(PageJumpTypeEnum.Next)
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
Dim lastPage As C1LinkTargetPage = New C1LinkTargetPage(PageJumpTypeEnum.Last)
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
Dim prevPage As C1LinkTargetPage = New C1LinkTargetPage(PageJumpTypeEnum.Previous)
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
Dim firstPage As C1LinkTargetPage = New C1LinkTargetPage(PageJumpTypeEnum.First)
End Sub
Private Sub Navigation_KeyDown(sender As Object, e As KeyEventArgs) Handles txtPageNum.KeyDown
If e.Modifiers = Keys.Enter Then
Dim setPage As C1LinkTargetPage = New C1LinkTargetPage(PageJumpTypeEnum.Absolute)
'setPage. = CInt(txtPageNum.Text)
If setPage.PageNo = 0 Then
'what to do if number entered is not a page in document
End If
End If
End Sub
I realize it's likely just because even though I make a C1LinkTargetPage, I don't tell the app what to do with it after that. But I'm not sure how to go about doing that - it's not like there's a "jumptopage" method for the C1PrintPreview (wish it were that easy). Buttons in the ribbon don't have a hyperlink property, so I can't set that when the form loads as in all the samples I found. Not sure where to go from here...
Also I don't even know how I'm supposed to be able to use the Absolute PageJumpTypeEnum...PageNo is read only.
Thank you!
UPDATE 2/25:
I learned that I should be dealing with properties of the Preview Pane...not the C1PrintDocument. With the code below, the navigation buttons and specifying a page number work. My only problem now then is displaying the current page in that page number box. With what I have, PreviewPane.CurrentHistoryEntry just goes to 1 (even if I was on a page other than 1 before-hand).
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
PreviewPane.DoGoNextPage()
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
Dim lastPage As DocumentLocation = New DocumentLocation(report.Pages(report.Pages.Count - 1))
PreviewPane.GotoDocumentLocation(lastPage)
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
PreviewPane.DoGoPreviousPage()
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
Dim firstPage As DocumentLocation = New DocumentLocation(report.Pages(0))
PreviewPane.GotoDocumentLocation(firstPage)
End Sub
Private Sub Navigation_KeyDown(sender As Object, e As KeyEventArgs) Handles txtPageNum.KeyDown
If e.KeyValue = Keys.Enter Then
Dim pageNum As Integer = CInt(txtPageNum.Text)
If (pageNum > 0) And (pageNum <= report.Pages.Count) Then
Dim setPage As DocumentLocation = New DocumentLocation(report.Pages(pageNum - 1))
PreviewPane.GotoDocumentLocation(setPage)
Else
txtPageNum.Text = PreviewPane.CurrentHistoryEntry.ToString
End If
End If
End Sub
They key was "PreviewPane.StartPageIdx"
txtPageNum.Text = (PreviewPane.StartPageIdx + 1).ToString

Web Controls Not Talking to Each other in ASP.NET using VB.NET

I have an asp.net page that loads two controls, Control A and Control B. Control A has some generic form submit and clear buttons that trigger click events in its' own code behind which use reflection to call the update function in Control B which has a few input fields. I have debugged this and everything seems to be in order, however; when the update function in control B is called the input fields are not returning a value when using inputname.text or me.inputname.text. Does anyone have any ideas why this is not working? Any guidance would be appreciated.
This is the code in Control A's codebehind which calls the update method in Control B's code behind
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = Session("SelectedQstnCtl")
Dim methodObj = lctlControl.GetType().GetMethod("UpdateGenInfo", BindingFlags.NonPublic Or BindingFlags.Instance)
' Execute UpdateGenInfo method to update the data
methodObj.Invoke(lctlControl, Nothing)
Catch ex As Exception
'TODO: check for concurrency error here
End Try
End Sub
This is the update function in Control B that is being called. The session values are being passed, but the form fields are not.
Protected Sub UpdateGenInfo()
Dim lclUtil As New clUtility
Dim genInfo As New clGenInfo
Try
Dim dt As Integer
'Update Data for 1-2
dt = genInfo.UpdateGenInfo_E1_01_02(Session("ConnStrEP"), Me.varLastUpdate, Session("AppNo"), Session("RevNo"), _
Me.txtPrName.Text, Me.txtPrAddr1.Text, Me.txtPrAddr2.Text, _
Me.txtPrCity.Text, Me.txtPrState.Text, Me.txtPrZip.Text)
Catch ex As Exception
'Display error
lclUtil.DisplayMsg(Me.lblErrMsg, String.Format("Error Location: Sub LoadGenInfo (ctlE1_01_02) {0}", ex.Message))
End Try
End Sub
The most likely cause is that the control instance stored in the session is not the control instance on the current page. For example, if you're storing the control instance in the session when the page is first loaded, and retrieving it on post-back, it will be a different instance.
If you can't give Control A a direct reference to Control B, then change your code to store the reference in the Page.Items collection:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.Items("SelectedQstnCtl") = TheSelectedQstnCtl
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Dim lctlControl = DirectCast(Page.Items("SelectedQstnCtl"), YourControlClass)
lctlControl.UpdateGenInfo()
End Sub
I see you are using reflection which might be an overkill for that task.Try referencing the method in the control directly.Make then method UpdateGenInfo public and then reference it like this.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = CType(Session("SelectedQstnCtl"),YourControlClass)
lctlControl.UpdateGenInfo()
Catch ex As Exception
End Sub
Public Function UpdateGenInfo()
'your code here
Catch ex As Exception
End Try
End Function
This way you can easily trace where your values are getting lost.Let me know how it goes.
Try yet another simple approach working demo here
In control a
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim testb1 = CType(Me.NamingContainer.FindControl("testb1"), testb)
testb1.UpdateGenInfo()
End Sub
In control b
Public Function UpdateGenInfo()
Try
Dim a = Me.TextBox1.Text
Catch ex As Exception
End Try
End Function
Aspx Parent Page
<uc1:testa ID="testa1" runat="server" />
<uc2:testb ID="testb1" runat="server" />
The controls in testb are in an update panel.Try this and let me know if this works.

CheckBoxList.Selected keeps coming back with False value

I have a CheckBoxList on my page that isn't behaving very well.
The idea is that once the submit button on the form is clicked, the app should clear the database table of all rows pertaining to the specific user and then re-insert new ones based on the user's CheckBoxList selections.
The problem is that regardless of whether or not any (or all) items in the CheckBoxList are selected, the app keeps getting Selected = False.
Here's my code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
loadRegions()
End Sub
Private Sub loadRegions()
Dim db As New Database
Dim sql As String = "select * from regions"
Dim dr As MySqlDataReader = db.execDB(sql, "Text", Nothing, "DataReader", False)
If dr.HasRows Then
cblRegion.DataSource = dr
cblRegion.DataTextField = "regionname"
cblRegion.DataValueField = "regionid"
cblRegion.DataBind()
End If
dr.Close()
End Sub
Protected Sub btnRegister_Click(sender As Object, e As System.EventArgs) Handles btnRegister.Click
' ============================================================
' There's more code in here, but it's irrelevant to this paste
' ============================================================
Dim sql As String = "delete from userregions where userid = " & lblUserID.Text & ";"
For i As Integer = 0 To cblRegion.Items.Count - 1
If cblRegion.Items(i).Selected Then
sql &= "insert into userregions (userid, regionid)" & _
"values(" & UserID & ", " & cblRegion.Items(i).Value & ")"
db.execDB(sql, "Text", Nothing, "None", False)
End If
Next
End Sub
For the record
I'm aware of the potential for SQL Injection here. I'll be going over to using Parameters as soon as I have the loop working.
Thanks for your time.
Any help will be greatly appreciated.
You only need to call loadRegions on the initial load and not on postbacks:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
loadRegions()
End If
End Sub
Otherwise you'll lose changed values and events are not triggered.
Add this line of copde "If IsPostBack Then Return" in Page_Load method.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then Return
loadRegions()
End Sub
In page loaded, write the following:
If Not IsPostBack
loadRegions()
End If

Global.asax breaks with AJAX Control Toolkit

Everything was working fine. Then I added the Global.asax and suddenly got this error:
Line: 4723
Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near 'eeCtrl_Data = null;|
<%# Application Language="VB" %>
<script runat="server">
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to StateServer
' or SQLServer, the event is not raised.
End Sub
Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)
HttpContext.Current.Items("renderStartTime") = DateTime.Now
End Sub
Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As System.EventArgs)
Dim startTime As DateTime = CType(HttpContext.Current.Items("renderStartTime"), DateTime)
Dim renderTime As TimeSpan = DateTime.Now - startTime
HttpContext.Current.Response.Write("<!-- Render Time (in milliseconds): " & renderTime.TotalMilliseconds.ToString & " -->")
End Sub
Try commenting out this line and see if that fixes it.
HttpContext.Current.Response.Write("<!-- Render Time (in milliseconds): " & renderTime.TotalMilliseconds.ToString & " -->")
HTH.
This is not elegant, but it works for my needs (thankfully this is an internal app). It's a two-part solution. One is for the postbacks that occur due to an UpdatePanel postback. The other is for regular postback.
I'd rather not close this thread, because I think better solutions can be presented.

Resources