Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

Amazon File upload - stop if duplicate file

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    #16
    I understand the synchronous and have used it many times. The problem with your example is that I don't know the file they have selected until AFTER I have started the File Upload. So I can't do the callback until halfway through the File Upload. Does that make sense?

    Comment


      #17
      Sorry about that. Amazing what can be missed when the ability to test isn't there.

      Are you adamant about using the javascript action, or would you be willing to use xbasic as demonstrated here
      Gregg
      https://paiza.io is a great site to test and share sql code

      Comment


        #18
        You should be saving the name of the file to upload in your database each and every time, then next time when the file gets selected to upload - check the database for the user and see if it exists already - before going to S3.
        Just Saying ..

        Pete - Hi Gregg - doing a good support job mate.

        Insanity: doing the same thing over and over again and expecting different results.
        Albert Einstein, (attributed)
        US (German-born) physicist (1879 - 1955)

        Comment


          #19
          Originally posted by peteconway View Post
          You should be saving the name of the file to upload in your database each and every time, then next time when the file gets selected to upload - check the database for the user and see if it exists already - before going to S3.
          Exactly what I'm already doing. But I don't know what file they are going to select for the upload until they have selected the file. Once they select it, I compare it in the database and flag it if it's a duplicate. As I said originally, this all works. What doesn't work, is getting the "After File Select" event to hold and NOT upload until after it's received my flag. And using the Action Javascript, that is the ONLY place I can deal with the filename before beginning the upload.

          Comment


            #20
            Originally posted by madtowng View Post
            Sorry about that. Amazing what can be missed when the ability to test isn't there.

            Are you adamant about using the javascript action, or would you be willing to use xbasic as demonstrated here
            That's probably what I'm going to have to do. It is just impossible in the Javascript Action for the S3 upload. Even getting that action to perform another action synchronously, the After File Select event does not wait for anything to return, and i cannot force it with timeouts or separate action javascript or splitting into separate functions. The entire process works to check if it's a duplicate and let the user know, but it still continues with the upload.

            Comment


              #21
              Can you show me your code in the AfterSelect?

              Also, try this code in the afterSelect, and see if it aborts the upload every time:

              return false;

              Comment


                #22
                Originally posted by Russell Craycraft View Post
                Can you show me your code in the AfterSelect?

                Also, try this code in the afterSelect, and see if it aborts the upload every time:

                return false;
                Thanks for chiming in. Yes, the "return false;" works fine. So does my code to check for invalid characters in the below code.

                This is my current version of code, where everything works except for waiting for the callback before uploading:

                Code:
                for(var i=0; i < e.length; i++) {
                    //check for invalid characters
                    var match = (new RegExp('[<>:*"?&#%(){}+\\\/\|]|\\.\\.|^\\.|\\.$')).test(e[i]["name"]);
                    if (match) {
                        {dialog.object}.setValue('upload','no');
                        var title = 'Invalid Filename';
                        var html = '<p style="padding:10px;text-align:center;">Invalid file name. The name of the attached file (<b>'+e[i]["name"]+'</b>) contains invalid characters. <br><br>Please rename your file without special characters before attaching.</p>'
                        var type = 'o';
                        var onClose = function (btn) {};
                        A5.msgBox.show(title, html, type,onClose);
                        return false;
                
                    } else {
                        //check for duplicate filenames
                        var network={dialog.object}.getSessionVariable('Network');
                        var addData ='_shortname='+e[i]["name"]+
                        '&_network='+network;
                               {dialog.Object}.ajaxCallback('','','checkDuplicates','',addData);
                               thisFilename=e[i]["name"];    
                
                        //wait for callback to complete and get updated value of upload control
                        canUpload={dialog.object}.getValue('upload');
                        if(canUpload=="no"){
                            var title = 'Duplicate Found';
                            var html = '<p style="padding:10px;text-align:center;">A file with the name '+ thisFilename+' already exists.<br><br>Please Delete or Update instead.</p>'
                            var type = 'o';
                            var onClose = function (btn) {};
                            A5.msgBox.show(title, html, type,onClose);
                            return false;
                        }  
                    }
                    if(canUpload=="no"){
                        return false;
                    }
                }​
                As I've mentioned, I've tried this hundreds of ways - with setTimeouts, using "thisthenthat", using a separate Action Javascript, shuffling the order of the JavaScript code so it runs the callback first, then checks for invalid characters, and many other things. Not one thing has been successful. I tried to set up a promise/resolve, but wasn't familiar enough with the JavaScript to make it work.

                Comment


                  #23
                  It's late, and I've put in enough time today lol. I did run this through ChatGPT and can give you a starting point if it helps for Promise/Resolve.

                  Code:
                  // Assuming ajaxCallback returns a Promise; if not, you'll need to adapt this to your implementation.
                  function checkDuplicateAsync(name) {
                      return new Promise((resolve, reject) => {
                          const network = {dialog.object}.getSessionVariable('Network');
                          const addData = `_shortname=${name}&_network=${network}`;
                          {dialog.Object}.ajaxCallback('', '', 'checkDuplicates', '', addData, (result) => {
                              // Assuming result is an object that contains a status; adjust based on your actual callback result.
                              if (result.status === "ok") {
                                  resolve(false); // No duplicate found
                              } else {
                                  resolve(true); // Duplicate found
                              }
                          }, (error) => {
                              reject(error); // Handle error case
                          });
                      });
                  }
                  
                  // Then, use this function in an async context
                  (async function() {
                      for (let i = 0; i < e.length; i++) {
                          // Check for invalid characters first
                          let match = (new RegExp('[<>:*"?&#%(){}+\\\/\|]|\\.\\.|^\\.|\\.$')).test(e[i]["name"]);
                          if (match) {
                              // Handle invalid filename
                              // ...
                              return false; // Exit if needed, or use 'continue;' to proceed with the next iteration
                          } else {
                              // Check for duplicate filenames
                              try {
                                  let isDuplicate = await checkDuplicateAsync(e[i]["name"]);
                                  if (isDuplicate) {
                                      // Handle duplicate filename
                                      // ...
                                      return false; // Exit if needed
                                  }
                              } catch (error) {
                                  console.error("Error checking for duplicates:", error);
                                  // Handle error appropriately
                              }
                          }
                      }
                  })();
                  ​

                  Comment


                    #24
                    Notes from ChatGPT:

                    The structure of your code indicates a few potential issues that could cause it not to work as expected. Here are some points to consider:
                    1. Syntax and Placeholder Issue: The code snippet contains placeholders (e.g., {dialog.object}) that seem to be intended for replacement or interpolation with actual object references. Make sure these placeholders are correctly replaced with actual references in your working environment.
                    2. Asynchronous Processing: The call to ajaxCallback for checking duplicate filenames appears to be asynchronous. This means the code immediately after this call (checking the canUpload variable) might execute before the callback has completed, leading to a logic error where canUpload does not yet reflect the result of the duplicate check. JavaScript does not wait for asynchronous calls to complete before moving to the next line of code.
                    3. Variable Scope: The use of var for variables like thisFilename and canUpload means they are function-scoped, not block-scoped, which can lead to unexpected behavior in loops and conditionals. Especially if the code dealing with canUpload relies on its value being set in an asynchronous callback, you might encounter scope-related issues.
                    4. Error Handling: There's no apparent error handling for the asynchronous request. If the request fails or encounters an issue, the code might not behave as expected.
                    5. Return Statement in a Loop: The return false; statements within your loop will exit the entire function, not just the loop iteration. If the intention is to skip the current iteration and continue with the next one, you should use continue; instead of return false;. However, if your intention is indeed to exit the function upon finding an invalid filename or a duplicate, then the return false; statement is appropriate.

                    To address some of these concerns, consider the following suggestions:
                    • Replace Placeholders: Ensure all {dialog.object} placeholders are replaced with the actual object references in your code.
                    • Handle Asynchronous Logic: If the ajaxCallback is asynchronous and you need to wait for its result before proceeding, consider using Promises or async/await syntax to wait for the asynchronous operation to complete. This might require restructuring your code to work with asynchronous patterns.
                    • Refactor Variable Declarations: Use let or const instead of var for block-scoped variables. This can help prevent issues related to variable hoisting and make the code more predictable.
                    • Introduce Error Handling: Add error handling for your asynchronous requests to gracefully manage failures or unexpected results.

                    Here's a conceptual start on how you might begin to refactor your code to handle asynchronous logic better, using Promises (note that further modifications will be required based on your specific environment and logic):

                    Comment


                      #25
                      Thankyou. I will definitely give the promise/resolve a try but I suspect that the issue is with the After File Select action rather than the code. Think I'll enjoy the long weekend here first 😁

                      Comment


                        #26
                        For anyone having similar issues in the future, I ended up doing the S3 Upload completely in Javascript using the Amazon SDK so things would execute in the correct order, and using AWS Credentials to hide keys and codes from the script. Happy to report that it is all working flawlessly.

                        Comment

                        Working...
                        X