I'd like to manually change the date and time for a specified time by invoking SetFileTime or something similar but on ASP Classic. As far as I know, ASP File Object provides method for retrieving the creation & modification times for the file but provides no methods for actually setting them.
How can I achieve this?
I found the answer relatively quickly:
Sub ModifyLastAccessedDate(emlFilePath, newDate)
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set file = objFSO.GetFile(emlFilePath)
Set app = Server.CreateObject("Shell.Application")
Set folder = app.NameSpace(file.ParentFolder & "\")
Set fileModify = folder.ParseName(file.Name)
fileModify.ModifyDate = NewDate
Set objFSO = Nothing
Set file = Nothing
Set folder = Nothing
Set app = Nothing
Set fileModify = Nothing
End Sub
And then you just call the routine by
Call ModifyLastAccessedDate("C:\Folder\SomeFile.Txt","2013-03-05")
Here is an example in JScript, and again in VB, taken directly from Microsoft just for posterity (and as another example of how the date and time string can be set):
<script language="JScript">
function fnModifyDateGetSetJ()
{
var objShell = new ActiveXObject("shell.application");
var objFolder2;
var ssfWINDOWS = 36;
objFolder2 = objShell.NameSpace(ssfWINDOWS);
if (objFolder2 != null)
{
var objFolderItem;
objFolderItem = objFolder2.ParseName("NOTEPAD.EXE");
if (objFolderItem != null)
{
var szReturn;
szReturn = objFolderItem.ModifyDate;
objFolderItem.ModifyDate = "01/01/1900 6:05:00 PM";
}
}
}
</script>
VB:
Private Sub fnModifyDateGetSetVB()
Dim objShell As Shell
Dim objFolder2 As Folder2
Dim ssfWINDOWS As Long
ssfWINDOWS = 36
Set objShell = New Shell
Set objFolder2 = objShell.NameSpace(ssfWINDOWS)
If (Not objFolder2 Is Nothing) Then
Dim objFolderItem As FolderItem
Set objFolderItem = objFolder2.ParseName("NOTEPAD.EXE")
If (Not objFolderItem Is Nothing) Then
Dim szReturn As String
szReturn = objFolderItem.ModifyDate
objFolderItem.ModifyDate = "01/01/1900 6:05:00 PM"
Else
'FolderItem object returned nothing.
End If
Set objFolderItem = Nothing
Else
'Folder object returned nothing.
End If
Set objFolder2 = Nothing
Set objShell = Nothing
End Sub
Related
This topic is related to Loop through links and download PDF's
I am trying to convert my current VBA code into VBScript. I have already understood that I have to remove the variable types (As ... part of Dim statements) and use CreatObject to get those objects but otherwise everything should port as-is. DoEvents will also have to be replaced with something like Wscript.sleep.
I came up with some problems. Currently while running VBS file I am getting an error saying "Object required: 'MSHTML'". Pointing to line 65, where I have Set hDoc = MSHTML.HTMLDocument. I have tried to search on Google but got nothing helpful for this one.
How I should proceed with this one?
DownloadFiles("https://www.nordicwater.com/products/waste-water/")
Sub DownloadFiles(p_sURL)
Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim xHttp
Dim hDoc
Dim Anchors
Dim Anchor
Dim sPath
Dim wholeURL
Dim internet
Dim internetdata
Dim internetlink
Dim internetinnerlink
Dim arrLinks
Dim sLink
Dim iLinkCount
Dim iCounter
Dim sLinks
Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = False
internet.navigate (p_sURL)
Do Until internet.ReadyState = 4
Wscript.Sleep 100
Loop
Set internetdata = internet.document
Set internetlink = internetdata.getElementsByTagName("a")
i = 1
For Each internetinnerlink In internetlink
If Left(internetinnerlink, 36) = "https://www.nordicwater.com/product/" Then
If sLinks <> "" Then sLinks = sLinks & vbCrLf
sLinks = sLinks & internetinnerlink.href
i = i + 1
Else
End If
Next
wholeURL = "https://www.nordicwater.com/"
sPath = "C:\temp\"
arrLinks = Split(sLinks, vbCrLf)
iLinkCount = UBound(arrLinks) + 1
For iCounter = 1 To iLinkCount
sLink = arrLinks(iCounter - 1)
'Get the directory listing
xHttp.Open "GET", sLink
xHttp.send
'Wait for the page to load
Do Until xHttp.ReadyState = 4
Wscript.Sleep 100
Loop
'Put the page in an HTML document
Set hDoc = MSHTML.HTMLDocument
hDoc.body.innerHTML = xHttp.responseText
'Loop through the hyperlinks on the directory listing
Set Anchors = hDoc.getElementsByTagName("a")
For Each Anchor In Anchors
'test the pathname to see if it matches your pattern
If Anchor.pathname Like "*.pdf" Then
xHttp.Open "GET", wholeURL & Anchor.pathname, False
xHttp.send
With CreateObject("Adodb.Stream")
.Type = 1
.Open
.write xHttp.responseBody
.SaveToFile sPath & getName(wholeURL & Anchor.pathname), 2 '//overwrite
End With
End If
Next
Next
End Sub
Function:
Function getName(pf)
getName = Split(pf, "/")(UBound(Split(pf, "/")))
End Function
Instead of Set hDoc = MSHTML.HTMLDocument, use:
Set hDoc = CreateObject("htmlfile")
In VBA/VB6 you can specify variable and object types but not with VBScript. You have to use CreateObject (or GetObject: GetObject function) to instantiate objects like MSHTML.HTMLDocument, Microsoft.XMLHTTP, InternetExplorer.Application, etc instead of declaring those using Dim objIE As InternetExplorer.Application for example.
Another change:
If Anchor.pathname Like "*.pdf" Then
can be written using StrComp function:
If StrComp(Right(Anchor.pathname, 4), ".pdf", vbTextCompare) = 0 Then
or using InStr function:
If InStr(Anchor.pathname, ".pdf") > 0 Then
Also, at the beginning of your sub, you do the following:
Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim xHttp
You should declare your variables before assigning them values or objects. In VBScript this is very relaxed, your code will work because VBScript will create undefined variables for you but it's good practice to Dim your variables before using them.
Except for Wscript.sleep commands, your VBScript code will work in VB6/VBA so you can debug your script in VB6 or VBA apps (like Excel).
I have a old VBScript function that save a file copy on the server from the URL. If the file already exists the function deletes the previous version and rewrites a new file version. The problem is that I need to insert case sensitive file names. For instance, the file names "Test.html" and "test.html" should be saved as different copys and my function just replaces them. Any suggestion?
The function:
Public Function SaveToChache(Url, SaveToFolder, FileName)
Dim ChacheFolder: ChacheFolder = SaveToFolder 'Folder where will the cache files be stored (include trailing slash)
Dim FilePath: FilePath = Server.MapPath(ChacheFolder & FileName)
Dim objXMLHTTP: Set objXMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
objXMLHTTP.open "GET", Url, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Dim objADOStream: Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
Dim objFSO: Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.FileExists(FilePath) Then objFSO.DeleteFile FilePath
Set objFSO = Nothing
objADOStream.SaveToFile FilePath
objADOStream.Close
Set objADOStream = Nothing
SaveToChache = objXMLHTTP.getResponseHeader("Content-Type")
Else
SaveToChache = ""
End if
Set objXMLHTTP = Nothing
End Function
Calling the function:
savefile = SaveToChache("http://www.example.com", "/cache/", "Test.html")
Thanks!
I would use a direct compare instead of objFSO.FileExists.
for example:
Dim objFSO: Set objFSO = Createobject("Scripting.FileSystemObject")
FilePath = "C:\Test\test.txt"
'Get path to file
strParentPath = objFSO.GetFile(FilePath).ParentFolder
'Get each file in the folder
Set objCheck = objFSO.GetFolder(strParentPath).Files
For Each x In objCheck
If x = FilePath Then objFSO.DeleteFile(FilePath)
Next
Basically, x will only equal FilePath if the case is also the same.
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));
}
}
I have the below code in my current solution, which returns an error of 'The value '' is invalid'. The below snippet has been shortened to just show the problem area as opposed to the entire ActionResult.
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
However, in a previous project, I have used exactly the same code, even the view is the same, but it still returns the above error.
Everything is receiving a value ok.
The only thing that's different is that it's a different project.
I'm at a bit of a loss with this one.
Anyone have any ideas?
EDIT For reference, here is the entire ActionResult.
'
' POST: /Calls/Details/5
<Authorize()> _
<AcceptVerbs(HttpVerbs.Post)> _
<ValidateInput(False)> _
Function Details(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
Dim calls As hdCall = callRepository.GetCall(id)
ViewData("MyCallID") = calls.CallID
ViewData("UserThatLogged") = calls.UserID
ViewData("TimeLogged") = calls.loggedOn.ToLongDateString & " " & calls.loggedOn.ToLongTimeString
ViewData("Title") = calls.Title
Dim dataContext As New CustomerServiceModelDataContext
ViewData("Status") = New SelectList(dataContext.hdStatus, "StatusID", "Status", calls.StatusID)
ViewData("Type") = New SelectList(dataContext.hdCategories, "CategoryID", "Title", calls.CategoryID)
ViewData("Company") = calls.hdCompany.Company
ViewData("Priority") = New SelectList(dataContext.hdPriorities, "PriorityID", "Priority", calls.PriorityID)
ViewData("CallDetails") = calls.CallDetails
ViewData("Customer") = calls.hdCustomer.CustomerName
ViewData("CustomerID") = calls.hdCustomer.CustomerID
ViewData("CustomerCallCount") = callRepository.CountCallsForThisCustomer(calls.hdCustomer.CustomerID).Count()
ViewData("ContactNumber") = calls.hdCustomer.Telephone
ViewData("AssignedTo") = New SelectList(dataContext.aspnet_Users, "UserName", "UserName", calls.AssignedTo)
Dim callComments = callRepository.GetCallComments(id)
Dim db As New CustomerServiceModelDataContext
Try
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
'Update any call changes
Dim tCall = (From c In db.hdCalls _
Where c.CallID = id _
Select c).SingleOrDefault
tCall.updatedOn = DateTime.Now
tCall.UpdatedBy = Session("LoggedInUser")
tCall.StatusID = collection("Status")
tCall.AssignedTo = collection("AssignedTo")
tCall.CategoryID = collection("Type")
tCall.PriorityID = collection("Priority")
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
Catch ex As Exception
ModelState.AddModelError("Error", ex)
Return View(callComments)
End Try
Return View(callComments)
End Function
The rest of the code works, if the wmd-input field is left blank on the form, it's only when there is something in it does it throw the error.
EDIT bit of an update to this, this line:
If Not tComment.Comment.Trim().Length = 0 Then
now reads
If (Not tComment.Comment.Trim().Length = 0) Then
and the page updates if nothing is in the wmd-input box, but if there is, it returns the The value '' is invalid.
You are probably missing a reference. Or the framework version is different.
Also is it the same development machine, is asp.net-mvc installed both places?
I managed to fix this, the problem actually lay in the Foriegn Key Contraints between hdCalls and hdComments.
I removed the contraints and recreated them and all of a sudden it was fine.
I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.
Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?
Thanks.
You can do the following,: (it works both on local reports as in Full Blown SSRS reports. but in full mode, use the appropriate class, the parameter part remains the same)
LocalReport myReport = new LocalReport();
myReport.ReportPath = Server.MapPath("~/Path/To/Report.rdlc");
ReportParameter myParam = new ReportParameter("ParamName", "ParamValue");
myReport.SetParameters(new ReportParameter[] { myParam });
// more code here to render report
If the Report server is directly accessible, you can pass parameters in the Querystring if you are accessing the repoort with a URL:
http://MyServer/ReportServer/?MyReport&rs:Command=Render&Param1=54321&Param2=product
You can add output formatting by adding the following on the end of the URL:
&rs:Format=Excel
or
&rs:Format=PDF
It's been a while since I did this code, but it may help:
Your web project has to be a Web Site, and not a project of type "ASP.Net Web Application", or you won't be able to add the reference mentioned below.
Right click on the project and add an ASP.Net folder - App_WebReferences. You'll have to specify the server where your SRS is; choose the .asmx.
Once it's added, the folder under that level is called RSService, and under that are 2 things: reportservice.discomap & .wsdl.
In my VB, I do Imports RSService and Imports System.Web.Services.Protocols, then...
Dim MyRS As New ReportingService
The reporting service is on a different server than the webserver the app is on, so I can't do the following: MyRS.Credentials = System.Net.CredentialCache.DefaultCredentials
Instead: MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3),
where the rs1/2/3 are the login to SRS box, password to SRS box, & domain name". (These are encrypted in my web.config.)
Then, a mass-paste:
MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3)
Dim ReportByteArray As Byte() = Nothing
Dim ReportPath As String = "/SRSSiteSubFolder/ReportNameWithoutRDLExtension"
Dim ReportFormat As String = "PDF"
Dim HistoryID As String = Nothing
Dim DevInfo As String = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"
'Dim x As ReportParameter - not necessary
Dim ReportParams(0) As ParameterValue
ReportParams(0) = New ParameterValue()
ReportParams(0).Name = "TheParamName"
ReportParams(0).Value = WhateverValue
Dim Credentials As DataSourceCredentials() = Nothing
Dim ShowHideToggle As String = Nothing
Dim Encoding As String
Dim MimeType As String
Dim ReportHistoryParameters As ParameterValue() = Nothing
Dim Warnings As Warning() = Nothing
Dim StreamIDs As String() = Nothing
'Dim sh As New SessionHeader() - not necessary
''MyRS.SessionHeaderValue = sh - not necessary
ReportByteArray = MyRS.Render(ReportPath, ReportFormat, HistoryID, DevInfo, ReportParams, Credentials, _
ShowHideToggle, Encoding, MimeType, ReportHistoryParameters, Warnings, StreamIDs)
'(Yay! That line was giving "HTTP error 401 - Unauthorized", until I set the credentials
' as above, as explained by http://www.odetocode.com/Articles/216.aspx.)
'Write the contents of the report to a PDF file:
Dim fs As FileStream = File.Create(FullReportPath, ReportByteArray.Length)
fs.Write(ReportByteArray, 0, ReportByteArray.Length)
fs.Close()
Call EmailTheReport(FullReportPath)
If IO.File.Exists(FullReportPath) Then
IO.File.Delete(FullReportPath)
End If
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.Reset();
Label1.Visible = false;
ReportViewer1.Visible = true;
DataSet dataSet = new DataSet();
dataSet = new ClassBLL().Load_Report_Detail(TextBox1.Text,
ddlType.SelectedValue, levelcode, fields);
ReportDataSource datasource = new ReportDataSource("DataSet_StoreprocedureName",
dataSet.Tables[0]);
if (dataSet.Tables[0].Rows.Count == 0)
{
ReportViewer1.Visible = false;
}
ReportViewer1.LocalReport.ReportPath = Server.MapPath("") + #"\Report.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
string fields="name,girish,Z0117";
string[] filedName = fields.Split(',');
ReportParameter[] param = new ReportParameter[2];
//for (int i = 0; i < filedName.Length; i++)
//{
param[0] = new ReportParameter(filedName[0], filedName[0], true);
param[1] = new ReportParameter(filedName[3], filedName[3], true);
// }
ReportViewer1.LocalReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();