This is a migrated thread and some comments may be shown as answers.

AsyncUpload lost its state on server-side validation

20 Answers 369 Views
AsyncUpload
This is a migrated thread and some comments may be shown as answers.
Andy
Top achievements
Rank 1
Andy asked on 27 Oct 2014, 05:02 AM
Hi Telerik,

I have AsyncUpload on my page, and I have a very complex validation on the page - this is where server-side validation is used.

When the user does not fill in all mandatory fields / fulfil the submission criteria, error messages will be shown on the page.
At this time, the AsyncUpload control do not keep the earlier uploaded document anymore. 
I believe it was because the PostbackTriggers set to btnSubmit, and the client state is lost.

<telerik:RadAsyncUpload id="RadUpload1" runat="server" PostbackTriggers="btnSubmit" />

Is there anyway for me to preserve the AsyncUpload client state in the server-side?
For example, in the below code, as soon as I have detected that the "IsIdeaValid" is false, I will preserve the AsyncUpload client state.
Please advice.

protected void btnSubmit_Click(object sender, EventArgs e)
        {         
            ErrorMessage = "";
            if(!IsIdeaValid())
                return;

20 Answers, 1 is accepted

Sort by
0
SANJAY
Top achievements
Rank 1
answered on 27 Oct 2014, 08:32 AM
Hi Andy

To the best of my understanding, you should call the validation function bu a button which is not the postbacktrigger button. If the validation passes then call the postback button programmatically


Regards


Sanjay Gupta
0
Andy
Top achievements
Rank 1
answered on 27 Oct 2014, 10:28 AM
Thank you for your reply Sanjay. Are you referring to calling the validation button through javascript?
Do you have any page to refer me to for any demo code on what you have explained to me?
0
SANJAY
Top achievements
Rank 1
answered on 27 Oct 2014, 11:33 AM
Hi Andy

I donot have a demo page. Please give me a idea of your code. I donot need all the validation I would just need the javascript that you call after successfull validation and after failed validation

Regards


Sanjay Gupta
0
Andy
Top achievements
Rank 1
answered on 27 Oct 2014, 11:49 AM
Hi Sanjay.

Basically, i did not call anything from javascript. The validation is on server-side, that is where the client state is lost.
I am looking for an approach to retain the client state during the server-side validation. 

If you see the code on my first post, you will see that the PostbackTriggers has "btnSubmit" as the value.
In the btnSubmit_click, it will do user input validation first before saving the form.
If there is something invalid entered by user input, it will return the whole function without saving the form. And this is where the AsyncUpload client state lost.
0
SANJAY
Top achievements
Rank 1
answered on 27 Oct 2014, 12:08 PM
Hi Andy

On Button_Click


if validation success then
    if len(me.session("tfile") ) > 0 then
        system.io.file.move(me.session("tfile"), finaldestination)
        me.session("tfile") = ""
    endif
else
    e.filesaveas = "~/myfolder/" & e.filename
    me.session("tfile") = "~/myfolder/" & e.filename
   'Give the message of failed validation to the user

endif


On Page load
if not ispostback then me.session.remove("tfile")

Hope this help
0
Andy
Top achievements
Rank 1
answered on 11 Nov 2014, 10:59 PM
Hi Sanjay,

Thank you for the reply. Unfortunately, it does not work for me. The Session["tfile"] is always NULL.

Any other method to preserve the AsyncUpload client state for buttons that are not specified in PostbackTriggers?

Thank you.
0
Andy
Top achievements
Rank 1
answered on 13 Nov 2014, 06:37 AM
Can anyone help me? I am totally stuck. Thank you.
0
SANJAY
Top achievements
Rank 1
answered on 14 Nov 2014, 02:34 AM
Hi Andy

I am sorry I did not see your post 2 days back

Enclosed a small test project.

The checkbox is used as validation process. If the checkbox is checked then I am treating the same in the code that validation has passeed

I have tested by uploading a file with check box unchecked. then check the check box and press the button "save Images" I am treating this has the changes for passing the validation have been made. the file is accessed and reached the location.

I noticed that you are coding in C#, I am more comfortable with vb. Hence the code is in VB. It would be kind of you to change the same to c#

Telerik Dll are not enclosed in the bin directory.

It is not allowing me to upload zip file so I have changed the extension to jpg, kindly rename to a.zip and then unzip.

Regards


Sanjay
0
SANJAY
Top achievements
Rank 1
answered on 14 Nov 2014, 02:48 AM
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test-upload.aspx.vb" Inherits="test_upload" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>Staff Members</title>
        <link href="css/drpd/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="form1" runat="server">
            <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            </telerik:RadScriptManager>
            <telerik:RadWindowManager ID="RadWindowManager1" runat="server">
                <Windows>
                    <telerik:RadWindow ID="wndPdfPreview" runat ="server" VisibleOnPageLoad="false" VisibleStatusbar="true"
                                       ShowContentDuringLoad= "false" KeepInScreenBounds ="true" VisibleTitlebar="true" ></telerik:RadWindow>
                </Windows>
            </telerik:RadWindowManager>
            <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
                <script type="text/javascript">
                    //<![CDATA[
                    var $ = $telerik.$;

                    function pageLoad() {
                        if (!Telerik.Web.UI.RadAsyncUpload.Modules.FileApi.isAvailable()) {
                            $(".qsf-demo-canvas").html("<strong>Your browser does not support Drag and Drop.</strong>");
                        } else {
                            $(document).bind({
                                                 "drop": function (e) {
                                                     e.preventDefault();
                                                 }
                                             });
                            var dropZone1 = $(document).find(".DropZone1");
                            dropZone1.bind({
                                               "dragenter": function (e) {
                                                   dragEnterHandler(e, dropZone1);
                                               }
                                           })
                                .bind({
                                          "dragleave": function (e) {
                                              dragLeaveHandler(e, dropZone1);
                                          }
                                      })
                                .bind({
                                          "drop": function (e) {
                                              dropHandler(e, dropZone1);
                                          }
                                      });
                            var dropZone2 = $(document).find("#DropZone2");
                            dropZone2.bind({
                                               "dragenter": function (e) {
                                                   dragEnterHandler(e, dropZone2);
                                               }
                                           })
                                .bind({
                                          "dragleave": function (e) {
                                              dragLeaveHandler(e, dropZone2);
                                          }
                                      })
                                .bind({
                                          "drop": function (e) {
                                              dropHandler(e, dropZone2);
                                          }
                                      });
                        }
                    }
                    function dropHandler(e, dropZone) {
                        dropZone[0].style.backgroundColor = "#357A2B";
                    }
                    function dragEnterHandler(e, dropZone) {
                        var dt = e.originalEvent.dataTransfer;
                        var isFile = (dt.types != null && (dt.types.indexOf ? dt.types.indexOf(`Files`) != -1 :
                                                           dt.types.contains(`application / x - moz - file`)));
                        if (isFile || $telerik.isSafari5 || $telerik.isIE10Mode || $telerik.isOpera)
                            dropZone[0].style.backgroundColor = "#000000";
                    }
                    function dragLeaveHandler(e, dropZone) {
                        if (!$telerik.isMouseOverElement(dropZone[0], e.originalEvent))
                            dropZone[0].style.backgroundColor = "#357A2B";
                    }
                    //]]>
                </script>
            </telerik:RadScriptBlock>
            <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" OutputCompression="AutoDetect"></telerik:RadStyleSheetManager>
            <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" MinDisplayTime="3000"  Transparency="25"></telerik:RadAjaxLoadingPanel>
            <telerik:RadSkinManager ID="QsfSkinManager" runat="server" ShowChooser="false" />
            <telerik:RadFormDecorator runat="server" id="RadFormDecorator1" DecoratedControls="All" EnableRoundedCorners="true"
                                      EnableEmbeddedSkins="true" RenderMode="Lightweight" />
            <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="timer1">
                        <UpdatedControls>
                            <telerik:AjaxUpdatedControl ControlID="tml" LoadingPanelID="RadAjaxLoadingPanel1" />
                        </UpdatedControls>
                    </telerik:AjaxSetting>
                </AjaxSettings>
            </telerik:RadAjaxManager>
            <telerik:RadNotification ID="RadNotification1" runat="server" LoadContentOn="TimeInterval"
                                     Width="300" Animation="Fade" EnableRoundedCorners="true" EnableShadow="true" Height="70"
                                     Title="Status" OffsetX="-200" OffsetY="-200" BackColor= "Red" ForeColor="Black" TitleIcon="none" AutoCloseDelay="30000">
                <ContentTemplate>
                    <asp:Label ID="lblr" runat="server" Text=""></asp:Label>
                </ContentTemplate>
            </telerik:RadNotification>
            <asp:Timer ID="timer1" runat="server" Interval="300000"></asp:Timer>
            <asp:Label ID="tml" runat="server"
                       Visible="false"></asp:Label>
            <telerik:RadPageLayout ID="pgl" runat="server" GridType="Fluid">
                <telerik:LayoutRow>
                    <Columns>
                        <telerik:LayoutColumn Span="2">

                        </telerik:LayoutColumn>
                        <telerik:LayoutColumn Span="10">
                            <asp:CheckBox ID="vald" Text="Process of Validation" runat="server" />
                        </telerik:LayoutColumn>

                    </Columns>
                </telerik:LayoutRow>
                <telerik:LayoutRow>
                    <Columns>
                        <telerik:LayoutColumn Span="2">

                        </telerik:LayoutColumn>
                        <telerik:LayoutColumn Span="10">
                            <div class="qsf-demo-canvas" style="height:400px;">
                                <h2>Upload Images</h2>
                                <div class=".qsf-fb">
                                    <telerik:RadAsyncUpload runat="server" ID="RadAsyncUpload1" AllowedFileExtensions="jpg,jpeg,png,gif"
                                                            MaxFileSize="1524288"  skin="Sunset" DropZones=".DropZone1"  MultipleFileSelection="Automatic" PostbackTriggers="btnsvi">
                                    </telerik:RadAsyncUpload>
                                    <telerik:RadButton ID="btnsvi" runat="server" Text="Save Images"  SingleClick="true" SingleClickText="Saving Images"></telerik:RadButton>
                                    <div class="DropZone1">
                                        <p>Drop Your Images Here for Upload</p>
                                        <p>Drop Files Here</p>
                                    </div>
                                </div>
                            </div>
                        
                        </telerik:LayoutColumn>

                    </Columns>
                </telerik:LayoutRow>
                <telerik:LayoutRow>
                    <Columns>
                        <telerik:LayoutColumn Span="2">

                        </telerik:LayoutColumn>
                        <telerik:LayoutColumn Span="10">

                        </telerik:LayoutColumn>

                    </Columns>
                </telerik:LayoutRow>

            </telerik:RadPageLayout>
        </form>
    </body>
</html>


==============================================



Partial Class test_upload
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            If Not IsPostBack Then 'IMportant to ensure that variables are cleared on page onload only
                Me.Session("tfile") = ""
            Else ' it is post back again then

               


                'if required you can check that validation was caused by which button



                If Len(Me.Session("tfile")) > 0 Then
                    If vald.Checked Then 'rund the validation code and check if passes the n
                        'Do whatever else has to be doen
                        Dim finalP As String
                        Dim flName As String
                        'process to set the final name of the filename
                        flName = "abc.jpg" ' I have set this explictily you might need some code to set the name
                        finalP = Me.Server.MapPath("~/final/") & flName
                        System.IO.File.Move(Me.Session("tfile"), finalP)
                        Me.Session("tfile") = ""

                        'I wouldprefer a clean up code to delete the temporary directory here

                    End If
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub RadAsyncUpload1_FileUploaded(sender As Object, e As Telerik.Web.UI.FileUploadedEventArgs) Handles RadAsyncUpload1.FileUploaded
        Try
            Dim path As String
            path = Me.Server.MapPath("~/temp/") & Me.Session.SessionID 'Session id will ensure that multiple sessions donot mix
            If Not System.IO.Directory.Exists(path) Then System.IO.Directory.CreateDirectory(path)

            e.File.SaveAs(path & "\" & e.File.GetName)
            Me.Session("tfile") = path & "\" & e.File.GetName
            Me.Session("lclfile") = e.File.FileName

            'Now run the validation code
            'if the validation check passes
            If vald.Checked = True Then
                Dim finalP As String
                finalP = Me.Server.MapPath("~/final/") & e.File.GetName
                System.IO.File.Move(path, finalP)
                Me.Session("tfile") = ""
            Else 'validation has failed exit sub

            End If

        Catch ex As Exception

        End Try
    End Sub
End Class

0
SANJAY
Top achievements
Rank 1
answered on 14 Nov 2014, 02:58 AM
Hi Andy

If you are able to achieve the target with the code, then

Add a label just above the Upload control. On post back if the Lenght of the me.session("Tfile") > 0 then in the label show the text eg

1 file has been uploaded to temporary directory


Regards     
0
Andy
Top achievements
Rank 1
answered on 17 Nov 2014, 01:59 AM
Hi Sanjay,

Thank you so much for getting back to me.
I have created a C# solution on the code that you gave me. To make it less complicated, I have removed the styling and javascript to drag & drop files. https://onedrive.live.com/redir?resid=37227F77B1ACDDA8%21164 

I am still getting blank for session["tfile"]. I enclosed the solution that i have converted into c#.
Please advice whether I have done something wrong there.

FYI. I am using Telerik version 2012.3.1205.35


0
SANJAY
Top achievements
Rank 1
answered on 17 Nov 2014, 03:49 AM
Hi Andy

I have executed your code with telerik 2014.2.724.40 , I guess that would not make a difference.

You need to change the following in your code

You need to add the parameter OnFileUploaded="RadAsyncUpload1_FileUploaded" in <telerik:RadAsyncUpload

This is because in C# you need to explicitly mention the code to be called on post back. Without this parameter it is never entering the FileUploaded code and hence the session object doesnot get a value.

I have successfully executed the code.

Hope this helps


Regards



Sanjay Gupta
0
Andy
Top achievements
Rank 1
answered on 17 Nov 2014, 06:17 AM
Hi Sanjay,

Sorry for missing that bit, yes, it is required by C#.
I am able to upload a file now. 

1. I wonder, why do we need to have the file upload code in the Page_Load?
2. The file is still missing after failed in page validation.
    I unchecked "Process of Validation", upload a file, and click "Save Images" - but the uploaded file is still missing.
    What I expect is as per the attach screenshot. Before upload, and after upload (failed on page validation), it should show the same thing. Is this achievable? And this was my original question :)

0
SANJAY
Top achievements
Rank 1
answered on 17 Nov 2014, 06:38 AM
Hi Andy

Pardon me if I am wrong

Telerik control starts uploading the file as soon as you select the file. On the trigger file as soon as trigger happens the file moves from the temp folder to new location. Even if you do exit sub before calling e.saveAs the file is lost

Experience taught me make many such turnarounds. I faced the simillar problem when I upload files and primary record is not yet updated saved( so the id is not available comparable to your case of validation failure)

I hope alteast you are able to tide over the crisis if any

You can put a label above the file upload. If your varialble tmp.lenght > 0 then you can label the text with name of file or hide the label


Regards


Sanjay Gupta
0
Andy
Top achievements
Rank 1
answered on 17 Nov 2014, 07:14 AM
Hi Sanjay,

Thank you for the explanation.
So, what you are suggesting is to control the listing of uploaded file myself, instead of using the one provided by Telerik. Because I like the file listing provided by Telerik, where it has the uploaded file status "green" or "orange" - which is very intuitive.

Is this the only way to do it for this scenario?
0
SANJAY
Top achievements
Rank 1
answered on 17 Nov 2014, 09:10 AM
Hi Andy

NO, I am recommedning that you use the telerik control.  Save the file in session object and if the validation fails show the label with then name of file ( the file is already uploaded). After the completion of validation hide the label and show the telerik control for new upload

In the mean time I will try hard to help reach a code that the file persists


Regards

Sanjay Gupta
0
Andy
Top achievements
Rank 1
answered on 18 Nov 2014, 12:21 AM
Hi Sanjay,

Yes, that will be really appreciated if you can find out on how to persist the file - without doing the suggested workarounds. 
Hope to hear from you.

Regards,
Andy Taslim
0
Accepted
SANJAY
Top achievements
Rank 1
answered on 18 Nov 2014, 03:17 AM
Hi Andy

Hope this would resolve your issue

1) Put a new button : <asp:Button ID="btnupl" runat="server" Text="Upload" />
2) Change the post back trigger control to : PostbackTriggers="btnupl"
3) Javascript code on
<script type="text/javascript">

             function upload_fls()

             {
                 alert("a");
                 document.getElementById("<%=btnupl.ClientID%>").click();
                }

</script>

4) Server side code
 Protected Sub btnsvi_Click(sender As Object, e As EventArgs) Handles btnsvi.Click
        Try
            If vald.Checked Then
                Dim ScriptString As String = "function f(){upload_fls();Sys.Application.remove_load(f);};Sys.Application.add_load(f);"

                ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "pdfOpener", ScriptString, True)
            End If
        Catch ex As Exception

        End Try
    End Sub


Logic

The server side code button executes to call the validation check. If validation fails then the files will persist in Upload control
If validation clears then it will call the java script which in turn will call the upload code

the working vb code (Tested successfully) on link
www.thetaskmate.com/app/telerik/asyntest.zip


Regards


Sanjay Gupta
0
SANJAY
Top achievements
Rank 1
answered on 19 Nov 2014, 09:18 AM
Hi Andy

I am eagerly waiting for you to evaluate

Regards
0
Andy
Top achievements
Rank 1
answered on 19 Nov 2014, 10:49 AM
Hi Sanjay,
 
I have just implemented it into my code today, it worked like charm. You saved my life. Thank you so much for your help. Really appreciate it.
 
Regards 
Andy Taslim 
Tags
AsyncUpload
Asked by
Andy
Top achievements
Rank 1
Answers by
SANJAY
Top achievements
Rank 1
Andy
Top achievements
Rank 1
Share this question
or