ASP.NET Crystal Reports image field not showing - asp.net

I am using VS-2008 for asp.net web application. However, I have developed my reports in VS 2005. ( I am reusing some reports that were developed in other project).
The reports work fine except the image field is not displayed. The image field is a 'VARBINARY(MAX)' field in database. Note that when I export my Crystal Report to .pdf the images shows up in the .pdf file.
(* I am able to see an image url in 'Firebug' but getting message 'Load Image failed')
I am using a 'TypedDataset' as DataSource for the Crystal Report.
I fetch the data from database and do a 'DataSet.WriteXML(filename,WriteMode.WriteSchema)'
Here is the code:-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim rgx As Regex = New Regex("[^a-zA-Z0-9 -]")
strComp = rgx.Replace(strComp, "")
strFile = "tempXML" + strComp + ".xml"
Dim dsTemp As New DataSet
dsTemp.Clear()
dsTemp.Tables.Clear()
Dim rptengine As New CrystalDecisions.CrystalReports.Engine.ReportDocument
rptengine.Load(Session("rptname"))
sdate = CType(Session("sdate"), Date)
edate = CType(Session("edate"), Date)
rptHeading = Session("rptHead")
If IO.File.Exists(Server.MapPath("~/" + strFile)) Then
dsTemp.ReadXml(Server.MapPath("~/" + strFile), XmlReadMode.ReadSchema)
'IO.File.Delete(Server.MapPath("~/" + strFile))
Try
If Session("rptname").ToString.Substring(Session("rptname").ToString.LastIndexOf("\") + 1) _
= "Rptemp.rpt" Then
Dim dsReport As New DDL.dsEmpList
dsReport.Tables("dtEmpList").Merge(dsTemp.Tables(0))
rptengine.SetDataSource(dsReport.Tables(0))
ElseIf Session("rptname").ToString.Substring(Session("rptname").ToString.LastIndexOf("\") + 1) _
= "rptDailyAttendance.rpt" Then
Dim dsReport As New DDL.dsDailyReoprt
dsReport.Tables("dtDailyReport").Merge(dsTemp.Tables(0))
rptengine.SetDataSource(dsReport.Tables(0))
End If
Catch ex As Exception
ShowMsg1("Exception : " & ex.Message)
End Try
'**********************assigning CR-ParameterFields*****************************
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As ParameterValues
Dim crParameterDiscreteValue As ParameterDiscreteValue
Dim parameterToDefine As Boolean = False
crParameterFieldDefinitions = rptengine.DataDefinition.ParameterFields
For Each crParameterFieldDefinition In crParameterFieldDefinitions
crParameterDiscreteValue = New ParameterDiscreteValue
crParameterValues = crParameterFieldDefinition.CurrentValues
Select Case crParameterFieldDefinition.Name
Case "sdate"
parameterToDefine = True
crParameterDiscreteValue.Value = sdate
Case "edate"
parameterToDefine = True
crParameterDiscreteValue.Value = edate
Case "heading"
parameterToDefine = True
crParameterDiscreteValue.Value = rptHeading
Case Else
parameterToDefine = False
End Select
If parameterToDefine Then
Try
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
Catch ex As Exception
objdata.writelog(ex.Message, "frmRptEngine", "frmRptEngine_Load", Server.MapPath("~/Reports"))
ShowMsg1("Error in report generation.")
Exit Sub
End Try
End If
Next
rptViewer.ReportSource = Nothing
rptViewer.ReportSource = rptengine
rptViewer.Enabled = True
rptViewer.DataBind()
Else
ShowMsg1("Invalid attempt.")
End If
End Sub

For those of us running migrated projects from .Net 4.0 or lower to 4.5+ I have made an observation. It seems if your page that contains the viewer is in a subdirectory then the image urls are being generated relative to that page and not to the root of the web application. E.g if your page is /gl/accounts.aspx then the image may be /gl/crystalimagehandler.aspx etc
A quick way to fix this is to change your handler mapping to a wildcard ending in crystalimagehandler.aspx or put the following code in Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
var p = Request.Path.ToLower().Trim();
if (p.EndsWith("/crystalimagehandler.aspx") && p!= "/crystalimagehandler.aspx")
{
var fullPath=Request.Url.AbsoluteUri.ToLower();
var index = fullPath.IndexOf("/crystalimagehandler.aspx");
Response.Redirect(fullPath.Substring(index));
}
}

Related

Converting HTML to PDF and attaching to email .NET

I am looking to use PDFSharp to convert a HTML page into a PDF. This then is attached into an email and sent all in one go.
So, I have a aspx page and vb code file in which gets called through a database SQL job.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim ReqUrl As String, WorkflowID As String = String.Empty
Using con As New SqlConnection(GlobalVariables.ConStr)
Using com As New SqlCommand("EXEC App.GetWorkflowToSend", con)
con.Open()
Using dr = com.ExecuteReader
Try
While dr.Read
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
ReqUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + dr.Item("WorkflowLink")
WorkflowID = dr.Item("WorkflowID")
Dim r As String = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + dr.Item("WorkflowLink")
Dim p As String = Server.MapPath("~\Data\Files") + "\" + WorkflowID + ".pdf"
Dim t As Thread = New Thread(CType(
Function()
ConvertHTML(r, p)
SendMail(Nothing, EmailFrom, "email#address", "New PDF Generated " + WorkflowID, r + "<br/>" + p + "<br/>" + WorkflowID, EmailUser, EmailPass, EmailHost, EmailPort, EmailSSL, "", Nothing, p)
End Function, ThreadStart))
t.SetApartmentState(ApartmentState.STA)
t.Start()
Response.Write(r + "<br>")
Response.Write(p)
End While
Catch
SendMail(Nothing, EmailFrom, "email#address", "Error: " + Err.Description, WorkflowID, EmailUser, EmailPass, EmailHost, EmailPort, EmailSSL, "", Nothing)
End Try
End Using
End Using
End Using
End Sub
In the vb code I essentially call a database stored procedure. This returns some records.
For each of these records, I am currently using HttpContext.Current.Request.Url to make up a string which is essentially the the document url.
I also then declare and specify the location as a String of where I want the converted PDF to be stored.
Public Shared Function ConvertHTML(HTMLPage As String, FileName As String) As String
Dim pngfilename As String = Path.GetTempFileName()
Dim res As String = "" ' = ok
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'Try
Using wb As System.Windows.Forms.WebBrowser = New System.Windows.Forms.WebBrowser
wb.ScrollBarsEnabled = False
wb.ScriptErrorsSuppressed = True
wb.Navigate(HTMLPage)
While Not (wb.ReadyState = WebBrowserReadyState.Complete)
Application.DoEvents()
End While
wb.Width = wb.Document.Body.ScrollRectangle.Width
wb.Height = wb.Document.Body.ScrollRectangle.Height
If wb.Height > 3000 Then
wb.Height = 3000
End If
' Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
Dim b As Bitmap = New System.Drawing.Bitmap(wb.Width, wb.Height)
Dim hr As Integer = b.HorizontalResolution
Dim vr As Integer = b.VerticalResolution
wb.DrawToBitmap(b, New Rectangle(0, 0, wb.Width, wb.Height))
wb.Dispose()
If File.Exists(pngfilename) Then
File.Delete(pngfilename)
End If
b.Save(pngfilename, Imaging.ImageFormat.Png)
b.Dispose()
Using doc As PdfSharp.Pdf.PdfDocument = New PdfSharp.Pdf.PdfDocument
Dim page As PdfSharp.Pdf.PdfPage = New PdfSharp.Pdf.PdfPage()
page.Width = PdfSharp.Drawing.XUnit.FromInch(wb.Width / hr)
page.Height = PdfSharp.Drawing.XUnit.FromInch(wb.Height / vr)
doc.Pages.Add(page)
Dim xgr As PdfSharp.Drawing.XGraphics = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
Dim img As PdfSharp.Drawing.XImage = PdfSharp.Drawing.XImage.FromFile(pngfilename)
xgr.DrawImage(img, 0, 0)
doc.Save(FileName)
doc.Close()
img.Dispose()
xgr.Dispose()
End Using
End Using
Return res
End Function
I run the conversion function with these two strings and finally call a mailing function.
PDF Error
The problem I am having at the moment is the attached PDF I receive in the email doesn't contain the correct output and states 'Navigation to the webpage was cancelled'.
http://127.0.0.1/PDF/TTR/4
C:\inetpub\wwwroot\Prod\Data\Files\4.pdf
I also sent the two strings as output within the email and they look ok.
I'm sure there is something small missing whether that be in my conversion function or just in the main code file.

The code for my aspx signup page does not work

Hello the following code for my signup page does not work. when I execute it, it refreshes and stays in the same page. But it is supposed to redirect to a page called message.aspx. The register command works as follows the person trying to register writes in comboboxs their information and then once they finished, they click the button begin which will save all their information and then use it to personalize the message.aspx page and the person will receive an email.
here is the code:
Private Sub cmdRegister_Click(sender As Object, e As System.EventArgs) Handles cmdRegister.Click
Dim status As MembershipCreateStatus
Dim organization As New Org
Dim employee As New Employee
Dim description As New Description(25)
Dim userMembership As MembershipUser
Dim stringBuilder As New StringBuilder
Try
Membership.CreateUser( _
txtUserName.Text, _
txtPassword.Text, _
txtEmail.Text, _
"question", _
"answer", _
True, _
status)
If status.ToString = "Success" Then
organization.GSTRate = 1
organization.QSTRate = 1
organization.AccountStatus = 2
organization.Name = txtOrg.Text
organization.Active = 1
organization.OrgTypeID = cboType.SelectedValue
organization.Create()
organization = Nothing
organization = New Org(txtOrg.Text)
employee.Username = txtUserName.Text
employee.OrgID = organization.ID
employee.FirstName = txtFName.Text
employee.LastName = txtLName.Text
employee.Title = txtTitle.Text
employee.Username = txtUserName.Text
employee.IsAdmin = True
employee.IsSupervisor = True
employee.IsAccountant = False
employee.IsAdvalorem = True
employee.Email = txtEmail.Text
employee.Phone = ""
employee.Create()
Roles.AddUserToRole(employee.Username, "Admin")
userMembership = Membership.GetUser(txtUserName.Text)
stringBuilder.Append(description.EnglishDescription)
stringBuilder.Replace("(name)", employee.FirstName & " " & employee.LastName)
stringBuilder.Replace("(OrgName)", organization.Name)
stringBuilder.Replace("(username)", employee.Username)
stringBuilder.Replace("you must activate your account", "you must <a href='https://www.advataxes.ca/login.aspx?action=activate&id=" + userMembership.ProviderUserKey.ToString + "&username=" + userMembership.UserName + "'>activate your account</a>")
SendEmail(userMembership.Email, "Advataxes: Account created ", stringBuilder.ToString, Session("language"))
Session("NewUserEmail") = userMembership.Email
Response.Redirect("message.aspx?id=364")
Else
lblInvalidUserName.Visible = True
If status.ToString = "DuplicateUserName" Then lblInvalidUserName.Text = "Username already exists"
End If
Catch ex As MembershipCreateUserException
MsgBox(GetErrorMessage(ex.StatusCode))
Catch ex As HttpException
MsgBox(ex.Message)
Finally
userMembership = Nothing
organization = Nothing
employee = Nothing
description = Nothing
End Try
End Sub
Looking at your code, I suspect the code execution is not successfully reaching the Response.Redirect("message.aspx?id=364") line and due to an exception the flow jumps to catch block/
Two possibilities I can think of:
Exception is thrown inside SendEmail method if smtp is not configured
Membership.CreateUser is failing due to incorrect database connectionstring
I suggest you put a breakpoint inside the cmdRegister_Click method and step through the code.

ASP repeater sorting ItemDataBound

I'm having a bit of trouble with ASP Repeaters and trying to sort the data.
So on Page_Load I obtain the datasource as below...
Protected Overloads Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not (Page.IsPostBack) Then
'No need to re-load Occasion because it's done in the PreLoad event
Me.Header.Title = "OCP - " + Occasion.Checklist.name
pnlStatistics.Visible = Not (Occasion.isClosed)
pnlClose.Visible = SecurityHelper.HasRole(SecurityMatchOption.AtLeast, SecurityRole.Manager, _relevantTeam) And Not (Occasion.isClosed)
'initially assume checklist can be closed. any un-signed off task in the item_databound event will disable it.
btnClose.Enabled = True
'Fix Issue 63: rptTask.DataSource = _db.vw_tasklists.Where(Function(o) o.occasionId = Occasion.id).ToList()
rptTask.DataSource = _db.vw_tasklists.Where(Function(o) o.occasionId = Occasion.id).OrderBy(Function(t) t.taskDueDate).ThenBy(Function(t) t.taskDueTime)
However within ItemDataBound we recalculate the task duedate.
Private Sub rptTask_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptTask.ItemDataBound
' Get the data relating to this task 'row'
Dim t = CType(e.Item.DataItem, vw_tasklist)
If e.Item.ItemType = ListItemType.Header Then
Dim thDueDate = CType(e.Item.FindControl("thDueDate"), HtmlTableCell)
thDueDate.Visible = Not (Occasion.isClosed)
End If
'securable buttons
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
' Dynamically create a span element named TASKnnnn, which will be referenced from
' 'child page' links back to this page in order to vertically reposition at the selected task
Dim span = New HtmlGenericControl("span")
span.ID = "TASK" & t.taskId
span.ClientIDMode = ClientIDMode.Static ' prevent ASP.NET element ID mangling
e.Item.FindControl("lblTaskName").Parent.Controls.AddAt(0, span) ' hook it into the repeater row
Dim btnSignoff = CType(e.Item.FindControl("btnSignOff"), Button)
Dim btnComment = CType(e.Item.FindControl("btnComment"), Button)
Dim btnAmend = CType(e.Item.FindControl("btnAmend"), Button)
Dim btnView = CType(e.Item.FindControl("btnView"), Button)
Dim lblSoTime = CType(e.Item.FindControl("lblSOTime"), Label)
Dim lblDueDate = CType(e.Item.FindControl("lblDueDate"), Label)
Dim lblTaskId = CType(e.Item.FindControl("lblTaskId"), Label)
Dim lblTaskName = CType(e.Item.FindControl("lblTaskName"), Label)
lblTaskId.Text = CType(t.taskId, String)
lblTaskName.Text = t.taskName
Dim time = (If(t.taskDueTime Is Nothing, New TimeSpan(0, 23, 59, 59), TimeSpan.Parse(t.taskDueTime)))
Dim dueDateTime As DateTime = (Occasion.started.Date + time)
'Setup up due DateTime for Daily Tasks
Select Case DirectCast(t.taskDayTypeId, helpers.Constants.enDayType)
Case helpers.Constants.enDayType.Daily
lblDueDate.Text = dueDateTime.ToString("dd/MM/yyyy HH:mm")
Exit Select
Case Else
'Calculate the actual due date for non-daily tasks
Dim calculator = New Calculator()
Dim calId = t.taskCalendarId
Dim taskMonthDay = "1"
If Not t.taskMonthDayId Is Nothing Then
taskMonthDay = CType(t.taskMonthDayId, String)
End If
Dim monthDay = _db.MonthDays.First(Function(m) m.id = CInt(taskMonthDay))
Dim calendar As Model.Calendar = Nothing
If Not calId is Nothing Then
calendar = _db.Calendars.First(Function(x) calId.Value = x.id)
End If
Dim potDate = calculator.GetActualDueDate(dueDateTime, monthDay.monthDay, t, calendar)
dueDateTime = (potDate.Date + time)
lblDueDate.Text = dueDateTime.ToString("dd/MM/yyyy HH:mm")
Exit Select
End Select
Therefore once the data is displayed in the repeater the sorting is wrong. I need to be able to sort the data after the due date re-calculation. How is this possible?
Thanks
You can to move the ItemDataBound logic up into the original query:
rptTask.DataSource = _db.vw_tasklists.
Where(Function(o) o.occasionId = Occasion.id).
Select(
Function(r)
'Fill in the logic here so the DueProperty has your real Due Date
New With {.Row = r, .DueDate = r.TaskDueDate + r.TaskDueTime}
End Function
OrderBy(Function(t) t.DueDate). ' Now we only need one OrderBy (the time is already included).
Select(Function(r) r.Row) 'But we do want to select back to the original record for the databinding
'And the ToList() was probably NEVER needed or helpful in this situation
Moreover, since this looks like linq-to-sql I might break that up a bit, so we cleanly separate what we expect to execute on the database from what we expect to execute on the web server:
'This runs on the databsae
Dim sqlData = _db.vw_tasklists.
Where(Function(o) o.occasionId = Occasion.id)
'This runs on the web server
rptTask.DataSource = sqlData.
Select(
Function(r)
'Fill in the logic here so the DueProperty has your real Due Date
New With {.Row = r, .DueDate = r.TaskDueDate + r.TaskDueTime}
End Function
OrderBy(Function(t) t.DueDate). ' Now we only need one OrderBy (the time is already included).
Select(Function(r) r.Row) 'But we do want to select back to the original record for the databinding
'And the ToList() was probably NEVER needed or helpful in this situation
Of course, you'll get the best results if you start putting information into the database such that you can effectively sort your data correctly there at the outset.

PDFs missing EOF section on customer's server

Folks- I'm relatively new to ASP.NET, and have a question that has stumped my peers-- folks much more experienced than myself.
My company created a website that uses iTextSharp to build and stream PDFs. The functionality works perfectly on my company's development and staging/test servers. The customer's functionality isn't working well, however. The customer's server streams a file where the PDF is missing the last block of data representing the EOF section. The PDF seems to build correctly, streams correctly, but when users open the PDF, the following error displays: 'There was an error opening this document. The file is damaged and could not be repaired.'
By comparing the PDFs in a text viewer (comparing the PDFs from my server vice the customer's server), I can see that the EOF section is missing from the customer's PDF. I'll also note that no errors are thrown during PDF creation, if that's helpful. To make matters more difficult, I have no access to the customer's servers, so I won't be able to interact with the systems directly.
The asp.net version is 3.5. Both of our servers (my company and the customer) are: running IIS7.5 on Server 2008R2; using iTextSharp is 5.1.2; and are configured for FIPS compatibility.
I've read dozens and dozens of posts detailing why a PDF isn't created properly, why it may not be streaming, and all things related, but I haven't seen this particular issue before. I guess what I need to know in the short-term is: 1) what can I provide to help diagnose the issue, 2) where is a good place to start looking for areas of concern?
Also, I updated to revision 5.5.3 last night; same results-- it works fine on my servers, but produces broken PDFs on the customer's server.
Code added:
Public Function BuildReport(ByVal tblReport As DataTable, _
ByRef memStream As MemoryStream, _
ByRef strErrMsg As String) As Boolean
Dim booOK As Boolean = True
strErrMsg = String.Empty
' Create document
Try
' Create writer (listens to the document and directs PDF stream)
memStream = New MemoryStream()
Dim msWriter As PdfWriter = PdfWriter.GetInstance(_document, memStream)
msWriter.CloseStream = False
'Create header
Dim ev As New itsEvents
msWriter.PageEvent = ev
' Set document metadata
_document.AddTitle(_strMetaTitle)
_document.AddSubject(_strMetaSubject)
_document.AddCreator(_strMetaApplication)
_document.AddAuthor(_strMetaAuthor)
' Open document, add document content, close document
_document.Open()
AddReportContent(tblReport)
_document.Close()
Catch ex As Exception
booOK = False
strErrMsg = ex.Message
End Try
Return booOK
End Function
Private Sub AddReportContent(ByVal tblReport As DataTable)
' Count report columns
Dim intReportColumns As Integer = 0
For Each col As DataColumn In tblReport.Columns
If ContainedInColumnMask(col.ColumnName) Then
intReportColumns += 1
End If
Next
' Build table
Dim table As PdfPTable
Dim cell As PdfPCell
Dim phrase As Phrase
If intReportColumns >= 1 Then
' Init table
table = New PdfPTable(intReportColumns)
' Add title to table
'phrase = New Phrase(_strMetaTitle, _fontLarge)
'cell = New PdfPCell(phrase)
'cell.Colspan = intReportColumns
'cell.HorizontalAlignment = 1 ' 0=Left, 1=Centre, 2=Right
'table.AddCell(cell)
' Add column headers to table
Dim i As Integer = 0
Dim intColWidth As Integer
Dim intColWidths As Integer() = New Integer(intReportColumns - 1) {}
Dim intColWidthTotal As Integer = 0
Dim strColName As String
For Each col As DataColumn In tblReport.Columns
If ContainedInColumnMask(col.ColumnName) Then
strColName = col.ColumnName
If (col.ExtendedProperties.Item("NOTEXTEXPORT") <> True) Then
If col.ExtendedProperties.Contains("FRIENDLYNAME") Then
strColName = col.ExtendedProperties.Item("FRIENDLYNAME")
End If
End If
phrase = New Phrase(strColName, _fontMedium)
cell = New PdfPCell(phrase)
cell.BorderWidth = 1
cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
'cell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY
table.AddCell(cell)
intColWidth = GetColumnWidth(col, strColName, _fontMedium.Size, _fontSmall.Size)
intColWidths(i) = intColWidth
intColWidthTotal += intColWidth
i += 1
End If
Next
table.TotalWidth = intColWidthTotal
table.SetWidths(intColWidths)
' Add rows to table
For Each row As DataRow In tblReport.Rows
For Each col As DataColumn In tblReport.Columns
If ContainedInColumnMask(col.ColumnName) Then
phrase = New Phrase(SetBlankIfNothing(row.Item(col.ColumnName).ToString()), _fontSmall)
cell = New PdfPCell(phrase)
cell.BorderWidth = 0.5
table.AddCell(cell)
End If
Next
Next
Else
' Init table
table = New PdfPTable(1)
' Nothing to add to table
table.AddCell(String.Empty)
End If
' Add table to document
_document.Add(table)
End Sub
Public Sub New(ByVal strMetaTitle As String, _
ByVal strMetaSubject As String, _
ByVal strMetaApplication As String, _
ByVal strMetaAuthor As String, _
Optional ByVal strColumnMask As String = "")
GetStaticInfo()
_strMetaTitle = strMetaTitle
_strMetaSubject = strMetaSubject
_strMetaApplication = strMetaApplication
_strMetaAuthor = strMetaAuthor
_document = New iTextSharp.text.Document(_itsPage, _itsMarginLeft, _itsMarginRight, _itsMarginTop, _itsMarginBottom)
If strColumnMask <> "" And Not strColumnMask Is Nothing Then
_strColumnMask = strColumnMask
End If
End Sub
Public Sub New(ByVal strMetaTitle As String, _
ByVal strMetaSubject As String, _
ByVal strMetaApplication As String, _
ByVal strMetaAuthor As String, _
Optional ByVal strColumnMask As String = "")
GetStaticInfo()
_strMetaTitle = strMetaTitle
_strMetaSubject = strMetaSubject
_strMetaApplication = strMetaApplication
_strMetaAuthor = strMetaAuthor
_document = New iTextSharp.text.Document(_itsPage, _itsMarginLeft, _itsMarginRight, _itsMarginTop, _itsMarginBottom)
If strColumnMask <> "" And Not strColumnMask Is Nothing Then
_strColumnMask = strColumnMask
End If
End Sub

how to find a Last Modified Date of a webPage?

i have a problem in my project to find the Last Modified date of a site..
is any code to find that in asp.net
thanks in advance..
Check out this question
How can you mine the "Last Modified Date" for an ASP.NET page which is based on a Master Page?
the basic code you need is this
Dim strPath As String = Request.PhysicalPath
Label1.Text = "Modified: " + System.IO.File.GetLastWriteTime(strPath).ToString()
FileInfo.LastWriteTime should give you what you need:
System.IO.File.GetLastWriteTime(Request.PhysicalPath).ToString();
According to your comment on the other answer, you instead want to get the last modified time of any web-site (not your own ASP.NET page). You could use Net.HttpWebRequest to request a given URL to get the LastModified property of the HttpResponse:
Protected Sub GetLastModifiedTimeOfWebPage(sender As Object, e As EventArgs)
Dim url = Me.TxtURL.Text.Trim
If Not url.StartsWith("http:") Then url = "http://" & url
Dim ResponseStatus As System.Net.HttpStatusCode
Dim lastModified As Date
Try
lastModified = RequestLastModified(url, ResponseStatus)
Catch ex As System.Exception
' log and/or throw
Throw
End Try
If ResponseStatus = Net.HttpStatusCode.OK Then
Me.LblLastModified.Text = lastModified.ToString
End If
End Sub
Public Shared Function RequestLastModified( _
ByVal URL As String, _
ByRef retStatus As Net.HttpStatusCode
) As Date
Dim lastModified As Date = Date.MinValue
Dim req As System.Net.HttpWebRequest
Dim resp As System.Net.HttpWebResponse
Try
req = DirectCast(Net.HttpWebRequest.Create(New Uri(URL)), Net.HttpWebRequest)
req.Method = "HEAD"
resp = DirectCast(req.GetResponse(), Net.HttpWebResponse)
retStatus = resp.StatusCode
lastModified = resp.LastModified
Catch ex As Exception
Throw
Finally
If resp IsNot Nothing Then
resp.Close()
End If
End Try
Return lastModified
End Function
Note: Many sites lie with this property and return only the current time.

Resources