Example #1
0
        /// <summary>
        /// Upload a document and associated image
        /// </summary>
        /// <param name="email"></param>
        /// <param name="rooturl"></param>
        /// <param name="encodedId"></param>
        /// <param name="documentImage"></param>
        /// <returns></returns>
        public async Task <bool> UploadDocumentImage(string email, string rooturl, string encodedId,
                                                     DocumentImageModel documentImage)
        {
            bool result = false;

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(rooturl) || string.IsNullOrEmpty(encodedId) ||
                documentImage?.Document == null || documentImage.Image == null)
            {
                return(false);
            }

            string      payload = new SerializerServices().SerializeObject(documentImage);
            string      url     = $"{rooturl}api/documentimages";
            HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

            LoggingService service   = new LoggingService();
            var            stopwatch = new Stopwatch();

            try
            {
                var response = await new WebApiServices().PostData(url, content, encodedId);
                result = response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                service.TrackException(ex);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                var properties = new Dictionary <string, string>
                {
                    { "UserEmail", email },
                    { "WebServicesEndpoint", rooturl },
                    { "EncodedId", encodedId },
                    { "DocumentName", documentImage.Document.Name }
                };
                service.TrackEvent(LoggingServiceConstants.UploadDocumentImage, stopwatch.Elapsed, properties);
            }
            return(result);
        }
        public async Task OnPostUpload(IEnumerable <IFormFile> files)
        {
            this.ErrorMessage = "";

            //ensure all information is correctly filled in before proceeding
            bool isValid = this.ValidateUpload(files);

            //retrieve the document ID passed on the querystring - retrieved in the OnGet()
            this.CurrentDocumentId = HttpContext.Session.Get <int>(SessionConstants.CurrentDocumentId);

            if (isValid)
            {
                string description = Request.Form["document_details_description_upload"];
                string type        = Request.Form["document_details_type_upload"];
                string category    = Request.Form["document_details_category_upload"];
                var    user        = HttpContext.Session.Get <UserModel>(SessionConstants.CurrentUser);

                var    fileToUpload = files.First();
                string filename     = fileToUpload.FileName;
                long   fileLength   = fileToUpload.Length;
                byte[] buffer       = new byte[fileLength];

                //read the image into a byte array
                using (var stream = fileToUpload.OpenReadStream())
                {
                    stream.Read(buffer, 0, (int)fileLength);
                }

                var currentUser = HttpContext.Session.Get <UserModel>(SessionConstants.CurrentUser);

                DocumentImageModel document = new DocumentImageModel
                {
                    UploadedBy = HttpContext.Session.Get <int>(SessionConstants.CurrentUserId)
                };
                document.Document = new DocumentsModel
                {
                    Description        = description,
                    CompanyId          = currentUser.CompanyId,
                    CompanyName        = currentUser.CompanyName,
                    Category           = Convert.ToInt32(category),
                    Name               = filename,
                    Active             = true,
                    IsDocument         = true,
                    IsPrivate          = true,
                    LastViewed         = DateTime.MinValue,
                    UploadedBy         = document.UploadedBy,
                    DocumentType       = Convert.ToInt32(type),
                    ParentId           = this.CurrentDocumentId,
                    Subscribers        = null,
                    UploadedByUsername = user.UserName
                };

                var documentType =
                    new DocumentManagerPageModelService().GetDocumentTypeForDocument(Convert.ToInt32(type), HttpContext.Session.Get <DocumentTypeModels>(SessionConstants.DocumentTypes));

                //possibly do a check to see if the DocumentModel.MimeType and the FileToUpload.ContentType are the same
                //fileToUpload.ContentType == documentType.MimeType

                document.Image = new ImageStreamModel
                {
                    MimeType   = documentType.MimeType,
                    ImagesList = new Dictionary <string, byte[]>
                    {
                        { filename, buffer }
                    }
                };

                //add any subscribers to the document
                var subscribers = this.GetDocumentSubscribers();
                if (subscribers != null && subscribers.Any())
                {
                    document.Document.Subscribers = subscribers;
                    document.Document.IsPrivate   = false;
                }

                string email     = HttpContext.Session.Get <string>(SessionConstants.EmailClaim);
                string rootUrl   = HttpContext.Session.Get <string>(SessionConstants.WebServicesUrl);
                string encodedId = HttpContext.Session.Get <string>(SessionConstants.EncodedUserId);

                var success = await new DocumentManagerPageModelService().UploadDocumentImage(email, rootUrl, encodedId, document);

                if (!success)
                {
                    this.ErrorMessage = StringConstants.DocumentUploadError;
                    await this.PopulateDataSources();
                }
                else
                {
                    var users = HttpContext.Session.Get <UserModels>(SessionConstants.CompanyUsers);
                    document.Document = new DocumentManagerPageModelService().UpdateDocumentSubscribers(document.Document, users);
                    await new DocumentManagerPageModelService().NotifySubscribers(document.Document, rootUrl);

                    this.DocumentCategories = new List <SelectListItem>();
                    this.DocumentTypes      = new List <SelectListItem>();

                    //force the document manager page to re-load the document manager treeview
                    HttpContext.Session.Set <ToolbarModel>(SessionConstants.DocumentManagerToolbar, null);

                    //navigate back to the document manager page
                    Response.Redirect("/DocumentManager/DocumentManager");
                }
            }
            else
            {
                await this.PopulateDataSources();
            }
        }