OpenFileDialog in Webform Application - asp.net

I tried to use OpenFileDialog() control inside my Webform Application but it's not working.
I tried this coding but it gave me error :
System.Windows.Forms.OpenFileDialog Not defined
Private Sub FnOpenFileDialog()
Dim openfile As New System.Windows.Forms.OpenFileDialog
openfile.Filter = String.Format("Image file (*.jpg)|*.jpg")
openfile.Multiselect = True
openfile.ShowDialog()
End Sub
Private Sub btnUpload_PreRender(sender As Object, e As EventArgs) Handles btnUpload.PreRender
Dim objThread As New Thread(AddressOf FnOpenFileDialog)
objThread.IsBackground = True
objThread.SetApartmentState(ApartmentState.STA)
objThread.Start()
End Sub
Or is there any way on how to do it? I don't want to use FileUpload control because it shows textbox + button. I only want to show the Button() control.
I refer to this website How to Apply OpenFileDialog Function to a WebApplication

In a ASP.NET web application, the VB code is run on the web server. So even if you would succeed in using OpenFileDialog that would result in the dialog being showed on the server, not in the browser.
JavaScript won't help you either, as the browswer sandbox in which JavaScripts run doesn't allow access to the file system (which is good from a security perspective). You simply have to accept that you need to work with the file upload control. You might be able to customize the appearance a bit by applying styles through css.

Use HTML input file ,as follow:
<input id="File1" type="file" />

Related

Script Manager Register Startup Script only runs script on initial Page Load When run through a Master Page Function

Edit:
I checked the page via developer tools and both of them put a script block with the function calls in the script block. The one running through the master page places the script block higher up in the page, a few lines from the top of the form. The ones called from the page place them with other script blocks near the end of the form element. I'm not sure if that means anything to anyone or not, but it seemed relevant to me.
Original Question
I have a multi page application in which I use the RegisterStartupScript method of the ScriptManager on multiple occasions on each page. We have a Master page, so I decided to put a Public function that just takes the name and optionally different script text and registers the startup scripts there so that way we can have a smaller, simpler function call for startup scripts and one that is accessible from every page that uses the master page. Here's the function:
Public Sub RunStartupScript( ByVal name As String, ByVal Optional script As String = "")
If script = "" Then
script = name & "();"
End If
ScriptManager.RegisterStartupScript(Me, [GetType](), name, script, True)
End Sub
I have the script manager in the aspx of the master page as well, and when using this function it does work and run the script, but only for the initial page load. Any subsequent async postbacks do not run any scripts that have already been run.
Master.RunStartupScript("SomePredefinedJavaScriptFunction")
If I take this exact function code and place it in the code behind of the specific page, it works just fine and will run on any postback. Why does this not work right when the function is owned by the master page?
Any thoughts?
So it turns out it was a pretty simple mistake (as these things so often are), but hard to see. I forgot that Me doesn't refer to the Page in a Master Page file, but instead refers to the Master type. Changing the Me to Page fixed the issue.
Public Sub RunStartupScript( ByVal name As String, ByVal Optional script As String = "")
If script = "" Then
script = name & "();"
End If
ScriptManager.RegisterStartupScript(Page, Page.GetType(), name, script, True)
End Sub
Thanks for the other answers and comments. Looking at those helped me to go back through and retrace my steps to find the issue.
You say I have the script manager in the aspx of the master page as well - does that as wel mean that you have it in the content pages? Per MSDN
Using the ScriptManager Control with Master Pages, User Controls, and Other Child Components
A page can contain only one ScriptManager control in its hierarchy. To register services and scripts for nested pages, user controls, or components when the parent page already has a ScriptManager control, use the ScriptManagerProxy control. For more information, see Using the ASP.NET UpdatePanel Control with Master Pages
While this doesn't answer why your approach doesn't work, I think it suggest that you should consider using the proxy object on content pages.
EDIT
Based on your comment, you should also consider accessing the script manager on content pages not by exposing your own property, but by ScriptManager's GetCurrent method
I am curious if doing it this way provides any improvement:
Public Sub RunStartupScript(System.Web.UI.ScriptManager sm, ByVal name As String, ByVal Optional script As String = "")
If script = "" Then
script = name & "();"
End If
sm.RegisterStartupScript(Page, Page.GetType(), name, script, True)
End Sub
and call Master.RunStartupScript(ScriptManager.GetCurrent(...), "SomePredefinedJavaScriptFunction")

How to implement a desktop download from web form in VB.NET

In my website that I am currently working on, I store some images in a folder in the same directory as my .aspx files in the project file. What method can I use to write a code so that when someone clicks an asp:Button, the browser downloads the image (with a given url) for them.
Here is a code example of what it would look like.
Protected Sub button_img_Click(sender As Object, e As EventArgs) Handles button_img.Click
MagicalFunctionDownloadImage("image.jpeg")
End Sub
Hope that made sense!
Thanks in advance!
The asp:button will really be just a hyperlink, and you'll set a url item that corresponds to your image. It will point to a handler (*.ashx file) that you build, instead of a page (*.aspx file). The handler works much like a page, but without some of the cruft you won't use, and it will allow to set a few specific headers. You then use Response.BinaryWrite() to send the file data to the browser:
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=<filename here>")
Response.ContentType = "<content/type here>"
Response.BinaryWrite(<path to file or byte array goes here>)
Response.Flush()
Response.End()

debuggin in aspx

I am trying to debug some code in my code behind files for as aspx page. I have debug set to true both in the page and in my web.config.
Can someone tell me why a) the breakpoint never fires even though the dropdown gets filled and b) why when i uncomment the msgbox it never fires and the dropdown does NOT fill.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If IsPostBack Then
ddlCity.Items.Clear()
Dim context As New enerteckEntities()
'Dim query = context.DistinctCityFromZiptax(Convert.ToInt16(ddlState.SelectedValue))
Dim query = From c In context.ziptaxes Where c.StateID = ddlState.SelectedValue Order By c.City Select c.City, c.ZipTaxId
'MsgBox(query.Distinct().ToList())
ddlCity.DataSource = query.Distinct().ToList()
ddlCity.DataValueField = "ziptaxid"
ddlCity.DataTextField = "City"
ddlCity.DataBind()
End If
End Sub
Well based on your code, you will only execute this after a PostBack and not on initial Page Load.
MsgBox will never show up because this is not a WinForms application! You cannot use that in a web.application. If you want you can use Response.Write() or just add a dummy Label to your page and set the text property temporarily. It is the same effect.
The easiest would be to just debug it. Make sure your breakpoints are full Red dots, and you must be in Debug mode. If you are trying to debug from IIS then you must attach to process. If you are using IIS7 (I am assuming you are) then you must go to:
Debug Menu > Attach to Process > Find the process named "w3wp.exe" and double click on it.
You are now attached.
If your breakpoints are not full red dots after starting debug, then your compiled code and your debug files do not match. Do a Rebuild as opposed to a Build. Beyond that you might be having a funky problem, you can try deleting your obj and bin folders (make sure to save any third party dlls first).
To hit a break point visual studio has to attach to the process hosting the aspx page.
This is typically done in a Web Application Project by pressing the F5 key or clicking on the "Debug" menu and clicking "Start Debugging".

How can I programmatically modify an aspx file content before the handler handle it?

The reason I need to modify the content of an aspx (not physically, but change the content in the memory) is because there are certain custom tags I made needs to be parsed to the correct data before the entire aspx is handled by the HttpHandler.
Is there a way for that?
You can use Response Filters (HttpFilter) and modify content on the fly, basically after response is formed, before EndRequest your filter is called (it's a stream descendant) and you can modify it as you wish. In the HttpModule, Init method you got to install HttpFilter (Response.Filter) and it will be called for that request.
Here is a good article :
http://aspnetresources.com/articles/HttpFilters
UPDATE:
Maybe this is a case of XY Problem, and you can solve your problem with simple server control that will render these custom tags properly.
you can use the Render event
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
Dim sw As New System.IO.StringWriter
Dim hw As New HtmlTextWriter(sw)
MyBase.Render(hw)
Dim html As String = sw.ToString()
' html = html.Replace() etc to change your html code in here
writer.Write(html)
End Sub
EDIT i see you want to inject mark up dynamically before asp.net handles the aspx, maybe the FileLevelPageControlBuilder Class is of use

Create FileUpload from code behind

I need to create a FileUpload control from the code behind page. I have this function:
Private Function CreateUpload() As FileUpload
Dim txtFileUpload As New FileUpload
txtFileUpload.ID = "element1"
Return txtFileUpload
End Function
However, even though I successfully use a similar technique for other form controls, my FormUpload doesn't get rendered to the page.
Can someone please explain what I'm doing wrong.
Edit: I'm writing the returned FileUpload to a DIV on the page outside of my function.
Update: It's sorted. Seemed to be a problem with Visual Studio. Closing it, relaunching and then rebuilding the website sorted it. Thanks to all who responded.
Thanks.
I can't see you adding this control to the WebForm. Try adding it:
Private Function CreateUpload() As FileUpload
Dim txtFileUpload As New FileUpload
txtFileUpload.ID = "element1"
Page.Controls.Add(txtFileUpload)
Return txtFileUpload
End Function
or if you don't have access to the Page inside this function add it when you call the function in the code behind of your webform:
Dim txtFileUpload As FileUpload = CreateUpload()
Page.Controls.Add(txtFileUpload)

Resources