Exemple #1
0
 /// <summary>
 /// Saves file from attachment View Model to given path.
 /// </summary>
 /// <param name="model">Attachment View Model that contains attachment file</param>
 /// <param name="filePath">File path where file need to be saved</param>
 /// <returns></returns>
 public async Task SaveFile(AttachmentViewModel model, string filePath)
 {
     using (var stream = new FileStream(filePath, FileMode.CreateNew))
     {
         await model.File.CopyToAsync(stream);
     }
 }
        public ActionResult Generate(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var rental = _context.Rental
                         .Include(a => a.Address)
                         .Include(c => c.Order.Customer)
                         .Include(m => m.Machinist)
                         .Include(m => m.Machine)
                         .SingleOrDefault(r => r.Id == id);

            if (rental == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new AttachmentViewModel
            {
                Attachment   = new Attachment(),
                SignatureImg = new SignatureImg(),
                Rental       = rental,
                Customers    = _context.Customer.ToList()
            };

            return(View("AttachmentsForm", viewModel));
        }
Exemple #3
0
        /// <summary>
        /// Saves attachment in Attachments folder and creates entry in attachments table in database
        /// </summary>
        /// <param name="model">An AttachmentViewModel with all data passed from form: file and description</param>
        /// <param name="createdBy">ApplicationUser which is adding attachment</param>
        /// <returns>created attachment model from ViewModel</returns>
        public async Task <Attachment> Add(AttachmentViewModel model, ApplicationUser createdBy)
        {
            var uniqueFileName = FileHelper.GetUniqueFileName(model.File.FileName);
            //var uploads = Path.Combine(HostingEnvironment.WebRootPath, AttachmentsFolder);
            //var uploads = Path.Combine("wwwroot", AttachmentsFolder);
            var filePath = Path.Combine(AttachmentsFolder, uniqueFileName);

            await FileHelper.SaveFile(model, filePath);

            var newAttachment = new Attachment()
            {
                CreatedById      = createdBy.Id,
                CreatedDate      = DateHelper.GetCurrentDatetime(),
                DocumentType     = model.DocumentType,
                DocumentId       = model.DocumentId,
                FileDescription  = model.FileDescription,
                OriginalFileName = model.File.FileName,
                FilePath         = filePath,
                ContentType      = model.File.ContentType
            };

            Context.Attachments.Add(newAttachment);
            var result = Context.SaveChanges();

            if (result == 0)
            {
                throw new Exception("Nie zapisano żadnych danych.");
            }

            return(newAttachment);
        }
        public async Task <IActionResult> RegistrationDocs(AttachmentViewModel attachmentViewModel, string applicationTraceId)
        {
            var fileCategory = Request.Form["FileCategory"];
            var rootPath     = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\documents", applicationTraceId);

            if (!Directory.Exists(rootPath))
            {
                Directory.CreateDirectory(rootPath);
            }



            var admissionApplication = _context.AdmissionApplications.Where(p => p.TraceId == applicationTraceId).Single();
            int i = 0;

            foreach (var attachment in attachmentViewModel.ApplicationAttachmentFiles)
            {
                _fileService.UploadFile(attachment, rootPath);
                admissionApplication.ApplicationAttachments.Add(new ApplicationAttachment {
                    FileName = attachment.FileName, FileCategory = fileCategory[i], AdmissionApplication = admissionApplication
                });
                i++;
            }
            _context.Update(admissionApplication);
            await _context.SaveChangesAsync();

            return(RedirectToAction("AttachDocs", new { applicationTraceId = applicationTraceId }));
        }
        public IActionResult Index()
        {
            AttachmentViewModel model = new AttachmentViewModel();

            model.attachments = _appContext.attachments.Select(m => m).ToList();
            return(View(model));
        }
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var attachment = _context.Attachment
                             .Include(s => s.SignatureImg)
                             .Include(r => r.Rental)
                             .Include(m => m.Rental.Machinist)
                             .Include(m => m.Rental.Machine)
                             .Include(a => a.Rental.Address)
                             .Include(c => c.Rental.Order.Customer)
                             .SingleOrDefault(m => m.Id == id);

            if (attachment == null)
            {
                return(HttpNotFound());
            }

            attachment.IsApproved = attachment.IsSigned = true;

            var viewModel = new AttachmentViewModel
            {
                Attachment   = attachment,
                SignatureImg = attachment.SignatureImg,
                Rental       = attachment.Rental,
                Customers    = _context.Customer.ToList(),
                Hours        = TimeSpan.FromTicks(attachment.WorkingHoursTicks).Hours,
                Minutes      = TimeSpan.FromTicks(attachment.WorkingHoursTicks).Minutes
            };

            return(View("AttachmentsForm", viewModel));
        }
Exemple #7
0
        // GET: Attachment/Create
        public ActionResult Attach(string id)
        {
            var vm = new AttachmentViewModel();

            vm.UID = new Guid(id);
            return(PartialView("AttachFormPartial", vm));
        }
Exemple #8
0
        public static AttachmentViewModel DownloadFile(string downloadParam)
        {
            AttachmentViewModel result = new AttachmentViewModel();

            result.FileContent = new byte[0];

            try
            {
                //Decode parameter
                byte[] data         = Convert.FromBase64String(downloadParam);
                string decodedParam = Encoding.Unicode.GetString(data);

                string fullPath = System.Web.HttpContext.Current.Server.MapPath(decodedParam);

                result.FileContent = System.IO.File.ReadAllBytes(@fullPath);

                result.SavedFileName = Path.GetFileName(fullPath);

                int index = result.SavedFileName.IndexOf('_');
                if (index > 0)
                {
                    result.FileName = result.SavedFileName.Substring(index + 1);
                }
                else
                {
                    result.FileName = result.SavedFileName;
                }
            }
            catch (Exception ex)
            {
            }

            return(result);
        }
Exemple #9
0
        public ActionResult Delete(int?flowerId, string attachmentName)
        {
            if (flowerId == null || attachmentName == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Missing parameters for the request."));
            }

            // Check that attachment exists
            Attachment attachment = uow.Attachments.Find(flowerId, attachmentName);

            if (attachment == null)
            {
                return(HttpNotFound());
            }

            if (!IsOwnedAttachment(attachment))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, "You do not own the file you request to delete"));
            }

            // Build view model
            AttachmentViewModel attachmentViewModel = new AttachmentViewModel
            {
                FlowerId = flowerId.Value,
                Name     = attachmentName
            };

            return(View(attachmentViewModel));
        }
Exemple #10
0
        public async Task <IActionResult> Create([Bind("PkJobAttachmentId,FkAttachmentJob,JobAttachmentFilePath,JobAttachmentFileName,JobAttachmentDownloadName")] AttachmentViewModel tblJobAttachment)
        {
            if (ModelState.IsValid)
            {
                string uniqufilename = null;
                if (tblJobAttachment.JobAttachmentFilePath != null && tblJobAttachment.JobAttachmentFilePath.Count > 0)
                {
                    foreach (var attachment in tblJobAttachment.JobAttachmentFilePath)
                    {
                        string filefolder = Path.Combine(_environment.WebRootPath, "Files");
                        uniqufilename = Guid.NewGuid().ToString() + "_" + attachment.FileName;
                        string filepath = Path.Combine(filefolder, uniqufilename);
                        attachment.CopyTo(new FileStream(filepath, FileMode.Create));
                        TblJobAttachment jobAttachment = new TblJobAttachment()
                        {
                            FkAttachmentJob           = tblJobAttachment.FkAttachmentJob,
                            JobAttachmentDownloadName = tblJobAttachment.JobAttachmentDownloadName,
                            JobAttachmentFileName     = tblJobAttachment.JobAttachmentFileName,
                            JobAttachmentFilePath     = uniqufilename,
                        };
                        _context.Add(jobAttachment);
                    }
                }

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index), "TblJobs"));
            }
            ViewData["FkAttachmentJob"] = new SelectList(_context.TblJob, "PkJobId", "JobBudget", tblJobAttachment.FkAttachmentJob);
            return(View(tblJobAttachment));
        }
Exemple #11
0
        public HttpResponseMessage DeleteAttachment(long docId)
        {
            AttachmentViewModel viewModel = new AttachmentViewModel()
            {
                DocumentID = docId
            };

            var successMessage = string.Empty;

            try
            {
                AttachmentResponse resonse = docrepositoryService.DeleteAttachment(
                    new AttachmentRequest()
                {
                    AttachmentViewModel = viewModel
                });

                if (resonse.Exception != null)
                {
                    successMessage = resonse.Exception.Message;
                }
                else
                {
                    successMessage = "Successfully Deleted Attachement";
                }
            }
            catch (Exception ex)
            {
                successMessage = ex.Message;
            }


            return(Request.CreateResponse(successMessage));
        }
Exemple #12
0
        public async Task <JsonResult> UpdateAttachment([FromBody] AttachmentViewModel model)
        {
            var           homePageId = rkbcSetting.Value.HomePageId;
            List <string> errmsg     = new List <string>();
            List <string> succmsg    = new List <string>();
            Attachment    modelObj   = new Attachment();

            if ((!ModelState.IsValid) || (model.id == 0))
            {
                errmsg.Add("Unabled to update the image.");
            }
            else
            {
                modelObj = await unitOfWork.attachments.get(model.id).FirstOrDefaultAsync();

                if (modelObj == null)
                {
                    errmsg.Add("Unabled to update the image.");
                }
                unitOfWork.attachments.update(modelObj);
                modelObj.isOn = model.isOn;
                modelObj.attachmentSectionEnum = model.sectionId;
                modelObj.pageEnum = (int)setPageEnum(model.sectionId);
                var success = await unitOfWork.tryCommitAsync();

                if (success)
                {
                    succmsg.Add("Updated.");
                }
                else
                {
                    errmsg.Add("unabled to update the image.");
                }
            }
            var strerrmsg = ""; if (errmsg.Count() > 0)
            {
                foreach (var s in errmsg)
                {
                    strerrmsg += "<p class=\"error\">" + s + "</p>";
                }
            }
            var strsuccmsg = ""; if (succmsg.Count() > 0)
            {
                foreach (var s in succmsg)
                {
                    strsuccmsg += "<p>" + s + "</p>";
                }
            }
            var result = new
            {
                success   = errmsg.Count == 0,
                isOn      = modelObj.isOn,
                sectionId = modelObj.attachmentSectionEnum,
                errmsg    = strerrmsg,
                succmsg   = strsuccmsg,
            };

            return(Json(result));
        }
Exemple #13
0
        /// <summary>
        /// Gets attachment View Model for given attachment id, document type and document Id.
        /// </summary>
        /// <param name="id">Attachment Id for attachment</param>
        /// <param name="documentType">Document type for attachment</param>
        /// <param name="documentId">Document Id for attachment</param>
        /// <returns>Attachment View Model for given attachment id, document type and document Id</returns>
        public AttachmentViewModel GetAttachmentViewModelById(string id, DocumentType documentType, string documentId)
        {
            var attachment = GetAttachmentById(id, documentType, documentId, false);

            var model = new AttachmentViewModel(attachment);

            return(model);
        }
Exemple #14
0
        // GET: Attachment/Create
        public JsonResult GetRecord(int id)
        {
            var model = new AttachmentViewModel();

            model.sectionId = (int)AttachmentSectionEnum.Home_Gallery;

            return(Json(model));
        }
Exemple #15
0
        public async Task <IActionResult> Delete(int attachmentId, AttachmentViewModel attachment)
        {
            var model = await _webApiCalls.Download(attachmentId);

            await _webApiCalls.Delete(attachmentId, model);

            return(RedirectToAction("Index", new { model.RequestId }));
        }
Exemple #16
0
        // GET: Attachment
        public ActionResult Index(string id)
        {
            var vm = new AttachmentViewModel();

            vm.UID         = new Guid(id);
            vm.Attachments = AttachmentRepository.GetAttachments(vm.UID);
            return(View(vm));
        }
Exemple #17
0
        public async Task OpenFileBrowserMenu()
        {
            var canOpenFileDialog = Locator.Current.GetService <ICanOpenFileDialog>();
            var attachmentsPatch  = await canOpenFileDialog.Open();

            await AttachmentViewModel.Open(attachmentsPatch);

            AttachMenuVisible = false;
        }
Exemple #18
0
        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var avm = (sender as Image).DataContext as AttachmentViewModel;

            if (avm != null)
            {
                try
                {
                    // Remove location attachment
                    if (avm.Type == AttachmentType.Location)
                    {
                        App.Current.EntityService.AttachedLatitude  = string.Empty;
                        App.Current.EntityService.AttachedLongitude = string.Empty;

                        AttachmentViewModel temp = null;
                        foreach (var item in _model)
                        {
                            if (item.Type == AttachmentType.Location)
                            {
                                temp = item;
                                break;
                            }
                        }

                        if (temp != null)
                        {
                            _model.Remove(temp);
                        }
                    }
                    // Remove photo attachment.
                    else
                    {
                        if (App.Current.EntityService.AttachmentPhotos.Remove(avm.Uri))
                        {
                            AttachmentViewModel temp = null;
                            foreach (var item in _model)
                            {
                                if (item.Uri == avm.Uri)
                                {
                                    temp = item;
                                    break;
                                }
                            }

                            if (temp != null)
                            {
                                _model.Remove(temp);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Image_Tap failed: " + ex.Message);
                }
            }
        }
        private void AttachmentOpenMenu_Click(object sender, RoutedEventArgs e)
        {
            AttachmentViewModel attachmentInfo = (AttachmentViewModel)AttachmentListView.SelectedItem;

            if (attachmentInfo != null)
            {
                Process.Start(attachmentInfo.FilePath);
            }
        }
 public AttachmentDTO MapFrom(AttachmentViewModel entity)
 {
     return(new AttachmentDTO()
     {
         FileName = entity.FileName,
         SizeMb = entity.SizeMb,
         SizeKb = entity.SizeKb
     });
 }
Exemple #21
0
        public ActionResult DisplayAttachmentRow(AttachmentViewModel attachment)
        {
            if (!string.IsNullOrEmpty(attachment.DocumentTypeValueType))
            {
                attachment.DocumentTypeValueHelp = ValueHelpService.GetValueHelp(attachment.DocumentTypeValueType);
            }

            return(PartialView("~/Views/Shared/AttachmentItem.cshtml", attachment));
        }
        /// <summary>
        /// Delete an entity.
        /// </summary>
        /// <param name="model"></param>
        public void Delete(AttachmentViewModel model)
        {
            var entity = model.ToEntity();

            this._AttachmentsRepository.Delete(entity);

            #region Commit Changes
            this._unitOfWork.Commit();
            #endregion
        }
Exemple #23
0
        private void removeAttachmentMenu_Click(object sender, RoutedEventArgs e)
        {
            AttachmentViewModel selectedAttachmentVm = (AttachmentViewModel)attachmentListView.SelectedItem;
            NewEmailViewModel   viewModel            = (NewEmailViewModel)this.DataContext;

            if (selectedAttachmentVm != null && viewModel.Attachments.Contains(selectedAttachmentVm))
            {
                viewModel.Attachments.Remove(selectedAttachmentVm);
            }
        }
Exemple #24
0
        private bool _AddLocationAttachment()
        {
            if (!string.IsNullOrEmpty(App.Current.EntityService.AttachedLatitude) &&
                !string.IsNullOrEmpty(App.Current.EntityService.AttachedLongitude))
            {
                try
                {
                    string uri = String.Format(AppResources.GeolocationMapUriFormatMessage,
                                               App.Current.EntityService.AttachedLatitude.Replace(",", "."),
                                               App.Current.EntityService.AttachedLongitude.Replace(",", "."));

                    var avm = new AttachmentViewModel(-1, -1, -1, AttachmentType.Location, uri, null, null, null, null);
                    _model.Add(avm);

                    string filename     = CommonHelper.DoDigest(uri);
                    var    photosToLoad = new List <AvatarLoadItem>();
                    photosToLoad.Add(new AvatarLoadItem(1, uri, filename));

                    var service = new AsyncAvatarsLoader();

                    if (photosToLoad.Any())
                    {
                        service.LoadAvatars(photosToLoad.ToList(), id =>
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                try
                                {
                                    ImageCache cache  = new ImageCache();
                                    BitmapImage image = cache.GetItem(filename);

                                    if (image != null && image.PixelHeight > 0 && image.PixelWidth > 0)
                                    {
                                        avm.AttachPhoto = image;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("_AddLocationAttachment failed in AttachmentsPage: " + ex.Message);
                                }
                            });
                        }, null);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Load attached location photo failed " + ex.Message);
                }

                return(true);
            }

            return(false);
        }
 private void Play(GestureEventArgs e)
 {
     this.SetPlayPauseVisibilityManually(false);
     Logger.Instance.Info("AudioAttachmentUC.play_Tap, AssignedCurrentTrack = " + this.AssignedCurrentTrack.ToString());
     this.NotifyPlaying();
     if (!this.AssignedCurrentTrack)
     {
         AttachmentViewModel dc = this.DataContext as AttachmentViewModel;
         if (dc != null)
         {
             AudioTrack track = AudioTrackHelper.CreateTrack(this.AttachmentVM.Audio);
             Logger.Instance.Info("Starting track for uri: {0}", dc.ResourceUri);
             BGAudioPlayerWrapper.Instance.Track = track;
             if (!this._initializedUri)
             {
                 Logger.Instance.Info("AudioAttachmentUC initializedUri = false, getting updated audio info");
                 AudioService  instance = AudioService.Instance;
                 List <string> ids      = new List <string>();
                 ids.Add(dc.MediaOwnerId.ToString() + "_" + dc.MediaId);
                 Action <BackendResult <List <AudioObj>, ResultCode> > callback = (Action <BackendResult <List <AudioObj>, ResultCode> >)(res =>
                 {
                     if (res.ResultCode != ResultCode.Succeeded)
                     {
                         return;
                     }
                     this._initializedUri = true;
                     AudioObj audio = res.ResultData.FirstOrDefault <AudioObj>();
                     if (audio == null)
                     {
                         return;
                     }
                     if (audio.url != dc.ResourceUri)
                     {
                         return;
                     }
                     Logger.Instance.Info("Received different uri for audio: {0}", audio.url);
                     dc.ResourceUri = audio.url;
                     dc.Audio       = audio;
                     this.Dispatcher.BeginInvoke(delegate
                     {
                         if (!this.AssignedCurrentTrack && BGAudioPlayerWrapper.Instance.Track != null || (BGAudioPlayerWrapper.Instance.PlayerState == PlayState.Paused || AudioTrackHelper.GetPositionSafe().TotalMilliseconds >= 1E-05))
                         {
                             return;
                         }
                         BGAudioPlayerWrapper.Instance.Track = AudioTrackHelper.CreateTrack(audio);
                         this.Play();
                     });
                 });
                 instance.GetAudio(ids, callback);
             }
         }
     }
     this.Play();
 }
Exemple #26
0
 public AudioMediaListItemViewModel(AudioObj audio, List <AudioObj> audios)
     : base(ProfileMediaListItemType.Audio)
 {
     this._audio          = audio;
     this._audios         = audios;
     this._audioViewModel = new AttachmentViewModel(new Attachment
     {
         type  = "audio",
         audio = audio
     } /*, null*/);
 }
Exemple #27
0
        public AttachmentResponse GeAttachment(AttachmentRequest request)
        {
            AttachmentResponse response   = new AttachmentResponse();
            Attachment         attachment = attachmentRepository.FindBy(Convert.ToInt16(request.AttachmentViewModel.DocumentID));

            if (attachment != null)
            {
                AttachmentViewModel attachmentViewModel = Mapper.Map <Attachment, AttachmentViewModel>(attachment);
                response.AttachmentViewModel = attachmentViewModel;
            }
            return(response);
        }
        public ActionResult Create()
        {
            var viewModel = new AttachmentViewModel
            {
                Attachment   = new Models.Attachment(),
                SignatureImg = new SignatureImg(),
                Customers    = _context.Customer.ToList(),
                Rental       = _context.Rental.Single(r => r.Id == 1)
            };

            return(View("AttachmentsForm", viewModel));
        }
        public static AttachmentViewModel ToVM(this EmailAttachmentsDTO attachmentDTO)
        {
            var model = new AttachmentViewModel
            {
                Id       = attachmentDTO.Id,
                FileName = attachmentDTO.FileName,
                FileSize = attachmentDTO.FileSize,
                EmailId  = attachmentDTO.EmailId
            };

            return(model);
        }
        public ActionResult Delete(int CaseID, Guid AttachmentID, long?SessionID = null)
        {
            vw_Documents        DocumentData = AttachmentService.GetDocumentData(AttachmentID);
            AttachmentViewModel model        = new AttachmentViewModel
            {
                AttachmentTypeID = DocumentData.TypeID,
            };

            return(CPartialView(new FileAttachment {
                AttachmentID = AttachmentID, CaseID = CaseID, SessionID = SessionID, AttachmentType = model.AttachmentTypeID.ToString()
            }));
        }