How to clear the file after uploading? - asp.net

I am using visual developer 2012 and have a simple form to upload the file to the server and then enter the name of the file into another table. For whatever reason it runs twice and enter the values twice in the second table:
Protected Sub BtnUploadImg_Click(sender As Object, e As EventArgs) Handles BtnUploadImg.Click
If IsPostBack Then
' Dim CurrentPath As String = Server.MapPath("C:\DSimages\")
If FileUpLoad1.HasFile = True Then
Try
FileUpLoad1.SaveAs("C:\DSimages\" & _
FileUpLoad1.FileName)
Label1.Text = "File name: " & _
FileUpLoad1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpLoad1.PostedFile.ContentLength & " kb<br>" & _
"Content type: " & _
FileUpLoad1.PostedFile.ContentType
ImageDataSource.InsertParameters("ImgName").DefaultValue = FileUpLoad1.PostedFile.FileName
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End If
ImageDataSource.Insert()
FileUpLoad1.PostedFile.InputStream.Dispose()
End Sub

Do you have the same code under the page load event? The postback will fire both events, so if you do it will run twice.

Related

ASP.NET VB , how to restrict filetype to upload?

I have a sub to upload file. How do I restrict the filetype that can be uploaded? I don't want the user to be able to upload .exe, .dll, .ini files. Right now any files can be uploaded.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.HasFile Then
Try
FileUpload1.SaveAs("C:\Uploads\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpload1.PostedFile.ContentLength & "<br>" & _
"Content type: " & _
FileUpload1.PostedFile.ContentType & "<br>" & _
"Location Saved: C:\Uploads\" & _
FileUpload1.FileName
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End Sub
If FileUpload1.HasFile Then
Try
if FileUpload1.FileName.ToLower().Contains(".exe") or FileUpload1.FileName.ToLower().Contains(".dll") or FileUpload1.FileName.ToLower().Contains(".ini")
' show your alert here stating this type of files are not allowed
return
End if
FileUpload1.SaveAs("C:\Uploads\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpload1.PostedFile.ContentLength & "<br>" & _
"Content type: " & _
FileUpload1.PostedFile.ContentType & "<br>" & _
"Location Saved: C:\Uploads\" & _
FileUpload1.FileName
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
But, I would suggest you client side check will be better too.

Problems with loading value after postback

I got a toolbar with different actions the user can start. In the user interface it looks like:
If I press on the "Ok" button the value will not known at the backend. My code structure is the following:
Configuration of an action
<Action Id="MyAction" Name="Action with Form">
<Form>
<asp:TextBox xmlns:asp="System.Web.UI.WebControls" ID="txtValue" runat="server" />
</Form>
</Action>
ASPX-File
<asp:Content ContentPlaceHolderID="cphToolbar" Runat="Server">
<asp:PlaceHolder ID="plhToolbar" runat="server" />
</asp:Content>
VB-File to the ASPX-File
Partial Class Form
Inherits UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.plhToolbar.Controls.Add(Me.CreateActionToolbar(<XML configuration element for the toolbar>))
End Sub
End Class
Page base class
Namespace UI
Public MustInherit Class Page
Inherits System.Web.UI.Page
Protected Overridable Function CreateActionToolbar(source As XmlElement) As Interfaces.IActions
Dim oAction As Interfaces.IActions = Me.LoadControl("~/Controls/Toolbar/Actions.ascx")
For Each element As XmlElement In source.SelectNodes("node()").OfType(Of XmlElement)()
Dim NewItem As New Controls.ActionItem
'set settings for the toolbar element
'add fields to form
For Each Item As XmlNode In element.SelectNodes("Form/node()", oNamespaceManager)
If (TypeOf Item Is XmlElement) Then
If (NewItem.Fields Is Nothing) Then NewItem.Fields = New List(Of XmlElement)
NewItem.Fields.Add(Item)
End If
Next
oAction.Items.Add(NewItem)
Next
Return oAction
End Function
End Class
End Namespace
Action user control
Partial Class Actions
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each Item As ActionItem In Me.Items
'set settings for action
If (Not (Item.Fields Is Nothing)) Then
Dim oPanel As New Panel
oPanel.ID = "dlgActionPanel" & Me.dlgAction.Controls.Count
Me.dlgAction.Controls.Add(oPanel)
Dim oFields As New Panel
oFields.ID = oPanel.ID & "_Controls"
For Each Field As XmlElement In Item.Fields
Dim oControl As System.Web.UI.Control = Nothing
Try
oControl = Me.ParseControl(Field.OuterXml)
Catch ex As Exception
oControl = New LiteralControl("<font style=""color:red;"">" & ex.Message & "</font>")
End Try
oFields.Controls.Add(oControl)
Next
Dim pnlResult As New Panel
Dim btnOk As New Button
btnOk.ID = "btnOk_" & oPanel.ID
AddHandler btnOk.Click, AddressOf Ok_Click
btnOk.Attributes.Add("onclick", "ShowWaitDialog();")
btnOk.Attributes.Add("ItemId", NewAnchor.Attributes("ItemId"))
btnOk.UseSubmitBehavior = False
btnOk.Text = Me.AcceptDialogText
pnlResult.Controls.Add(btnOk)
Dim btnCancel As New Button
btnCancel.Attributes.Add("onclick", "ShowWaitDialog();$('#" & oPanel.ClientID & "').dialog('close');CloseWaitDialog();return false;")
btnCancel.Text = Me.CancelDialogText
pnlResult.Controls.Add(btnCancel)
oPanel.Controls.Add(oFields)
oPanel.Controls.Add(pnlResult)
Dim strMessageControlId As String = oPanel.ClientID
strClientScript &= "$(""#" & strMessageControlId & """).dialog({" & NewLine
strClientScript &= " bgiframe:true, " & NewLine
strClientScript &= " autoOpen:false, " & NewLine
strClientScript &= " modal:true, " & NewLine
strClientScript &= " closeOnEscape:false, " & NewLine
strClientScript &= " width:600, " & NewLine
strClientScript &= " height:450, " & NewLine
strClientScript &= " minWidth:450, " & NewLine
strClientScript &= " minHeight:300, " & NewLine
If (Not (Item.Description Is Nothing)) Then strClientScript &= " title:'" & Item.Description & "', " & NewLine
strClientScript &= " open: function(event, ui) { $("".ui-dialog-titlebar-close"").hide(); } " & NewLine
strClientScript &= "});" & NewLine
If (String.IsNullOrEmpty(NewAnchor.Attributes("onclick"))) Then NewAnchor.Attributes.Add("onclick", String.Empty)
NewAnchor.Attributes("onclick") &= "$('#" & oPanel.ClientID & "').dialog('open');"
End If
Next
End Sub
Private Sub Ok_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim oDialog As Panel = Nothing
If (Not (String.IsNullOrEmpty(sender.ID))) Then oDialog = Me.dlgAction.FindControl(sender.ID.Substring(sender.ID.IndexOf("_") + 1) & "_Controls")
Dim oAction As ActionItem = Items.Find(Function(item) item.ItemId = sender.Attributes("ItemId"))
If (Not (oDialog Is Nothing)) Then
For Each Field As XmlElement In oAction.Fields
Dim oControl As WebControl = Nothing
If (Not (Field.SelectSingleNode("#Id|#ID") Is Nothing)) Then oControl = oDialog.FindControl(Field.SelectSingleNode("#Id|#ID").Value)
If (Not (oControl Is Nothing)) Then
Dim oParameter As SqlClient.SqlParameter = oAction.Parameters.Find(Function(item) item.ParameterName = "#" & oControl.ID.Substring(3))
If (Not (oParameter Is Nothing)) Then
Select Case oControl.GetType.ToString
Case GetType(TextBox).ToString
'After postback the value is empty!!!
If (Not (String.IsNullOrEmpty(CType(oControl, TextBox).Text))) Then oParameter.Value = CType(oControl, TextBox).Text
'more controls
Case Else
End Select
End If
End If
Next
End If
End Sub
End Class
Where is the fault that the value of the TextBox is after PostBack empty and not set because of the View State?
Thanks for any response.
I could solve it. The problem was that the jQuery dialog was not PostBack save. The solution was
$("#dialog").dialog({
appendTo:'form:first'
});

Creating a doc file from .net web app

I have a vb.net web app, and I need to give my users the facility to download a ms-word .doc file. This file needs to be created dynamically, and should contain some bold text and a table.
I've come across this code, which builds a .doc file, and lets you download it:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFileName As String = "GenerateDocument" + ".doc"
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName)
Dim strHTMLContent As StringBuilder = New StringBuilder()
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Charset = ""
HttpContext.Current.Response.ContentType = "application/msword"
strHTMLContent.Append("<p align='Center'>MY CONTENT GOES HERE</p>".ToString())
HttpContext.Current.Response.Write(strHTMLContent)
HttpContext.Current.Response.End()
HttpContext.Current.Response.Flush()
End Sub
...but I don't know how to make the text bold, or create a table. I'm sure there's a better way.
Sorry to answer my own question, but I've just come across this: http://www.codeproject.com/KB/office/Wordyna.aspx
It works perfectly for me, because it allows HTML input. So tables are a doddle.
Public Sub Page_Load(sender as Object, e as EventArgs)
'build the content for the dynamic Word document
'in HTML alongwith some Office specific style properties.
Dim strBody As New System.Text.StringBuilder("")
strBody.Append("<html " & _
"xmlns:o='urn:schemas-microsoft-com:office:office' " & _
"xmlns:w='urn:schemas-microsoft-com:office:word'" & _
"xmlns='http://www.w3.org/TR/REC-html40'>" & _
"<head><title>Time</title>")
'The setting specifies document's view after it is downloaded as Print
'instead of the default Web Layout
strBody.Append("<!--[if gte mso 9]>" & _
"<xml>" & _
"<w:WordDocument>" & _
"<w:View>Print</w:View>" & _
"<w:Zoom>90</w:Zoom>" & _
"<w:DoNotOptimizeForBrowser/>" & _
"</w:WordDocument>" & _
"</xml>" & _
"<![endif]-->")
strBody.Append("<style>" & _
"<!-- /* Style Definitions */" & _
"#page Section1" & _
" {size:8.5in 11.0in; " & _
" margin:1.0in 1.25in 1.0in 1.25in ; " & _
" mso-header-margin:.5in; " & _
" mso-footer-margin:.5in; mso-paper-source:0;}" & _
" div.Section1" & _
" {page:Section1;}" & _
"-->" & _
"</style></head>")
strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" & _
"<div class=Section1>" & _
"<h1>Time and tide wait for none</h1>" & _
"<p style='color:red'><I>" & _
DateTime.Now & "</I></p>" & _
"</div>" & _
"<div>" & _
"<table border=1>" & _
"<tr>" & _
"<td>1</td>" & _
"<td>2</td>" & _
"<td>3</td>" & _
"</tr>" & _
"<tr>" & _
"<td>a</td>" & _
"<td>b</td>" & _
"<td>c</td>" & _
"</tr>" & _
"</table>" & _
"</div>" & _
"</body></html>")
'Force this content to be downloaded
'as a Word document with the name of your choice
Response.AppendHeader("Content-Type", "application/msword")
Response.AppendHeader ("Content-disposition", _
"attachment; filename=myword.doc")
Response.Write(strBody)
End Sub

concatenate filenames

I have the following code in child window which is working but what I want to do is instead of using response.write I want to use label control or to display all the filename like this:
music.pdf, inventory.doc
My Ultimate goal is to pass the values in string (e.g.: "music.pdf, inventory.pdf" ) to the parent window.
How do I do it?
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
'' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("/ServerName/DirectoryName") & "\"" & System.IO.Path.GetFileName(hpf.FileName))
Response.Write("<b>File: </b>" & hpf.FileName & " <b>Size:</b> " & hpf.ContentLength & " <b>Type:</b> " & hpf.ContentType & " Uploaded Successfully! <br/>")
Else
Response.Write("Please select a file to upload.")
End If
Next i
Catch ex As Exception
End Try
End Sub
This is not the way I would do it but you asked for your code to work with a Label.
ASPX:
<asp:Label id="lblUploadMsg" runat="server" visible="false"></asp:Label>
Code:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
'' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
lblUploadMsg.Text = String.empty
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("/ServerName/DirectoryName") & "\"" & System.IO.Path.GetFileName(hpf.FileName))
lblUploadMsg.Visible = True;
lblUploadMsg.Text +="<b>File: </b>" & hpf.FileName & " <b>Size:</b> " & hpf.ContentLength & " <b>Type:</b> " & hpf.ContentType & " Uploaded Successfully! <br/>"
Else
lblUploadMsg.Text="Please select a file to upload."
End If
Next i
''HTML Encode lblUploadingMsg.Text after
Catch ex As Exception
End Try
End Sub
Consider using a <asp:BulletedList>, which is an ASP.NET server control for an unordered list <ul>.
ASPX:
<asp:BulletedList
id="uploadedFiles" runat="server"></asp:BulletedList>
Instead of Response.Write() each file, simply:
Dim displayText as String = string.Format("File: {0} Size: {1} Type: {2} Uploaded Successfully", _
hpf.FileName ,hpf.ContentLength ,hpf.ContentType)
uploadedFiles.Items.Add(New ListItem(displayText, hpf.FileName ))
Add a label control onto the form/control and then instead of using Response.Write, why not use a string builder and append all of the output to that in the loop. Once you have processed all of the files set the Label control's Text property of the string builder ToString method.
Hope this helps
You can use one of the String.Join() overloads.
Use a string builder to join strings. Strings in .NET are immutable, so Join and any other operators are memory intensive
Comment (not on the question, but I noticed it in your code) Use Path.Combine and any other Path functions. Amazingly easy to forget that they exist and have saved me millions of headaches.
Move your Response.Write outside of the loop over i.
Inside of i loop, keep track using a List<String>. Then, after the loop, use the Response.Write, to write a String.Join over the List.ToArray with a comma.
Using a Label control won't honour your <b> tags - what you're looking for here is to use the Literal control. Try something like this:
In your markup:
<asp:literal runat="server" id="UploadedFileInfoLiteral" />
In your code-behind:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
'' Get the HttpFileCollection
Dim hfc As HttpFileCollection = Request.Files
Dim FileInfoStringBuilder As System.Text.StringBuilder = New System.Text.StringBuilder
Dim hpf As HttpPostedFile
For i As Integer = 0 To hfc.Count - 1
hpf = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("/ServerName/DirectoryName") & "\"" & System.IO.Path.GetFileName(hpf.FileName))
FileInfoStringBuilder.Append("<strong>File: </strong>" & hpf.FileName & " <strong>Size:</strong> " & hpf.ContentLength & " <strong>Type:</strong> " & hpf.ContentType & " Uploaded Successfully! <br/>")
Else
FileInfoStringBuilder.Append("Please select a file to upload.")
End If
Next
UploadedFileInfoLiteral.Text = FileInfoStringBuilder.ToString()
Catch ex As Exception
End Try
End Sub

problem for chrome setfocus textbox

ScriptManager scrmgr = (ScriptManager)this.Master.FindControl("scrmgr");
scrmgr.SetFocus(txtSearch);
this is my coding ,it works all browser.but my problem is chrome display with selection if textbox has any value..
i want just remove the selection.......
I think there is no better solution than code your own setFocus function. The simpliest cross-browser method to remove the selection is to store the text temporarily, clear the value and set it again afterwards. Then call the js-function focus on the input-control.
I think this VB.Net Code helps to get the idea(I dont know if you prefer c#):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
setFocusOnControl(Me.TextBox1)
End Sub
Public Sub setFocusOnControl(ByVal ctrl As Control)
Dim script As String = "" & vbCrLf & _
"var control = document.getElementById('" & ctrl.ClientID & "');" & vbCrLf & _
"var temptext = control.value;" & vbCrLf & _
"control.value='';" & vbCrLf & _
"control.value=temptext;" & vbCrLf & _
"control.focus();" & vbCrLf & _
"" & vbCrLf
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "setFocusOnControlScript", script, True)
End Sub

Resources