ajax control toolkit fileupload - asp.net

I am trying to get the fileupload control from the ajax control toolkit to work.
I need to use the uploaded files in my code behind (I use asp.net),
This includes unzipping, resizing and putting some data in a database.
The problem I have is that when I use ajaxUpload1_OnUploadComplete, i can't get the text from a textbox on the same page.
When I use a breakpoint, I noticed that the value of the textbox is just "".
I have searched a lot and I really can't find a solution for this, so I hoped that someone here might be able to help.
I have pasted my code below, thanks in advance!
.aspx code:
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"
CodeFile="Upload.aspx.vb" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="LblUploadError" runat="server" Text="Please login first" Visible="false"></asp:Label>
<asp:Panel ID="PnlUpload" runat="server" Visible="false">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<span>Album name:</span><br />
<asp:TextBox ID="txtAlbumNaam" runat="server" ViewStateMode="Disabled"></asp:TextBox><br />
<span>Private album</span> <asp:CheckBox ID="chkPrivate" runat="server" /><br />
<span>Upload files (.zip, .jpg, .jpeg or .png)</span><br />
<asp:AjaxFileUpload id="ajaxUpload1" OnUploadComplete="ajaxUpload1_OnUploadComplete" ThrobberID="MyThrobber" runat="server" AllowedFileTypes="jpg,jpeg,zip,png" /><br />
<asp:Label ID="lblError" runat="server"/><br />
</asp:Panel>
</asp:Content>
code behind:
Imports Ionic.Zip
Imports System.IO
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("LoggedIn") = True Then
PnlUpload.Visible = True
Else
LblUploadError.Visible = True
End If
End Sub
Protected Sub ajaxUpload1_OnUploadComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AjaxFileUploadEventArgs)
'indien zip:
Dim ziperror As Boolean = False
If System.IO.Path.GetExtension(e.FileName) = ".zip" Then
ajaxUpload1.SaveAs(Server.MapPath("./TempZips/" & e.FileName.ToString))
Dim ZipToUnpack As String = Server.MapPath("./TempZips/" & e.FileName.ToString)
Dim UnpackDirectory As String = Server.MapPath("./TempFotos")
Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)
Dim file As ZipEntry
For Each file In zip1
Dim strExtensie As String = System.IO.Path.GetExtension(file.ToString)
If Not (strExtensie = ".jpeg" Or strExtensie = ".jpg" Or strExtensie = ".png") Then
ziperror = True
lblError.Text = "The .zip structure is incorrect, please make sure that you only have compatible pictures inside the zip file."
End If
Next
If ziperror = False Then
For Each file In zip1
file.Extract(UnpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Next
End If
End Using
'indien foto:
ElseIf System.IO.Path.GetExtension(e.FileName) = ".jpeg" Or System.IO.Path.GetExtension(e.FileName) = ".jpg" Or System.IO.Path.GetExtension(e.FileName) = ".png" Then
ajaxUpload1.SaveAs(Server.MapPath("./TempFotos/" & e.FileName.ToString))
Else
'indien geen van beide
lblError.Text = "Invalid filetype on one of the files, please use other files."
End If
'tempzips leegmaken
If ziperror = False Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(Server.MapPath("TempZips"))
File.Delete(foundFile)
Next
'verkleinen en album toevoegen aan database:
Dim strFolderDirectory As String = Server.MapPath("users/" & Session("UserNickName") & "/" & txtAlbumNaam.Text)
System.IO.Directory.CreateDirectory(strFolderDirectory)
Dim strDirectory As String = Server.MapPath("TempFotos")
Dim intAantalFotos As Integer = 0
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory)
Using Afbeelding As System.Drawing.Image = System.Drawing.Image.FromFile(foundFile)
Dim resizedimage As System.Drawing.Image
Dim resizedwidth As Integer
resizedwidth = (300 / Afbeelding.Height) * Afbeelding.Width
resizedimage = Afbeelding.GetThumbnailImage(resizedwidth, 300, Nothing, New IntPtr)
resizedimage.Save(strFolderDirectory & "/" & Path.GetFileName(foundFile))
End Using
intAantalFotos += 1
Next
Dim CmdInsert As New OleDbCommand
Dim Sqlstatement As String = "INSERT INTO tblAlbums (userID, createdDate, pictures, private, albumName) VALUES (#userID, Now(), #pictures, #private, #albumName);"
CmdInsert.Connection = dbConn.cn
CmdInsert.CommandText = Sqlstatement
CmdInsert.Parameters.AddWithValue("userID", CInt(Session("userID")))
CmdInsert.Parameters.AddWithValue("pictures", intAantalFotos)
CmdInsert.Parameters.AddWithValue("private", chkPrivate.Checked)
CmdInsert.Parameters.AddWithValue("albumName", txtAlbumNaam.Text)
dbConn.cn.Close()
dbConn.cn.Open()
CmdInsert.ExecuteNonQuery()
dbConn.cn.Close()
'TempFotos leegmaken
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory)
File.Delete(foundFile)
Next
'pagina herladen
LblUploadError.Visible = True
LblUploadError.Text = "Your pictures have been successfully uploaded!"
End If
End Sub
End Class

The problem is that ajax control toolkit file upload control can upload files to server using hidden iFrame (depending on what HTML5 features browser supports). Hidden iFrame references to the same url as you page and that's why you page loaded once more but only to hidden iframe. That's why on server side during handling UploadComplete event you get that the text box has empty value (because it is really have empty value because this is the state of the page which was loaded in iframe).
One of the solution to your problem is performing additional logic (which depends on entered data) after uploading is complete. To do this you can handle client side upload complete event and perform postback (or ajax request) manually.
Other solution can be setting content of the hidden iFrame elements manually before upload will start. In this case you can get hidden iframe, found necessary HTML elements (like text input in your case) and set it value the same as it was entered by user. But this approach can required extending logic of the ajax control toolkit upload control on client side.

Related

How can I change File Info in Ajax File Upload Control ,Asp.net(VB)?

I am creating a drag file upload by using Ajax File Upload Control in Asp.net(VB).
I want to show file name, uploaded datetime, file size when I dragged into panel.
How can I do for that setting?
I could change the text for droparea like
$(document).ready(function () {
Sys.Extended.UI.Resources.AjaxFileUpload_Pending = "保留中";
Sys.Extended.UI.Resources.AjaxFileUpload_Remove = "削除";
Sys.Extended.UI.Resources.AjaxFileUpload_Uploaded = "アップロード済";
Sys.Extended.UI.Resources.AjaxFileUpload_Uploading = "アップロード中";
Sys.Extended.UI.Resources.AjaxFileUpload_UploadedPercentage = "アップロード中 {0} %";
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "アップロード";
document.getElementsByClassName
$(".ajax__fileupload_dropzone").text("ここにファイルをドロップ");
document.getElementsByClassName
$(".ajax__fileupload_uploadbutton").text("アップロード");
});
But I don't know how to change file info display.
This is my drag form and I want to change from application/pdf to uploaded datetime
You can't really display the "time" of up-load until the user starts.
You ALREADY can see the file size in your screen cap, so why the need for that?
you have:
so in above, you see the file name, you see the file size.
However, until such time you hit up-load and start up-loading files, you don't know yet the up-load time as of yet, do you?
So, when you hit up-load files, then each file selected will be up-loaded, and in the server side (code behind), you have this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now code to add say to a database table of files up-loaded.
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL = "INSERT INTO MyUpoadFiles (FileName, UpLoadTime, Size, User_id) " &
"VALUES (#File, #Time,#Size, #User)"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
With cmdSQL.Parameters
.Add("#File", SqlDbType.NVarChar).Value = e.FileName
.Add("#Time", SqlDbType.DateTime).Value = Date.Now
.Add("#Size", SqlDbType.Int).Value = e.FileSize
.Add("#User", SqlDbType.Int).Value = Membership.GetUser.ProviderUserKey
End With
cmdSQL.ExecuteNonQuery()
End Using
End Using
End Sub
Now, when ALL files are up-loaded, then the server side even UpLoadComplete all will fire, and THEN you can take the above list/table and display the files up-loaded along with the FileName, size, and time.
But, you really don't have the ability to display the file information such as what time until such time you uploaded the file and then have the time, right?
Edit:
Perhaps the idea above was not all that clear. What I am suggesting is that you have the up-loader on the page.
So, say we drop in this markup:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" />
<asp:Button ID="cmdDone" runat="server" Text="Done" CssClass="btn" ClientIDMode="Static"/>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table"></asp:GridView>
</div>
And note how we use the client side all done click.
So, we now have this:
We hit upload, and now we see this:
Now we should (need to) hide the Done button - we have the upload clicking on that done button for us.
So that button in theory should become this to hide it:
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
And the code for that button is this:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
Dim rstFiles As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "select FileName, UpLoadTime, Size, User_id from MyUpLoadFiles"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstFiles.Load(cmdSQL.ExecuteReader)
End Using
End Using
Gfiles.DataSource = rstFiles
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub

The ConnectionString property has not been initialized for DropDownList

I have the following code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Reports</title>
<script language="javascript" src="js/DynamicReports.js" type="text/javascript"></script>
</head>
<body onload="doSelect()">
<asp:DropDownList ID="ddlDynReports" runat="server" DataSourceID="sdsDynReports" DataTextField="DynReportName" DataValueField="DynReportID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsDynReports" runat="server" SelectCommand="select v.object_id as DynReportID, substring(v.name, 11, LEN(v.name)) as DynReportName from sys.views v where v.name like 'DynReport[_]%'">
</asp:SqlDataSource>
</body>
</html>
It throws the following error at runtime:
The ConnectionString property has not been initialized.
My web.config file seems to be okay because I am doing many other sql calls in the .vb code. This is the first time I am doing sql in .aspx code.
I presume my connection that is available in my .vb code needs to be exposed to the .aspx code.
I am open to a solution that would move the select to the .vb code.
EDIT: I figured out that I should add ConnectionString="<%$ ConnectionStrings:constr %>" to the SqlDataSource element, but the problem is that I do not have connection strings in my web.config file. My connection strings are in a file called ApplicationConfig.vb.
So, how can I get the connection string out of ApplicationConfig.vb into the .aspx code?
EDIT: I am doing it this way because it is the sample code I found for populating a dropdown from a select statement. I am a vb.net noob so I am basically surviving by cutting and pasting from the SO. Suggestions for better ways is cheerfully accepted but I get lost if the example code is not complete. Example: Some example code I find on SO looks like what I want to do, but it is a series of snip-its and I don't know where to put those snip-its.
EDIT: Add .vb code:
Partial Class XXX_CommonPages_DynamicReports
Inherits System.Web.UI.Page
Protected Sub dynreport_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dynreports_run.ServerClick
Dim ViewObjectId As String = ddlDynReports.SelectedValue
Dim DataOut As String = "some,data,out"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=DynReport_" + ViewObjectId + ".csv")
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Length", DataOut.Length())
Response.Write(DataOut)
' Response.End ' Causes ThreadAbortException.
End Sub
End Class
EDIT: Here is the .vb code that contains the connection string:
Public Class ApplicationConfig
Public Class AppConfig
Implements IConfigurationSectionHandler
Private Const PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT As String = "serve ..."
Public Shared ReadOnly Property ConnectionString() As String
Get
If fieldConnectionString Is Nothing Then fieldConnectionString = PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT
Return fieldConnectionString
End Get
End Property
End Class
End Class

Changes to Site.Master page do not persist for a session

Good Afternoon.
I'm working with the following web pages using ms vwd 2010 express:
Site.Master/Site.Master.vb, Login.aspx/Login.aspx.vb
The Site.Master has the following:
<div class="loginDisplay">
<asp:Label ID="WelcomeLabel" runat="server" Text=""></asp:Label>
<asp:HyperLink ID="LogHyperlink" navigateurl="~/Account/Login.aspx" runat="server">Log In</asp:HyperLink>
</div>
I have the following code in the Login.aspx.vb program:
Dim WelcomeLabel As New Label
WelcomeLabel = CType(Master.FindControl("WelcomeLabel"), Label)
WelcomeLabel.Text = "Welcome " & OLEdr.Item("ho1FirstName")
Dim LogHyperlink As New HyperLink
LogHyperlink = CType(Master.FindControl("LogHyperlink"), HyperLink)
LogHyperlink.Text = "Log Out"
LogHyperlink.NavigateUrl = "Exit.aspx"
When a user logs in successfully the LogHyperlink is changed from Log In to
Log Out and the WelcomeLabel contains the text "Welcome " and person's first name. This all works fine.
However, the code only works for the Login.asp page. When I navigate to another
page, say About.aspx (which also uses the Site.Master), the Site.Master
page is back to the orginal and I have lost the changes the code made.
How can I make the changes persist for the session across all the
web pages? All the web pages use the Site.Master.
Thank you.
tfj
Have a look at the LoginView control. It seems you're trying to implement exactly what that control is for. It allows you to display different information depending on whether a user is logged in or not.
It is doable ( although I don't recommend it). In Login.aspx.vb add a line to save the user name in session:
Session("LoggedInUser") = OLEdr.Item("ho1FirstName").ToString()
Dim WelcomeLabel As New Label
WelcomeLabel = CType(Master.FindControl("WelcomeLabel"), Label)
WelcomeLabel.Text = "Welcome " & OLEdr.Item("ho1FirstName")
Dim LogHyperlink As New HyperLink
LogHyperlink = CType(Master.FindControl("LogHyperlink"), HyperLink)
LogHyperlink.Text = "Log Out"
LogHyperlink.NavigateUrl = "Exit.aspx"
In Site.Master.vb load the username from Session in Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Session("LoggedInUser") Is Nothing Then
WelcomeLabel.Text = Session("LoggedInUser").ToString()
LogHyperlink.Text = "Log Out"
LogHyperlink.NavigateUrl = "Exit.aspx"
Else
LogHyperlink.Text = "Log In"
LogHyperlink.NavigateUrl = "~/Account/Login.aspx"
WelcomeLabel.Text = ""
End If
End Sub

ASP.Net AutoCompleteExtender VB WebMethod not firing - why?

Definitely at my wits end here. This should be simple. In a page to create new user accounts, we have a database with a little of allowable users. To streamline getting the Email address of the new user correct, we want to use an AutoComplete extended textbox.
Now I know that WebMethods are working because I have a cascading-drop-down tied to web methods in another page.
As I'm just starting on this page, the code is simple.
The page itself:
<cc1:ToolkitScriptManager ID="ScriptManager2" runat="server"/>
<p></p> Please enter new user's Email:
<asp:TextBox ID="txtUser" runat="server" />
<cc1:AutoCompleteExtender runat="server" ID="autUser" TargetControlID="txtUser"
ServiceMethod="ScanGALUsers" ServicePath="~/AutoScan.asmx"
MinimumPrefixLength="3" CompletionSetCount="150" /> <p></p>
The .asmx file is simple:
<%# WebService Language="VB" CodeBehind="~/App_Code/VB_Code/AutoScan.vb" Class="AutoScan" %>
The WebMethod:
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class AutoScan
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Shared Function ScanGALUsers(ByVal strPrefix As String, ByVal intMaxCount As Integer) As String()
Dim arlResults As New ArrayList
Dim intCount As Integer
Dim dt As DataTable
Dim colParameters As New SortedList
SysDA.LogDebug("ScanGALUsers called with parameters: " & strPrefix & " and count of " & intMaxCount.ToString)
... Deleted for brevity ...
If intCount > 0 Then
Dim arrResults(intCount - 1) As String
arrResults = arlResults.ToArray(GetType(System.String))
Return arrResults
Else
Return Nothing
End If
End Function
End Class
I'm not even getting to the LogDebug statement. I've used all the same boilerplate code (Inherits, the 'WebService' tags, etc) that worked in the other WebMethod with the appropriate changes to the Class name but this really has me stumped.
What am I missing that I'm not even making it to the method?
Did you ever resolve this issue? Have you tried removing Shared from your WebService declaration? This has worked for me before (and I don't know why!).

vb.net upload file problem

When I try to post a file its coming back false ie there was no file attached. Can anyone see anything wrong with this? Or what might be causing it.
<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="cmdSubmitApplication" runat="server" Text="Button" />
</form>
Protected Sub cmdSubmitApplication_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmitApplication.Click
If Me.fileUpload.PostedFile Is Nothing Then
Response.Write("You must specify file to upload!")
Else
Try
Dim strExt As String = Path.GetExtension(Me.fileUpload.PostedFile.FileName)
If strExt.ToLower() = ".doc" Then
Dim savedFile As String
savedFile = Path.GetFileName(Me.fileUpload.PostedFile.FileName)
Me.fileUpload.PostedFile.SaveAs(Server.MapPath("cvs\") & savedFile)
Response.Write("File Uploaded Successfully")
Else
Response.Write("Only Image Files are Allowed")
End If
Catch exp As Exception
Response.Write(exp.Message)
End Try
End If
End Sub
Try using:
If Me.fileUpload.HasFile Then
Response.Write("You must specify file to upload!")
Else
here is a full working example from MSDN:
http://msdn.microsoft.com/en-us/kb/kb00323245.aspx
please have a look.
also try replacing "If Me.fileUpload.PostedFile Is Nothing Then" with "If fileUpload.PostedFile Is Nothing Then"
and check permissions on the destination folder
Try removing the enctype="multipart/form-data" from the form tag. I'm looking at my pages that I use the upload on and they don't have it.
I have the form tag in a master page, but it's just:
< form id="form1" runat="server" >
< form >
Public Sub UploadFile(ByVal BugID As System.Guid, ByVal Files As System.Web.UI.WebControls.FileUpload, ByVal fileDescription As String)
Dim guid As System.Guid = System.Guid.NewGuid()
Dim filesSave As New BugTrackerData.Files.Files()
Dim filename As String = Files.PostedFile.FileName
'Grab the file name from its fully qualified path at client
Dim strFileName As String = guid.ToString() & System.IO.Path.GetExtension(filename)
'Save uploaded file to server at C:\ServerFolder\
Dim savepath As String = System.Web.HttpContext.Current.Server.MapPath("~/Resources/FileUploads/" & strFileName)
Try
If Not String.IsNullOrEmpty(FileUpload1.FileName) Then
Files.PostedFile.SaveAs(savepath)
filesSave.SaveToDB(guid, BugID, strFileName, fileDescription)
End If
Catch Exp As Exception
Throw Exp
End Try
End Sub
fixed it. There was a tag in the master, so the form I added below was nested. I removed the form tag from the master. Would that cause problems elsewhere. Should I just remove the form tag above instead of the master.
ps I hate vb.net and everything about it.

Resources