I have a website written in ASP.Net . On one page I have a table of images. Those images are stored in folders. There is a drop down box that displays the various folder names. When a user selects folder name from the drop down, then the images in that folder are displayed in the table.
The issue is that as soon as a folder is selected in the drop down box, then none of the images on the page can be downloaded in Chrome. If you right click on an image and select "Save Image As.." and click Save, Chrome returns with an error "Interrupted - Network Error" . You can click resume and the file downloads . You can open the image in a new tab and download the file. It also causes all images on the page to not download , including static ones such as the logo on the header. It works fine in Firefox. The images are quite small 420 K or so. The code for the page is very simple, in fact the code that occurs on page load is almost identical to the code that occurs on selecting an item from the drop box. This happens to all our website users , so definitely not some plug in or antivirus etc. Any ideas why selecting a folder from the drop box may cause an issue? Following is the page code
``
Imports System.IO
Partial Class m_Images
Inherits System.Web.UI.Page
Private imgPath As String
Dim strFolderName As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
For Each d In System.IO.Directory.GetDirectories(Server.MapPath("~\images\ClientImages"))
Dim dir = New DirectoryInfo(d)
Dim dirName = dir.Name
lstCategories.Items.Add(dirName)
Next
strFolderName = lstCategories.SelectedItem.Text.Trim
imgPath = Server.MapPath("~\images\ClientImages\" + strFolderName + "\")
Session("FolderName") = strFolderName
Dim directoryInfo As DirectoryInfo = New DirectoryInfo(imgPath)
If directoryInfo.Exists Then
DataList1.DataSource = directoryInfo.GetFiles("*")
DataList1.DataBind()
Else
DataList1.DataSource = Nothing
DataList1.DataBind()
End If
End If
End Sub
Protected Sub lstCategories_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCategories.SelectedIndexChanged
strFolderName = lstCategories.SelectedItem.Text.Trim
imgPath = Server.MapPath("~\images\ClientImages\" + strFolderName + "\")
Session("FolderName") = strFolderName
Dim directoryInfo As DirectoryInfo = New DirectoryInfo(imgPath)
If directoryInfo.Exists Then
DataList1.DataSource = directoryInfo.GetFiles("*")
DataList1.DataBind()
Else
DataList1.DataSource = Nothing
DataList1.DataBind()
End If
End Sub
Protected Function GetFolderName() As String
imgPath = Session("FolderName")
Return imgPath
End Function
End Class
``
Tried different desktops, and browsers. The problem is limited to Chrome (and Chromium based browsers such as Opera) . The problem occurred on at least 50 desktops scattered throughout the country.
Related
I have some issues downloading an image (or zip sometimes) from a webpage.
I've checked a few forums about the topic where most of the time they suggest using the URLDownloadToFile function.
I tried to apply it but it doesn't seem to work.
Here's an example of the type of webpage I'm dealing with :
The type here is jpg but sometimes it can be a zip.
For the jpg case, I have two ways to do it:
Click on the View button, which will open a new webpage containing 1 image only, selecting that webpage and somehow dowloading the image, which I don't manage to do.
(There is a "Save Picture As" when you rigth click a picture manually, but how to access to this with VBA ? ) :
objIE.document.frames(1).frames(1).document.getElementById("notPrintable").document.getElementsByName("view")(0).Click 'This clicks on the View Button
attachment_url = "https://pumapgf-row.bmwgroup.net/puma/case/showfile.do?selectedIndex=" & elem_id & "&filename=" & elem_name & "%20%7C%20jpg%20%7C%20" & end_url ' this is the url of the new webpage which is opened when I click the view button
Set objIE = IEWindowFromLocation(attachment_url) ' I select the new webpage
Set IEDoc = objIE.document ' set document on it
The html from this new webpage in the case it's a jpg of course) looks like this:
What I tried to do then but unsuccessfully is to use the URLDownloadToFile function this way
Dim myImages As IHTMLElementCollection
Set myImages = IEDoc.getElementsByTagName("img")
returnValue = URLDownloadToFile(0, myImages(0).href, "P:\Alex\ABC.img", 0, 0)
Whether I create or not a such called file before I run the code, it doesn't make any difference. I also tried with .jpg, .img, .png.
myImages(0).href ends like this :
So I don't know if the fact that .href doesn't end with something like .jpg or .img is an issue.
Click on the Save As button : valid for both jpg and zip files, so would be a better solution. I manage to click on it of course, but the issue comes from the fact that Internet displays this and I have no idea how to deal with it.
Any idea how to do this ?
EDIT : Here is the properties window of the image
Assuming that you have a valid download URL (which I can't test based on the site in your question), all you should need to do to test if a file is a jpg is to download it and check for the presence of the JPEG file header:
Public Function FileIsJpg(filepath As String) As Boolean
Dim handle As Long
handle = FreeFile
Open filepath For Binary As #handle
Dim header As Integer
Get #handle, , header
'Note the byte order.
If header = &HD8FF Then
Get #handle, , header
If header = &HE0FF Or header = &H1FF Then
FileIsJpg = True
End If
End If
Close #handle
End Function
Note that for your usage, this will need error handling because of the possibility that URLDownloadToFile still has the file open. I'm assuming that you have some sort of wait mechanism in place (it's a non-blocking function). If not, you need to either use the native callback mechanisms or take a guess and used Application.Wait or something similar.
Example usage:
Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Private Const S_OK As Long = 0
Sub Examples()
Const TestJpgUrl As String = "https://www.gstatic.com/webp/gallery/1.jpg"
Const TestPngUrl As String = "https://www.gstatic.com/webp/gallery3/1.png"
Dim target As String
target = Environ$("TEMP") & "\test.png"
If URLDownloadToFile(0, TestPngUrl, target, 0, 0) = S_OK Then
'Wait for download to complete - a callback function would be better.
Application.Wait Now + TimeSerial(0, 0, 1)
MsgBox target & ": " & FileIsJpg(target)
End If
Kill target
target = Environ$("TEMP") & "\test.jpg"
If URLDownloadToFile(0, TestJpgUrl, target, 0, 0) = S_OK Then
Application.Wait Now + TimeSerial(0, 0, 1)
MsgBox target & ": " & FileIsJpg(target)
End If
Kill target
End Sub
Note that you can also explicitly test for zip files in a similar way, but I'll leave that as an exercise for the reader.
Good day stack overflow,
I am trying to save pictures in my mysql database, i think i will use BLOB correct?
I am planning to update my mysql database that is already hosted online to support uploading and displaying pictures in my project in vb.net,
I know the easiest way to do saving picture in mysql database is by saving the picture in a directory and putting the path only in the database, but how about for online database that is hosted in the internet and does not have a working directory? I mean just the database itself?
How can i optimized the time access for the picture to load?
Protected Sub UpLoadThisFile(ByVal upload As FileUpload)
If UpL1.HasFile Then
Dim fileName As String = Path.GetFileName(UpL1.PostedFile.FileName)
UpL1.PostedFile.SaveAs(Server.MapPath("~/AltImg2/") + fileName)
UpImag.ImageUrl = ("~/AltImg2/") + fileName
T8.Text = ("~/AltImg2/") + fileName
Else
T8.Text = "~/NOPic/noimage.jpg"
End If
End Sub
Protected Sub CheckImag()
If UpL1.HasFile Then
Dim ValidatFileTy As String() = {"bmb", "gif", "png", "jpg", "jpeg"}
Dim Ext As String = System.IO.Path.GetExtension(UpL1.PostedFile.FileName)
Dim isValidFile As Boolean = False
For i As Integer = 0 To ValidatFileTy.Length - 1
If Ext = "." & ValidatFileTy(i) Then
isValidFile = True
End If
Next
If Not isValidFile Then
MsgLbl.Visible = True
MsgLbl.ForeColor = Drawing.Color.Red
MsgLbl.Text = String.Join(",", ValidatFileTy)
Exit Sub
Else
UpLoadThisFile(UpL1)
End If
Else
UpLoadThisFile(UpL1)
End If
End Sub
and in button
Protected Sub BTAddNew_Click(sender As Object, e As EventArgs) Handles BTAddNew.Click
Try
CheckImag()
Insert()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
but how about for online database that is hosted in the internet and does not have a working directory?
yes you must use ~ ("~/AltImg2/").
once in a while in this application I have been working on a form will suddenly lose all of it's functionality with the database and I am forced to erase all of the work I have done on it and completely re-build it.
For instance adding a new entry to the database; I can hit Add New which calls bindingsource.addnew() enter all of the required information into the text boxes, hit save then when I close and re-open the form nothing is displayed in the datagrid. If I go directly to the table in the SQL Database nothing has been added here either?
It seems to escalate suddenly, when I edit an entry in a table then save it it does not update. After that I cannot add rows to it but it will let me delete rows and save that?
Tablename.bindingsource.addnew()
Tablename.bindingsource.endedit()
Tablename.tableadapter.update(datasetname.tablename)
This is what I have used for adding rows and saving new entries plus edits to the data source for some time now. Is there something I need to be watching out for otherwise?
Private Sub createnew()
'' CREATE AND SAVE NEW ENTRY
CalibratedEquipmentBindingSource.AddNew()
dateaddedlbl.Text = datelbl.Text
CalibratedEquipmentBindingSource.EndEdit()
Calibrated_EquipmentTableAdapter.Update(MacroQualityDataSet.Calibrated_Equipment)
End Sub
Private Sub savebtn_Click(sender As Object, e As EventArgs) Handles savebtn.Click
Try
Dim accountname As String = "macroqc"
Dim acocuntkey As String = My.Settings.Storagekey1
Dim creds As StorageCredentials = New StorageCredentials(accountname, acocuntkey)
Dim account As CloudStorageAccount = New CloudStorageAccount(creds, useHttps:=True)
Dim client = account.CreateCloudBlobClient()
Dim container As CloudBlobContainer = client.GetContainerReference(My.Settings.smallequipmentcertscontainername)
container.CreateIfNotExists()
Dim blob As CloudBlockBlob = container.GetBlockBlobReference(My.Settings.ticketsource)
Using FileStream = System.IO.File.OpenRead(My.Settings.ticketsource)
blob.UploadFromStream(FileStream)
filenamelbl.Text = My.Settings.ticketsource
'' GET HTTPS: PATH OF BLOB
''blob.Uri.AbsoluteUri & blob.Uri.AbsolutePath
End Using
Catch ex As Exception
MessageBox.Show("Sorry an error has occured while uploading your file: " & Environment.NewLine & ex.ToString, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
If datelbl.Text.Length > 3 Then
dateeditedlbl.Text = datelbl.Text
End If
CalibratedEquipmentBindingSource.EndEdit()
Calibrated_EquipmentTableAdapter.Update(MacroQualityDataSet.Calibrated_Equipment)
gridcolors()
MsgBox("Save Complete!")
End Sub
End Class
I have been trying to work out the best way for a power point to be shown on a Intranet. The users in the company will not be very technical and might not follow the processes I will describe.
I found this page
Which shows how to convert a power point in to a html page which can be viewed. I was wanting to know if there is some way to automate this process. Such as a file watcher watching the location it will saved and then as soon as it is seen automatically changes this to a html using the code provided on the page I gave. Preferred language to use would be VB.NET.
I am happy for any suggestions that people can give.
Thanks in advance
You can try with this code - based on Microsoft.Office.Interop.PowerPoint.Application
You have sample of code in order to try functionality
View Aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="AspNetPowerPointConvertToHTML.aspx.vb" Inherits="AspNetPowerPointConvertToHTML" %>
<html>
<head>
<title>ShotDev.Com Tutorial</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label id="lblText" runat="server"></asp:Label>
</form>
</body>
</html>
Code behind
Imports Microsoft.Office.Interop.PowerPoint
Public Class AspNetPowerPointConvertToHTML
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim ppApp As New Microsoft.Office.Interop.PowerPoint.Application
Dim ppName As String = "MySlides.ppt"
Dim FileName As String = "MyPP/MyPPt"
ppApp.Visible = True
ppApp.Presentations.Open(Server.MapPath(ppName))
ppApp.ActivePresentation.SaveAs(Server.MapPath(FileName), 13)
ppApp.Quit()
ppApp = Nothing
Me.lblText.Text = "PowerPoint Created to Folder <strong> " & FileName & "</strong>"
End Sub
End Class
I've used the:
Imports PowerPoint = Microsoft.Office.Interop.PowerPoint
to be able to automatically change a power point in to a HTML. I've used a file watcher to watch a directory on my computer to look out for power point presentations at the moment it is only set to .pptx however I'll change this to add other formats soon. This fileWater is sat on a service that starts up when the computer does. It then looks to see if a powerpoint has been created or modified and runs this code:
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
'set varaibles so that html can save in correct place
Dim destinationDirectory As String = e.FullPath.Replace(e.Name.ToString(), "")
Dim sourceLocation As String
Dim fileName As String
'couple of if statements to get rid of unwanted characters
If e.Name.Contains("~$") Then
fileName = e.Name.Replace("~$", "")
fileName = fileName.Replace(".pptx", ".html")
Else
fileName = e.Name
fileName = fileName.Replace(".pptx", ".html")
End If
If e.FullPath.Contains(("~$")) Then
sourceLocation = e.FullPath.Replace("~$", "")
Else
sourceLocation = e.FullPath
End If
Dim strSourceFile As String = sourceLocation 'set source location after removing unwanted characters
Dim strDestinationFile As String = destinationDirectory & fileName 'set the destination location with the directory and file name
'set ppAPP to a power point application
Dim ppApp As PowerPoint.Application = New PowerPoint.Application
Dim prsPres As PowerPoint.Presentation = ppApp.Presentations.Open(strSourceFile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse)
'Call the SaveAs method of Presentaion object and specify the format as HTML
prsPres.SaveAs(strDestinationFile, PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue)
'Close the Presentation object
prsPres.Close()
'Close the Application object
ppApp.Quit()
End Sub
This gets the file which has been modified and saves it as a html document. It will also get the files needed to run so if any animations have been saved it will also keep those.
Can we change printer settings at run time in SSRS 2008?
For example, if a report is on Legal size paper but I want to print on A4 Landscape or Legal at run time, depending on a parameter which is passed in.
The answer is that NO, you cannot unless you write your own solution. The report viewer control does not support this. Your options are either to create a custom printing solution, OR to manipulate your RDLC file to modify the settings manually.
If you decide to modify the RDLC file on the fly, you need to load the RDLC file into memory, modify the XML file to specify the new page settings, then reload the RDLC file in the report viewer.
If you decide to do manual printing, here is some VB.NET code to help you get started:
Dim m_pageSettings As PageSettings 'Stores page settings for printout
Dim m_currentPage As Integer 'Used for index of pages
Private m_pages As New List(Of Stream)() 'Stores a stream for each pages
'Event fires when printDocument starts printing - reset page index to zero
Private Sub PrintDocument1_BeginPrint(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
m_currentPage = 0
End Sub
'Function that prints all the pages included in the report
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim pageToPrint As Stream = m_pages(m_currentPage)
pageToPrint.Position = 0
Dim pageMetaFile As Metafile = New Metafile(pageToPrint) 'create an image(metafile) of the report page
Using (pageMetaFile)
'Create a rectangle the size of our report - include margins
' Dim adjustedRect As Rectangle = New Rectangle( _
' e.PageBounds.Left - CType(e.PageSettings.HardMarginX, Integer), _
' e.PageBounds.Top - CType(e.PageSettings.HardMarginY, Integer), _
' e.PageBounds.Width, _
' e.PageBounds.Height)
Dim adjustedRect As Rectangle = New Rectangle( _
e.PageBounds.Left, _
e.PageBounds.Top, _
e.PageBounds.Width, _
e.PageBounds.Height)
e.Graphics.FillRectangle(Brushes.White, adjustedRect) 'Fill rectangle with WHITE background
e.Graphics.DrawImage(pageMetaFile, adjustedRect) 'Draw report in rectangle - this will be printed
m_currentPage = m_currentPage + 1
e.HasMorePages = m_currentPage < m_pages.Count 'If more pages are left - keep processing
End Using
End Sub
'Event fires when PrintDocument queries for PageSettings. Return a copy of m_pagesettings.
Private Sub PrintDocument1_QueryPageSettings(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.QueryPageSettingsEventArgs) Handles PrintDocument1.QueryPageSettings
e.PageSettings = CType(m_pageSettings.Clone, PageSettings)
End Sub
'Render the report in a EMF - This function creates metafiles(images) of each page in the report
Private Sub RenderAllLocalReportPages(ByVal localReport As LocalReport)
Dim deviceInfo As String = CreateEMFDeviceInfo() 'Enhanced MetaFile
Dim warnings As Warning() = Nothing
m_pages.Clear()
localReport.Render("IMAGE", deviceInfo, AddressOf LocalReportCreateStreamCallback, warnings)
End Sub
'Callback function used with RenderAllLocalReportPages
Private Function LocalReportCreateStreamCallback(ByVal name As String, ByVal extension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As New MemoryStream()
m_pages.Add(stream)
Return stream
End Function
Private Function CreateEMFDeviceInfo() As String
Dim paperSize As PaperSize = m_pageSettings.PaperSize
Dim margins As Margins = m_pageSettings.Margins
'The device info string defines the page range to print as well as the size of the page.
'A start and end page of 0 means generate all pages.
Return String.Format(CultureInfo.InvariantCulture, "<DeviceInfo><OutputFormat>emf</OutputFormat><StartPage>0</StartPage><EndPage>0</EndPage><MarginTop>{0}</MarginTop><MarginLeft>{1}</MarginLeft><MarginRight>{2}</MarginRight><MarginBottom>{3}</MarginBottom><PageHeight>{4}</PageHeight><PageWidth>{5}</PageWidth></DeviceInfo>", ToInches(margins.Top), ToInches(margins.Left), ToInches(margins.Right), ToInches(margins.Bottom), ToInches(paperSize.Height), ToInches(paperSize.Width))
End Function
'Convert report printing size to inches
Private Shared Function ToInches(ByVal hundrethsOfInch As Integer) As String
Dim inches As Double = hundrethsOfInch / 100.0R
Return inches.ToString(CultureInfo.InvariantCulture) & "in"
End Function
Hopefully this helps.