Trying to understand logic for boolean

Jason Phang

Well-known member
Joined
Aug 13, 2019
Messages
46
Programming Experience
Beginner
At the moment, my program is able to upload files and display alert messages to users when it is uploaded. The thing is now, after uploading, it is supposed to see if it is a duplicate file or not. If it is, then a message alert will inform the user that it is a duplicate while if it is new , then the user gets to upload the file and a message informing the user the file is uploaded is displayed. The thing is, I know there is something off with my logic but I am unable to find a way to wrap this up. As of now, when I upload a file, irregardless of new or same file, it is being uploaded to the Google Drive and the message alerting the user that it is uploaded is being displayed. I know there is a problem with my boolean but I am not too sure how to resolve it.

Compare Hash Function:
        public static bool compareHash(string path)
        {
            
            DriveService service = GetService();
            FilesResource.ListRequest FileListRequest = service.Files.List();
            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
            List<GoogleDriveFiles> FileList = new List<GoogleDriveFiles>();

            foreach (var file in files)
            {
                if (file.Equals(path))
                {
                    return false; //if it is a duplicate return false
                
                }
                else
                {
                    return true; //if it is new, then return true
                }
            }
          return false; //I am not too sure what this affects the overall boolean of the code
          
        }
File Upload Method:
  public static bool FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                DriveService service = GetService();

               string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),Path.GetFileName(file.FileName));
                file.SaveAs(path);
                if(compareHash(path))
                {
                    var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                    FileMetaData.Name = Path.GetFileName(file.FileName);
                    FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
                    FilesResource.CreateMediaUpload request;

                    using (var stream = new FileStream(path, FileMode.Open))
                    {
                        request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                        request.Fields = "id";
                        request.Upload();
                    }

                    return true;
                }
                return false;             
            }
            return true;//it will always return true to the controller for upload, yes? How do i make it like
      //check for the condition from the hash generator?
        }

C#:
        [HttpPost]
        public JsonResult UploadFile(HttpPostedFileBase file)
        {
            bool kk = GoogleDriveFilesRepository.FileUpload(file);
            return Json(kk, JsonRequestBehavior.AllowGet);
        }

File Upload Razor:
 event.preventDefault();
                            var formData = new FormData($('form')[0]);

                            $.ajax({
                                url: "/Home/UploadFile",
                                type: 'Post',
                                success: function (result) {
                                    if (result) {
                                        Swal.fire({
                                            title: 'Wait awhile...',
                                            text: 'File will be uploaded shortly',
                                            type: 'success',
                                            confirmButtonText: 'Okay, cool',
                                            timer: 4000
                                        })
                                        location.href = "/Home/GetGoogleDriveFiles";
                                      
                                    } else {
                                        Swal.fire({
                                            title: 'OOps',
                                            text: 'File unable to be uploaded shortly',
                                            type: 'error',
                                            confirmButtonText: 'Okay, then',
                                            timer: 4000
                                        })
                                        location.href = "/Home/GetGoogleDriveFiles";
                                    
                                    }
                                },
                                data: formData,
                                cache: false,
                                contentType: false,
                                processData: false
                            });

Sorry for the lengthy post. It is just this last hurdle and I want to understand how can I sort of check the condition whether its true or not because if I understand correctly, in the last return true from this return true;//it will always return true to the controller for upload, yes? How do i make it like //check for the condition from the hash generator? overrides the entire boolean and jsut return true all the time.
 
Where did you acquire the code from?

If you wrote it you would know what it's doing.

If you wrote it, and don't know what it's doing, you need to do more research on the areas in which make no sense to you.

If you acquired it from someone else, you should ask them how the code works.

You need MD5 Class (System.Security.Cryptography) to compare the MD5 checksums of a file, and not compare the filenames as a method to see if a file exists...

if(compareHash(path)). - Before you go fixing this. You need to do some housework. An upload event should be for uploading the file, and nothing more.

In public static bool compareHash(string path) Where do you compare the hash of any file?

Separate your code so its compartmentalised into functions. Doing so will help you with troubleshooting. Try not to dump to much code into one method.

  • Have a method for the upload
  • Have a function to check google drive for a file with existing md5 sum of the file being uplaoded
  • Have a function to get the md5 of a file currently being uploaded
  • Have a function to compare the two md5s of the files, and if either match, return false, and abort the upload, and alert the user of the error
 
Where did you acquire the code from?

If you wrote it you would know what it's doing.

If you wrote it, and don't know what it's doing, you need to do more research on the areas in which make no sense to you.

If you acquired it from someone else, you should ask them how the code works.

You need MD5 Class (System.Security.Cryptography) to compare the MD5 checksums of a file, and not compare the filenames as a method to see if a file exists...

if(compareHash(path)). - Before you go fixing this. You need to do some housework. An upload event should be for uploading the file, and nothing more.

In public static bool compareHash(string path) Where do you compare the hash of any file?

Separate your code so its compartmentalised into functions. Doing so will help you with troubleshooting. Try not to dump to much code into one method.

  • Have a method for the upload
  • Have a function to check google drive for a file with existing md5 sum of the file being uplaoded
  • Have a function to get the md5 of a file currently being uploaded
  • Have a function to compare the two md5s of the files, and if either match, return false, and abort the upload, and alert the user of the error

The file upload code I got it from Youtube and mixture of some websites but the compare hash and generate hash, I wrote it. Regarding the MD5 checksum, I had two dilemmas. The first is, I already got the generate hash code which is public static string HashGenerator(string path) { using (var md5 = MD5.Create()) { using (var stream = new FileStream(path, FileMode.Open)) { return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); } } } and the other is I get the hash of the files from the Google Drive files properties. But I am not too sure which to use as I have used both but both are yielding the same result which is the file will be uploaded irregardless even if it is same.

For the compare hash, public static bool compareHash(string pathFile) { DriveService service = GetService(); FilesResource.ListRequest FileListRequest = service.Files.List(); FileListRequest.Fields = "*"; IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files; List<GoogleDriveFiles> FileList = new List<GoogleDriveFiles>(); foreach (var file in files) { if (file.Md5Checksum.Equals(pathFile)) { return false; //check all hash of the files and if there is same, return false which will pass to the file upload. } } return true; }

My idea was that if the false value is returned, then it will pass that bool value to the file upload method and the file upload method will run whatever function based on the bool value. I am trying how to be able to make the logic of this code block to return the bool value according to the compare hash bool instead of just return true all the time.
C#:
    if(!compareHash(path))
                {
                    var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                    FileMetaData.Name = Path.GetFileName(file.FileName);
                    FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
                    FilesResource.CreateMediaUpload request;

                    using (var stream = new FileStream(path, FileMode.Open))
                    {
                        request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                        request.Fields = "id";
                        request.Upload();
                    }

                    return true;
                }
                    return false;                     
            }
            return false;
 
I finally got it to work.

C#:
      //file Upload to the Google Drive.
        public static bool FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                DriveService service = GetService();

               string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),Path.GetFileName(file.FileName));
               file.SaveAs(path);

                var hash = HashGenerator(path);

               if(!CompareHash(hash))
                {
                    var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                    FileMetaData.Name = Path.GetFileName(file.FileName);
                    FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
                    FilesResource.CreateMediaUpload request;

                    using (var stream = new FileStream(path, FileMode.Open))
                    {
                        request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                        request.Fields = "id";
                        request.Upload();
                    }
                  
                    return true; //determine if file is uploaded or not
                }
                return false;   //affects message                 
            }
           return false;
          
        }
        
        public static string HashGenerator(string path)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
                }
            }
        }

        public static bool CompareHash (string hash)
        {
            var service = GetService();
            var fileListRequest = service.Files.List();
            fileListRequest.Fields = "*";
            var files = fileListRequest.Execute().Files;

            foreach(var file in files)
            {
                if(file.Md5Checksum.Equals(hash))
                {
                    return true;
                }

            }
            return false;
        }
 
Back
Top Bottom