Beispiel #1
0
        async public Task <DocProof> PutProof(string bindingId, string citizenIdentifier, Microsoft.AspNetCore.Http.IFormFile proofDocs = null)
        {
            //create storage container and set permissions
            CloudBlobContainer container = blobClient.GetContainerReference(bindingId);
            await container.CreateIfNotExistsAsync();

            BlobContainerPermissions permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Off
            };

            await container.SetPermissionsAsync(permissions);

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(citizenIdentifier);

            // string fileString = "";
            byte[] fileHash = null;

            using (var fileStream = proofDocs.OpenReadStream())
            {
                await blockBlob.UploadFromStreamAsync(fileStream);

                fileStream.Seek(0, SeekOrigin.Begin);
                using (var md5 = MD5.Create())
                {
                    fileHash = md5.ComputeHash(fileStream);
                }
            }

            var storedProofDocs = new DocProof()
            {
                Container       = bindingId,
                ContentType     = proofDocs.ContentType,
                FileName        = citizenIdentifier,
                Hash            = GetHash(bindingId, Encoding.UTF8.GetString(fileHash)),
                StorageSharding = "none"
            };

            //Update profile with proof document info
            //Should be controlled by Application  -- Commented by DB
            //await UpdateProofDocument(bindingId, storedProofDocs, "The Proof document was proven and stored");

            return(await Task.Run(() => storedProofDocs));
        }
Beispiel #2
0
        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Private methods
         */

        /// <summary>
        /// Execute the configured action for the upload
        /// </summary>
        /// <param name="id">Primary key value</param>
        /// <param name="upload">Posted file</param>
        /// <returns>File identifier - typically the primary key</returns>
        private dynamic _actionExec(dynamic id, IFormFile upload)
        {
            if (_actionStr == null)
            {
                // Custom function
                return(_actionFn != null?
                       _actionFn(upload, id) :
                           null);
            }

            // Default action - move the file to the location specified by the
            // action string
            string to = _path(_actionStr, upload.FileName, id);

            try
            {
#if NETCOREAPP2_1
                using (var readStream = upload.OpenReadStream())
                {
                    using (var writeStream = new StreamWriter(to))
                    {
                        readStream.CopyTo(writeStream.BaseStream);
                    }
                }
#else
                upload.SaveAs(to);
#endif
            }
            catch (Exception e)
            {
                _error = "Error saving file. " + e.Message;
                return(false);
            }

            return(id ?? to);
        }
Beispiel #3
0
        /// <summary>
        /// Add a record to the database for a newly uploaded file
        /// </summary>
        /// <param name="editor">Host editor</param>
        /// <param name="upload">Uploaded file</param>
        /// <returns>Primary key value for the newly uploaded file</returns>
        private dynamic _dbExec(Editor editor, IFormFile upload)
        {
            var db         = editor.Db();
            var pathFields = new Dictionary <string, string>();

            // Insert the details requested, for the columns requested
            var q = db.Query("insert")
                    .Table(_dbTable)
                    .Pkey(new [] { _dbPKey });

            foreach (var pair in _dbFields)
            {
                var column = pair.Key;
                var prop   = pair.Value;
#if NETCOREAPP2_1
                var contentLength = (int)upload.Length;
#else
                var contentLength = upload.ContentLength;
#endif

                if (prop is DbType)
                {
                    var propType = (DbType)prop;

                    switch (propType)
                    {
                    case DbType.ReadOnly:
                        break;

                    case DbType.Content:
                        q.Set(column, upload.ToString());
                        break;

                    case DbType.ContentBinary:
                        byte[] fileData = null;
#if NETCOREAPP2_1
                        var stream = upload.OpenReadStream();
#else
                        var stream = upload.InputStream;
#endif
                        using (var binaryReader = new BinaryReader(stream))
                        {
                            fileData = binaryReader.ReadBytes(contentLength);
                            q.Set(column, fileData);
                        }
                        break;

                    case DbType.ContentType:
                    case DbType.MimeType:
                        q.Set(column, upload.ContentType);
                        break;

                    case DbType.Extn:
                        q.Set(column, Path.GetExtension(upload.FileName));
                        break;

                    case DbType.FileName:
                        q.Set(column, Path.GetFileName(upload.FileName));
                        break;

                    case DbType.FileSize:
                        q.Set(column, contentLength);
                        break;

                    case DbType.SystemPath:
                        pathFields.Add(column, "__SYSTEM_PATH__");
                        q.Set(column, "-"); // Use a temporary value to avoid cases
                        break;              // where the db will reject empty values

                    case DbType.WebPath:
                        pathFields.Add(column, "__WEB_PATH__");
                        q.Set(column, "-");     // Use a temporary value (as above)
                        break;

                    default:
                        throw new Exception("Unknown database type");
                    }
                }
                else
                {
                    try
                    {
                        // Callable function - execute to get the value
                        var propFn = (Func <Database, IFormFile, dynamic>)prop;

                        pathFields.Add(column, propFn(db, upload));
                        q.Set(column, "-"); // Use a temporary value (as above)
                    }
                    catch (Exception)
                    {
                        // Not a function, so use the value as it is given
                        pathFields.Add(column, prop.ToString());
                        q.Set(column, "-"); // Use a temporary value (as above)
                    }
                }
            }

            var res = q.Exec();
            var id  = res.InsertId();

            // Update the newly inserted row with the path information. We have to
            // use a second statement here as we don't know in advance what the
            // database schema is and don't want to prescribe that certain triggers
            // etc be created. It makes it a bit less efficient but much more
            // compatible
            if (pathFields.Any())
            {
                // For this to operate the action must be a string, which is
                // validated in the `exec` method
                var path = _path(_actionStr, upload.FileName, id);
#if NETCOREAPP2_1
                var physicalPath = Directory.GetCurrentDirectory() ?? "";
                var webPath      = physicalPath.Length != 0 ?
                                   path.Replace(physicalPath, "") :
                                   "";
#else
                var physicalPath = editor.Request().PhysicalApplicationPath ?? "";
                var webPath      = physicalPath.Length != 0 ?
                                   path.Replace(physicalPath, Path.DirectorySeparatorChar.ToString()) :
                                   "";
#endif

                var pathQ = db
                            .Query("update")
                            .Table(_dbTable)
                            .Where(_dbPKey, id);

                foreach (var pathField in pathFields)
                {
                    var val = _path(pathField.Value, upload.FileName, id)
                              .Replace("__SYSTEM_PATH__", path)
                              .Replace("__WEB_PATH__", webPath);

                    pathQ.Set(pathField.Key, val);
                }

                pathQ.Exec();
            }

            return(id);
        }
Beispiel #4
0
        public static async Task <string> ProcessFormFile(Microsoft.AspNetCore.Http.IFormFile formFile,
                                                          ModelStateDictionary modelState)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(FileUpload).GetProperty(
                    formFile.Name.Substring(formFile.Name.IndexOf(".") + 1));

            if (property != null)
            {
                var displayAttribute =
                    property.GetCustomAttribute(typeof(DisplayAttribute))
                    as DisplayAttribute;

                if (displayAttribute != null)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            // Use Path.GetFileName to obtain the file name, which will
            // strip any path information passed as part of the
            // FileName property. HtmlEncode the result in case it must
            // be returned in an error message.
            var fileName = WebUtility.HtmlEncode(
                Path.GetFileName(formFile.FileName));

            if (formFile.ContentType.ToLower() != "text/plain")
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) must be a text file.");
            }

            // Check the file length and don't bother attempting to
            // read it if the file contains no content. This check
            // doesn't catch files that only have a BOM as their
            // content, so a content length check is made later after
            // reading the file's content to catch a file that only
            // contains a BOM.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) is empty.");
            }
            else if (formFile.Length > 1048576)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB.");
            }
            else
            {
                try
                {
                    string fileContents;

                    // The StreamReader is created to read files that are UTF-8 encoded.
                    // If uploads require some other encoding, provide the encoding in the
                    // using statement. To change to 32-bit encoding, change
                    // new UTF8Encoding(...) to new UTF32Encoding().
                    using (
                        var reader =
                            new StreamReader(
                                formFile.OpenReadStream(),
                                new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,
                                                 throwOnInvalidBytes: true),
                                detectEncodingFromByteOrderMarks: true))
                    {
                        fileContents = await reader.ReadToEndAsync();

                        // Check the content length in case the file's only
                        // content was a BOM and the content is actually
                        // empty after removing the BOM.
                        if (fileContents.Length > 0)
                        {
                            return(fileContents);
                        }
                        else
                        {
                            modelState.AddModelError(formFile.Name,
                                                     $"The {fieldDisplayName}file ({fileName}) is empty.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"The {fieldDisplayName}file ({fileName}) upload failed. " +
                                             $"Please contact the Help Desk for support. Error: {ex.Message}");
                    // Log the exception
                }
            }

            return(string.Empty);
        }