Example #1
0
 internal FileList(string path)
 {
     this.path = path;
       this.fileLocationList = new List<string>();
       this.fileResult = FileResult.Undefined;
       LoadFileList();
 }
Example #2
0
 internal JobResult(int jobID, LoadFile loadFile, ModifiedFile modifiedFile, WriteFile writeFile)
 {
     this.jobID = jobID;
       this.originalPath = loadFile.Path;
       this.newPath = writeFile.Path;
       this.loadFileResult = loadFile.Result;
       this.modifiedFileResult = modifiedFile.Result;
       this.writeFileResult = writeFile.Result;
 }
Example #3
0
        private void LoadFileList()
        {
            try
              {
            Path.GetFullPath(path);
              }
              catch (Exception)
              {
            fileLocationList = new List<string> { path };
            fileResult = FileResult.IllegalFilename;
            return;
              }

              try
              {
            FileAttributes fileAttributes = File.GetAttributes(path);
            if (!fileAttributes.HasFlag(FileAttributes.Directory))
            {
              fileLocationList = new List<string> { path };
              fileResult = FileResult.Success;
              return;
            }
              }
              catch (FileNotFoundException)
              {
            fileLocationList = new List<string> { path };
            fileResult = FileResult.PathNotFound;
            return;
              }
              catch (Exception)
              {
            fileLocationList = new List<string> { path };
            fileResult = FileResult.UnknownError;
            return;
              }

              if (!Directory.Exists(path))
              {
            fileLocationList = new List<string> { path };
            fileResult = FileResult.PathNotFound;
            return;
              }

              try
              {
            fileLocationList = Directory.GetFiles(path, "*.mp4").ToList<string>();
              }
              catch (Exception)
              {
            fileLocationList = new List<string> { path };
            fileResult = FileResult.UnknownError;
            return;
              }

              fileResult = FileResult.Success;
        }
Example #4
0
        public void ProcessResult_WhenCreatedWithPathToUnknownFile_ReturnsPathToFileAndHasDispositionHeader()
        {
            var response = new FakeResponseContext();
            var result = new FileResult("..\\..\\Test Data\\HandlerResult\\Files\\Download.unknown");

            result.ProcessResult(null, response);

            Assert.That(response.ContentType, Is.EqualTo("application/unknown"));
            Assert.IsTrue(response.Response.EndsWith("\\Test Data\\HandlerResult\\Files\\Download.unknown"));
            Assert.That(response.Headers["Content-Disposition"], Is.EqualTo("attachment; filename=Download.unknown"));
        }
Example #5
0
        public void ProcessResult_WhenCreatedWithPathToHtmlFile_ReturnsPathToFileAndHasDispositionHeader()
        {
            var response = new FakeResponseContext();
            var result = new FileResult("..\\..\\Test Data\\HandlerResult\\Views\\View.html");

            Assert.That(result.FilePath, Is.EqualTo("..\\..\\Test Data\\HandlerResult\\Views\\View.html"));

            result.ProcessResult(null, response);

            Assert.That(response.ContentType, Is.EqualTo("text/html"));
            Assert.IsTrue(response.Response.EndsWith("\\Test Data\\HandlerResult\\Views\\View.html"));
            Assert.That(response.Headers["Content-Disposition"], Is.EqualTo("attachment; filename=View.html"));
        }
 public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
 {
     var fileResult = new FileResult();
     foreach (var file in files)
     {
         if (file.ContentLength > 0)
         {
             var fileName = Path.GetFileName(file.FileName);
             var path = Path.Combine(Server.MapPath("~/assets/img/uploads"), fileName);
             file.SaveAs(path);
             fileResult.files.Add(new File { name = file.FileName, size = file.ContentLength, url = Url.Content("~/assets/img/uploads/" + fileName) });
         }
     }
     return Json(fileResult);
 }
Example #7
0
        private void videoSourcePlayer_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();

            if (task.Contains(0))
            {
                String timepath = DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + "_" + device_id;
                string img      = this.save_path + "\\" + timepath + ".jpg";
                bitmap.Save(img);
                task.Remove(0);

                FileResult fr = rf.UploadFile(img, CacheService.Instance.GetStuToken());
                if (fr != null)
                {
                    if (fr.code == "200")
                    {
                        //关联文件与记录
                        List <Attach> attaches = new List <Attach>();
                        foreach (Student s in CacheService.Instance.GetStudentList())
                        {
                            Attach a = new Attach {
                                subjectId = s.RecordId, ownerId = s.Id, type = "EXPERIMENT_RECORD_IMAGE"
                            };
                            attaches.Add(a);
                        }

                        AttachResult ar = rf.AttachRecordWithFile(CacheService.Instance.ExperimentId, fr.data.id, attaches, CacheService.Instance.GetStuToken());

                        if (ar != null)
                        {
                            if (ar.code == "200")
                            {
                                UploadFile up = new UploadFile()
                                {
                                    FileName = timepath + ".jpg", FileType = fileType, Status = UploadFile.SUCCESS, FilePath = img, Id = fr.data.id, Color = "#FF979797", Operation = UploadFile.OPENDOC
                                };
                                this.cb.Dispatcher.BeginInvoke(updateListBoxAction, this.cb, up);
                            }
                            else
                            {
                                UploadFile up = new UploadFile()
                                {
                                    FileName = timepath + ".jpg", FileType = fileType, Status = UploadFile.FAIL, FilePath = img, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                                };
                                this.cb.Dispatcher.BeginInvoke(updateListBoxAction, this.cb, up);
                            }
                        }
                        else
                        {
                            UploadFile up = new UploadFile()
                            {
                                FileName = timepath + ".jpg", FileType = fileType, Status = UploadFile.FAIL, FilePath = img, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                            };
                            this.cb.Dispatcher.BeginInvoke(updateListBoxAction, this.cb, up);
                        }
                    }
                    else
                    {
                        UploadFile up = new UploadFile()
                        {
                            FileName = timepath + ".jpg", FileType = fileType, Status = UploadFile.FAIL, FilePath = img, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                        };
                        this.cb.Dispatcher.BeginInvoke(updateListBoxAction, this.cb, up);
                    }
                }
                else
                {
                    UploadFile up = new UploadFile()
                    {
                        FileName = timepath + ".jpg", FileType = fileType, Status = UploadFile.FAIL, FilePath = img, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                    };
                    this.cb.Dispatcher.BeginInvoke(updateListBoxAction, this.cb, up);
                }
            }
            GC.Collect();
        }
        public ActionResult GetEntity([FromQuery] string PlaceName, [FromQuery] int Id)
        {
            try
            {
                BaseTable row = _authenticationContext.BaseTable.Where(c => c.Name == PlaceName && c.CategoryId == Id).FirstOrDefault();
                if (row != null)
                {
                    Guid entityId = row.ID;

                    if (Id == 1)
                    {
                        AddTouristsEntryViewModel getTourists = new AddTouristsEntryViewModel();
                        _amenities  = _authenticationContext.TouristsAmenities.FirstOrDefault(data => data.Id == entityId);
                        getTourists = _mapper.Map <AddTouristsEntryViewModel>(_amenities);
                        _amenities  = getTourists;
                    }
                    else if (Id == 2)
                    {
                        AddActivitiesAmenitiesViewModel activities = new AddActivitiesAmenitiesViewModel();
                        _amenities = _authenticationContext.ActivitiesAmenities.FirstOrDefault(data => data.Id == entityId);
                        activities = _mapper.Map <AddActivitiesAmenitiesViewModel>(_amenities);
                        _amenities = activities;
                    }
                    else if (Id == 3)
                    {
                        AddFoodAmenitiesViewModel getFood = new AddFoodAmenitiesViewModel();
                        _amenities = _authenticationContext.FoodAmenities.FirstOrDefault(data => data.Id == entityId);
                        getFood    = _mapper.Map <AddFoodAmenitiesViewModel>(_amenities);
                        _amenities = getFood;
                    }
                    else
                    {
                        AddAccommodationAmenitiesViewModel getAccommodation = new AddAccommodationAmenitiesViewModel();
                        _amenities       = _authenticationContext.AccommodationAmenities.FirstOrDefault(data => data.Id == entityId);
                        getAccommodation = _mapper.Map <AddAccommodationAmenitiesViewModel>(_amenities);
                        _amenities       = getAccommodation;
                    }
                    var           images    = _authenticationContext.EnitityImages.Where(c => c.EntityID == entityId).Select(d => d.Image).ToList();
                    List <Object> imageList = new List <Object>();
                    if (images != null)
                    {
                        foreach (byte[] image in images)
                        {
                            FileResult data = File(image, "image/png", $"Image");
                            imageList.Add(data);
                            //var base64 = Convert.ToBase64Strin g(image, 0, image.Length);
                            //var imgsrc = string.Format("data: image/png ; base64{0},",base64);
                            //imageList.Add(imgsrc);
                        }
                    }
                    var Result = new Dictionary <string, Object>();
                    Result.Add("Details", row);
                    Result.Add("Images", imageList);
                    Result.Add("Amenities", _amenities);

                    return(Ok(Result));
                }
                else
                {
                    return(BadRequest(new { message = "No such entry in database" }));
                }
            }
            catch (Exception ex) {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Example #9
0
        public FileResult DeleteMediaFiles(Media media)
        {
            var fileResult = new FileResult
            {
                Action     = FileResult.FileAction.Delete,
                Files      = media.RelativePath,
                FolderName = StripInvalidCharacters(media.GetPhysicalName()),
                Status     = FileResult.ActionStatus.MediaNotFound
            };

            if (media.RelativePath?.Any() ?? false)
            {
                bool deleted = false;

                var mediaType = media.GetType();
                var mediaPath = Path.Combine(BuildMediaPath(mediaType.Name, fileResult.FolderName));

                try
                {
                    if (media is Movie)
                    {
                        deleted = DeleteFolder(mediaPath);
                    }
                    else
                    {
                        foreach (var mediaFile in media.RelativePath.Select(x => Path.Combine(mediaPath, x)))
                        {
                            if (File.Exists(mediaFile))
                            {
                                var filesInFolder = System.IO.Directory.GetFiles(mediaPath);
                                if (filesInFolder.Count(x => this.Config.MediaTypes.Contains(Path.GetExtension(x).Substring(1))) == 1)
                                {
                                    deleted = DeleteFolder(mediaPath);
                                }
                                else
                                {
                                    File.Delete(mediaFile);
                                    deleted = true;
                                }
                            }
                        }
                    }
                }
                catch (IOException ioEx)
                {
                    deleted           = false;
                    fileResult.Error  = ioEx.ToString();
                    fileResult.Status = FileResult.ActionStatus.Error;
                    return(fileResult);
                }

                if (deleted)
                {
                    fileResult.Status = FileResult.ActionStatus.OK;
                }
            }

            this.OnChange?.Invoke(fileResult, new List <Media> {
                media
            });
            return(fileResult);
        }
Example #10
0
 public Attachment(AttachmentType type, FileResult file)
 {
     Type = type;
     File = new FileData(file);
 }
Example #11
0
 private static void ExecuteFileResult(IContext context, FileResult result)
 {
     result.Execute(context);
 }
 void LoadFile(FileResult file)
 {
     FilePath = file.FullPath;
 }
Example #13
0
        protected virtual (RangeItemHeaderValue range, long rangeLength, bool serveBody) SetHeadersAndLog(
            ActionContext context,
            FileResult result,
            long?fileLength,
            bool enableRangeProcessing,
            DateTimeOffset?lastModified = null,
            EntityTagHeaderValue etag   = null)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            SetContentType(context, result);
            SetContentDispositionHeader(context, result);

            var request            = context.HttpContext.Request;
            var httpRequestHeaders = request.GetTypedHeaders();

            // Since the 'Last-Modified' and other similar http date headers are rounded down to whole seconds,
            // round down current file's last modified to whole seconds for correct comparison.
            if (lastModified.HasValue)
            {
                lastModified = RoundDownToWholeSeconds(lastModified.Value);
            }

            var preconditionState = GetPreconditionState(httpRequestHeaders, lastModified, etag);

            var response = context.HttpContext.Response;

            SetLastModifiedAndEtagHeaders(response, lastModified, etag);

            // Short circuit if the preconditional headers process to 304 (NotModified) or 412 (PreconditionFailed)
            if (preconditionState == PreconditionState.NotModified)
            {
                response.StatusCode = StatusCodes.Status304NotModified;
                return(range : null, rangeLength : 0, serveBody : false);
            }
            else if (preconditionState == PreconditionState.PreconditionFailed)
            {
                response.StatusCode = StatusCodes.Status412PreconditionFailed;
                return(range : null, rangeLength : 0, serveBody : false);
            }

            if (fileLength.HasValue)
            {
                // Assuming the request is not a range request, and the response body is not empty, the Content-Length header is set to
                // the length of the entire file.
                // If the request is a valid range request, this header is overwritten with the length of the range as part of the
                // range processing (see method SetContentLength).

                response.ContentLength = fileLength.Value;

                // Handle range request
                if (enableRangeProcessing)
                {
                    SetAcceptRangeHeader(response);

                    // If the request method is HEAD or GET, PreconditionState is Unspecified or ShouldProcess, and IfRange header is valid,
                    // range should be processed and Range headers should be set
                    if ((HttpMethods.IsHead(request.Method) || HttpMethods.IsGet(request.Method)) &&
                        (preconditionState == PreconditionState.Unspecified || preconditionState == PreconditionState.ShouldProcess) &&
                        (IfRangeValid(httpRequestHeaders, lastModified, etag)))
                    {
                        return(SetRangeHeaders(context, httpRequestHeaders, fileLength.Value));
                    }
                }
                else
                {
                    Logger.NotEnabledForRangeProcessing();
                }
            }

            return(range : null, rangeLength : 0, serveBody : !HttpMethods.IsHead(request.Method));
        }
Example #14
0
        /// <summary>
        /// Open platform specific FilePicker and allow user to pick audio file of supported type.
        /// </summary>
        /// <param name="writeResult">Action accepting result of Upload process described in string.</param>
        /// <returns>True if picked song was sucessfuly uploaded, false otherwise.</returns>
        public async Task <bool> UploadRecording(Action <string> writeResult, ulong maxSize_MB)
        {
            #region UWP
#if NETFX_CORE
            // Setup FilePicker
            var picker = new Windows.Storage.Pickers.FileOpenPicker();
            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
            picker.FileTypeFilter.Add(".wav");

            // Open FilePicker
            StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                writeResult("No song uploaded.");
                return(false);
            }

            // Check size of uploaded file
            var fileProperties = await file.GetBasicPropertiesAsync();

            if (fileProperties.Size > maxSize_MB * 1024 * 1024)
            {
                writeResult($"Selected file is too big." + Environment.NewLine + $"Maximum allowed size is {maxSize_MB} MB.");
                return(false);
            }
            else
            {
                buffer = await file.OpenAsync(FileAccessMode.ReadWrite);

                writeResult(file.Name);
                return(true);
            }
#endif
            #endregion

            #region ANDROID
#if __ANDROID__
            if (await Utils.Permissions.Droid.GetExternalStoragePermission())
            {
                // Setup FilePicker
                PickOptions options = new PickOptions
                {
                    PickerTitle = "Please select a wav song file",
                    FileTypes   = new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
                    {
                        { DevicePlatform.Android, new[] { "audio/x-wav", "audio/wav" } }
                    })
                };

                // Open FilePicker
                FileResult result = await FilePicker.PickAsync(options);

                // Process picked file
                if (result != null)
                {
                    var audioFileData = await result.OpenReadAsync();

                    if ((ulong)audioFileData.Length > maxSize_MB * 1024 * 1024)
                    {
                        writeResult($"File is too large." + Environment.NewLine + $"Maximum allowed size is {maxSize_MB} MB.");
                        return(false);
                    }

                    buffer = new byte[(int)audioFileData.Length];
                    audioFileData.Read(buffer, 0, (int)audioFileData.Length);
                    writeResult(result.FileName);

                    return(true);
                }
                // No file picked
                else
                {
                    writeResult("No song uploaded");
                    return(false);
                }
            }
            // External Sotrage Permission not granted
            else
            {
                writeResult("Acces to read storage denied.");
                return(false);
            }
#endif
            #endregion
            // Fallback value for unsupported platforms
            return(false);
        }
Example #15
0
        }         // Index

        public ActionResult DownloadMessagesDocument(string id, bool download = false)
        {
            Guid       guid;
            FileResult fs = null;
            string     fileName;

            if (Guid.TryParse(id, out guid))
            {
                var askville     = _askvilleRepository.GetAskvilleByGuid(id);
                var askvilleData = ConvertFormat(string.IsNullOrEmpty(askville.MessageBody) ? "" : askville.MessageBody, SaveFormat.Pdf, "text");

                fs       = File(askvilleData, "application/pdf");
                fileName = string.Format("Askville({0}).pdf", FormattingUtils.FormatDateTimeToStringWithoutSpaces(askville.CreationDate));
            }
            else
            {
                var f = _exportResultRepository.Get(Convert.ToInt32(id));
                if (f == null)
                {
                    throw new Exception(String.Format("File id={0} not found", id));
                }
                fileName = f.FileName.Replace(",", "").Replace("£", "");
                if (f.FileType == 1)
                {
                    fs = File(f.BinaryBody, "application/pdf");
                }
                else
                {
                    if (f.FileName.EndsWith("html"))
                    {
                        fs = File(f.BinaryBody, "text/html");
                    }
                    else
                    {
                        if (download)
                        {
                            fs = File(f.BinaryBody, "application/msoffice");
                        }
                        else
                        {
                            var pdfDocument = AgreementRenderer.ConvertToPdf(f.BinaryBody, LoadFormat.Docx);
                            fs = File(pdfDocument, "application/pdf");
                            fileName.Replace("docx", "pdf");
                        }
                    }
                }
            }

            if (download)
            {
                fs.FileDownloadName = fileName;
            }
            else
            {
                var cd = new System.Net.Mime.ContentDisposition {
                    FileName = fileName,
                    Inline   = true,
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());
            }
            return(fs);
        }
Example #16
0
        private void UploadButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String token = CacheService.Instance.GetStuToken();

                FileResult fr = rf.UploadFile(openFileDialog.FileName, token);

                //获取文件名字
                String file_name = openFileDialog.FileName.Split('\\')[openFileDialog.FileName.Split('\\').Length - 1];

                if (fr != null)
                {
                    if (fr.code == "200")
                    {
                        //关联文件与记录
                        List <Attach> attaches = new List <Attach>();
                        foreach (Student s in CacheService.Instance.GetStudentList())
                        {
                            Attach a = new Attach {
                                subjectId = s.RecordId, ownerId = s.Id, type = "EXPERIMENT_RECORD_FILE"
                            };
                            attaches.Add(a);
                        }

                        AttachResult ar = rf.AttachRecordWithFile(CacheService.Instance.ExperimentId, fr.data.id, attaches, CacheService.Instance.GetStuToken());

                        if (ar != null)
                        {
                            if (ar.code == "200")
                            {
                                UploadFile up = new UploadFile()
                                {
                                    FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.SUCCESS, FilePath = openFileDialog.FileName, Id = fr.data.id, Color = "#FF979797", Operation = UploadFile.OPENDOC
                                };
                                upfiles.Add(up);
                                fileList.Items.Refresh();
                            }
                            else
                            {
                                LSMessageBox.Show("关联文件错误", ar.message);
                                UploadFile up = new UploadFile()
                                {
                                    FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                                };
                                upfiles.Add(up);
                                fileList.Items.Refresh();
                            }
                        }
                        else
                        {
                            LSMessageBox.Show("网络错误", "网络异常");
                            UploadFile up = new UploadFile()
                            {
                                FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                            };
                            upfiles.Add(up);
                            fileList.Items.Refresh();
                        }
                    }
                    else
                    {
                        LSMessageBox.Show("上传文件错误", fr.message);
                        UploadFile up = new UploadFile()
                        {
                            FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                        };
                        upfiles.Add(up);
                        fileList.Items.Refresh();
                    }
                }
                else
                {
                    LSMessageBox.Show("网络错误", "网络异常");
                    UploadFile up = new UploadFile()
                    {
                        FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                    };
                    upfiles.Add(up);
                    fileList.Items.Refresh();
                }
            }
        }
Example #17
0
        private void OpenLabel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label label = sender as Label;

            UploadFile uploadFile = null;

            foreach (UploadFile uf in this.upfiles)
            {
                if (uf.FilePath.Equals(label.Tag.ToString()))
                {
                    uploadFile = uf;
                }
            }
            if (uploadFile != null)
            {
                if (label.Content.Equals(UploadFile.OPENDOC))
                {
                    String doc = uploadFile.FilePath.Substring(0, uploadFile.FilePath.Length - uploadFile.FilePath.Split('\\')[uploadFile.FilePath.Split('\\').Length - 1].Length);
                    System.Diagnostics.Process.Start("explorer.exe ", doc);
                }
                else if (label.Content.Equals(UploadFile.REUPLOAD))
                {
                    String token = CacheService.Instance.GetStuToken();

                    FileResult fr = rf.UploadFile(uploadFile.FilePath, token);

                    //获取文件名字
                    String file_name = uploadFile.FilePath.Split('\\')[uploadFile.FilePath.Split('\\').Length - 1];

                    if (fr != null)
                    {
                        if (fr.code == "200")
                        {
                            //关联文件与记录
                            List <Attach> attaches = new List <Attach>();
                            foreach (Student s in CacheService.Instance.GetStudentList())
                            {
                                Attach a = new Attach {
                                    subjectId = s.RecordId, ownerId = s.Id, type = "EXPERIMENT_RECORD_FILE"
                                };
                                attaches.Add(a);
                            }

                            AttachResult ar = rf.AttachRecordWithFile(CacheService.Instance.ExperimentId, fr.data.id, attaches, CacheService.Instance.GetStuToken());

                            if (ar != null)
                            {
                                if (ar.code == "200")
                                {
                                    uploadFile.Status    = UploadFile.SUCCESS;
                                    uploadFile.Color     = "#FF979797";
                                    uploadFile.Operation = UploadFile.OPENDOC;
                                    fileList.Items.Refresh();
                                }
                                else
                                {
                                    LSMessageBox.Show("关联文件错误", ar.message);
                                    uploadFile.Status    = UploadFile.FAIL;
                                    uploadFile.Color     = "Red";
                                    uploadFile.Operation = UploadFile.REUPLOAD;
                                    fileList.Items.Refresh();
                                }
                            }
                            else
                            {
                                LSMessageBox.Show("网络错误", "网络异常");
                                uploadFile.Status    = UploadFile.FAIL;
                                uploadFile.Color     = "Red";
                                uploadFile.Operation = UploadFile.REUPLOAD;
                                fileList.Items.Refresh();
                            }
                        }
                        else
                        {
                            LSMessageBox.Show("上传文件错误", fr.message);
                            uploadFile.Status    = UploadFile.FAIL;
                            uploadFile.Color     = "Red";
                            uploadFile.Operation = UploadFile.REUPLOAD;
                            fileList.Items.Refresh();
                        }
                    }
                    else
                    {
                        LSMessageBox.Show("网络错误", "网络异常");
                        uploadFile.Status    = UploadFile.FAIL;
                        uploadFile.Color     = "Red";
                        uploadFile.Operation = UploadFile.REUPLOAD;
                        fileList.Items.Refresh();
                    }
                }
            }
        }
Example #18
0
        private StackLayout AddNewLineForm()
        {
            FileResult photo     = null;
            string     PhotoPath = null;


            #region Define elements
            DatePicker dateEntry = new DatePicker
            {
                Date = DateTime.Now
            };

            TimePicker timeEntry = new TimePicker
            {
                Time = DateTime.Now.TimeOfDay,
                HorizontalOptions = LayoutOptions.End
            };
            Picker currencyPicker = new Picker
            {
                ItemsSource = new List <string>()
                {
                    "£", "€", "$"
                },
                SelectedIndex           = 0,
                HorizontalTextAlignment = TextAlignment.Start,
                FontAttributes          = FontAttributes.Bold,
            };
            Entry amountEntry = new Entry
            {
                Keyboard = Keyboard.Numeric
            };
            Entry descEntry = new Entry
            {
                Placeholder = "e.g. Lunch at services"
            };

            Label recieptButton = new Label
            {
                Text     = FontAwesomeIcons.FontAwesomeIcons.Camera,
                FontSize = 20,
                HorizontalTextAlignment = TextAlignment.Center,
                VerticalTextAlignment   = TextAlignment.Center,
                TextColor  = Color.WhiteSmoke,
                FontFamily = "fa.otf#fa"
            };



            TapGestureRecognizer tap = new TapGestureRecognizer();
            tap.Tapped += async(s, e) =>
            {
                photo = await MediaPicker.CapturePhotoAsync();

                if (photo != null)
                {
                    dateEntry.IsEnabled = false;

                    photo_attempted = true;
                    var newFile = Path.Combine(FileSystem.CacheDirectory, dateEntry.Date.ToString("ddMMM_") + get_count() + ".jpg");
                    using (var stream = await photo.OpenReadAsync())
                        using (var newStream = File.OpenWrite(newFile))
                            await stream.CopyToAsync(newStream);
                    PhotoPath = newFile;
                }
                else
                {
                    DisplayAlert("Error", "No photo taken, please try again.", "Ok");
                }
            };

            recieptButton.GestureRecognizers.Add(tap);
            #endregion

            #region Enter Button
            Label enterButton = new Label
            {
                Text     = "Add",
                FontSize = 30,
                VerticalTextAlignment   = TextAlignment.Center,
                HorizontalTextAlignment = TextAlignment.Center,
                TextColor      = Color.WhiteSmoke,
                FontAttributes = FontAttributes.Bold
            };

            TapGestureRecognizer tap1 = new TapGestureRecognizer();
            tap1.Tapped += async(s, e) =>
            {
                if (just_tapped == true)
                {
                    await Task.Delay(1000);

                    just_tapped = false;
                }
                else
                {
                    just_tapped = true;
                    TapSuccess();
                }

                void TapSuccess()
                {
                    if (amountEntry.Text == null)
                    {
                        DisplayAlert("Error", "You must enter a reciept amount in " + currencyPicker.SelectedItem + ".", "OK");
                    }
                    else
                    {
                        PopupNavigation.PopAsync();
                        if (photo_attempted == true && PhotoPath == null)
                        {
                            DisplayAlert("Warning!", "Input failed!", "OK"); photo_attempted = false;
                        }                                                                                                                               // Catches empty photo file if stream is laggy.
                        else
                        {
                            photo_attempted = false;

                            decimal dcml        = Convert.ToDecimal(amountEntry.Text);
                            MyItem  newLineList = new MyItem()
                            {
                                Time    = timeEntry.Time.Hours.ToString() + ":" + timeEntry.Time.Minutes.ToString(),
                                Amount  = new KeyValuePair <string, decimal>(currencyPicker.SelectedItem.ToString(), dcml),
                                Reciept = PhotoPath,
                                Desc    = descEntry.Text,
                                Line    = get_count()
                            };

                            if (App.SavedLines[DeploymentName].ContainsKey(dateEntry.Date))
                            {
                                App.SavedLines[DeploymentName][dateEntry.Date].Add(newLineList);
                                App.UpdateCache();
                            }
                            else
                            {
                                App.SavedLines[DeploymentName].Add(dateEntry.Date, new List <MyItem>()
                                {
                                    newLineList
                                });
                                App.UpdateCache();
                            }

                            Content = drawLayout();

                            Application.Current.Properties["DataCache"] = JsonConvert.SerializeObject(App.SavedLines);
                        }
                    }
                }
            };

            enterButton.GestureRecognizers.Add(tap1);
            #endregion

            #region Draw Grid Layout

            Grid grid = new Grid();

            grid.Children.Add(MakeLabel("DTG", 20), 0, 1, 0, 1);
            grid.Children.Add(dateEntry, 1, 3, 0, 1);
            grid.Children.Add(timeEntry, 2, 3, 0, 1);

            grid.Children.Add(MakeLabel("Reciept", 20), 0, 1, 1, 2);
            Grid recieptGrid = new Grid();
            recieptGrid.Children.Add(currencyPicker, 0, 1, 0, 1);
            recieptGrid.Children.Add(amountEntry, 1, 5, 0, 1);
            recieptGrid.Children.Add(recieptButton, 5, 6, 0, 1);
            grid.Children.Add(recieptGrid, 1, 3, 1, 2);

            grid.Children.Add(MakeLabel("Remarks", 20), 0, 1, 2, 3);
            grid.Children.Add(descEntry, 1, 3, 2, 3);

            grid.Children.Add(new Frame
            {
                Content         = enterButton,
                CornerRadius    = 10,
                Padding         = 0,
                Margin          = 0,
                BackgroundColor = Color.LimeGreen
            }, 0, 3, 3, 4);
            #endregion

            #region Counter
            int get_count()
            {
                int i;

                if (App.SavedLines[DeploymentName].ContainsKey(dateEntry.Date))
                {
                    i = App.SavedLines[DeploymentName][dateEntry.Date].Count() + 1;
                }
                else
                {
                    i = 1;
                }

                return(i);
            }

            #endregion

            return(new StackLayout
            {
                Padding = 10,
                Children =
                {
                    MakeLabel("Add new expenses line", 25),
                    new BoxView {
                        Color = Color.WhiteSmoke,      HeightRequest = 1
                    },
                    grid
                },
                BackgroundColor = App.GetRandomColour()
            });
        }
        private void SetContentType(ActionContext context, FileResult result)
        {
            var response = context.HttpContext.Response;

            response.ContentType = result.ContentType.ToString();
        }
 private void DeleteImageButton_Clicked(object sender, EventArgs args)
 {
     ImageInfoStack.IsVisible = false;
     photo = null;
 }
        public NonNumericCharacters()
        {
            var parser = new StreetSpecificationParser();

            _fileResult = parser.ParseStreetSpecification("..\\..\\SpecificationExamples\\NonNumericCharacters.txt");
        }
Example #22
0
        private static void SetContentType(ActionContext context, FileResult result)
        {
            var response = context.HttpContext.Response;

            response.ContentType = result.ContentType;
        }
Example #23
0
        /// <summary>
        /// Reads a picture and returns the data obtained from it into a dictionary with key-value pairs.
        /// For this specifically, items in a picture are connected (ie. fruit : apple), except its for
        /// (judgement, values) in the game. This will return the appropriate pairing. Until I rework this
        /// to be able to grab both the judgement and its value into one var.
        /// </summary>
        /// <param name="photo">photo file to be analyzed</param>
        /// <param name="tupleList">list containing what to search for in the image</param>
        /// <returns>A dictionary containing values sought out by the keys in ProcessorOptions</returns>
        public async Task <IDictionary <string, string> > ProcessPictureInfoAsync(FileResult photo, IEnumerable <ProcessorOptions> tupleList)
        {
            try
            {
                DetectTextRequest req = new DetectTextRequest
                {
                    Image = new Image()
                };

                // Grab image bytes
                using (var memoryStream = new MemoryStream())
                {
                    var stream = await photo.OpenReadAsync();

                    stream.CopyTo(memoryStream);
                    req.Image.Bytes = memoryStream;
                }

                DetectTextResponse res = await arClient.DetectTextAsync(req);

                foreach (TextDetection text in res.TextDetections)
                {
                    if (text.Confidence < confidenceThreshold) // Yeet the words its not confident in
                    {
                        continue;
                    }

                    // REGEX MATCHING TIME (Consider having 2 lists: not found and already found regexes, so it doesn't repeat over)
                    using (var iteratorTuple = tupleList.GetEnumerator())
                    {
                        while (iteratorTuple.MoveNext())
                        {
                            ProcessorOptions curr = iteratorTuple.Current;

                            // Fix this so I can iterate through while editing the Found part of ProcessorOptions T-T

                            Match match = curr.Rgx.Match(text.DetectedText);

                            if (match.Success)
                            {
                                if (!HashMap.ContainsKey(curr.Key))
                                {
                                    HashMap.Add(curr.Key, match.Groups[1].Value);
                                    Debug.WriteLine($"{curr.Key} IS NOW SET TO: {HashMap[curr.Key]}"); // Debug Statement
                                    curr.Found = true;                                                 // This does not work because this enumerator is read-only
                                }

                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Could not process picture into a song.\n");
                Debug.WriteLine(e.Message);
            }

            return(HashMap); // return this as a read only dictionary
        }
Example #24
0
 private bool IsUserCanceledOperation(FileResult fileResult)
 {
     return(fileResult == null);
 }
Example #25
0
        private MobileDataBase.Result UploadFile(MobileDataBase.Result rslt, string DocumentName, string DocumentType, string OrgReqId, string OrgId, bool ImportLicenseDoc, string LicenseNumber, string IssuanceDate, string ExpiryDate, string LicenseType)
        {
            MobileDataBase m  = new MobileDataBase();
            string         ID = m.GetNewIntKey("ScanRequestUploadDocs");

            string sPath        = "";
            string UploadedFrom = Convert.ToString(System.Web.HttpContext.Current.Request.Form["UploadedFrom"]);

            string ShareFolderPath1 = Path.Combine(UploadedFrom, DateTime.Now.Year + "\\" + DateTime.Now.Month.ToString("00") + "\\" + DateTime.Now.Day.ToString("00") + '\\' + OrgReqId + '\\' + ID);// System.Web.Hosting.HostingEnvironment.MapPath("~/locker/");


            sPath = Path.Combine(UploadedFrom, DateTime.Now.Year + "\\" + DateTime.Now.Month.ToString("00") + "\\" + DateTime.Now.Day.ToString("00") + '\\' + OrgReqId + '\\' + ID); // System.Web.Hosting.HostingEnvironment.MapPath("~/locker/");
                                                                                                                                                                                     //  sPath = Path.Combine("Etrade\\" + UploadedFrom, DateTime.Now.Year + "\\" + DateTime.Now.Month.ToString("00") + "\\" + DateTime.Now.Day.ToString("00") + '\\' + OrgReqId + '\\' + ID);// System.Web.Hosting.HostingEnvironment.MapPath("~/locker/");


            //   string ShareFolderPath1 = UploadedFrom + "\\" + year + "\\" + month + "\\" + day + "\\" + sProfileReferenceId;// +DeclarationId;



            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            FileResult Frdata = new FileResult();

            Frdata.DocumentName = DocumentName;
            Frdata.DocumentType = DocumentType;
            Frdata.OrgReqId     = OrgReqId;
            Frdata.UploadedFrom = Convert.ToString(System.Web.HttpContext.Current.Request.Form["UploadedFrom"]);
            //  Frdata.NewFileName = DocumentName;
            Frdata.FilePath   = DateTime.Now.Year + "\\" + DateTime.Now.Month.ToString("00") + "\\" + DateTime.Now.Day.ToString("00") + '\\' + OrgReqId;
            Frdata.IsUploaded = 'n';

            if (System.Web.HttpContext.Current.Request.Form["eservicerequestid"] != null)
            {
                Frdata.EserviceRequestId = Convert.ToString(System.Web.HttpContext.Current.Request.Form["eservicerequestid"]);

                if (!Convert.ToString(System.Web.HttpContext.Current.Request.Form["eservicerequestid"]).All(char.IsDigit))
                {
                    Frdata.EserviceRequestId = CommonFunctions.CsUploadDecrypt(Convert.ToString(System.Web.HttpContext.Current.Request.Form["eservicerequestid"]).ToString());
                }
            }
            // CHECK THE FILE COUNT.
            FileInfo F = null;

            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    try
                    {
                        int    iLen  = hpf.ContentLength;
                        byte[] btArr = new byte[iLen];
                        hpf.InputStream.Read(btArr, 0, iLen);

                        var memoryStream = new MemoryStream(btArr);

                        Boolean isValidFile = false;

                        if (hpf.ContentType.Contains("image"))
                        {
                            isValidFile = IsImage(memoryStream);
                        }

                        else if (hpf.ContentType.Contains("application/pdf"))
                        {
                            isValidFile = IsPDF(memoryStream);
                        }


                        if (isValidFile)
                        {
                            if (!Directory.Exists(Path.Combine(ServerUploadFolder, ShareFolderPath1)))
                            {
                                Directory.CreateDirectory(Path.Combine(ServerUploadFolder, ShareFolderPath1));
                            }
                            // sPath = ShareFolderPath1 + "\\" + FullfileName;
                            // file.SaveAs(Path.Combine(ServerUploadFolder, sPath));



                            // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                            //   if (!File.Exists(Path.Combine(sPath, Path.GetFileName(hpf.FileName))) && Regex.IsMatch(hpf.FileName.Trim(), "(\\.(jpg|jpeg|pdf))$", RegexOptions.IgnoreCase))
                            {
                                // SAVE THE FILES IN THE FOLDER.
                                string NewfileName;
                                string extension = Path.GetExtension(hpf.FileName);
                                if (UploadedFrom == "OrganizationRequests")
                                {
                                    NewfileName = DocumentName;//+ extension;
                                }
                                else
                                {
                                    NewfileName = DocumentName + extension;
                                }
                                NewfileName        = NewfileName.Replace('/', '-');
                                Frdata.NewFileName = NewfileName;
                                //   hpf.SaveAs(Path.Combine(sPath, Path.GetFileName(hpf.FileName)));
                                hpf.SaveAs(Path.Combine(ServerUploadFolder, sPath, NewfileName));

                                Frdata.Name     = Path.Combine(sPath, NewfileName);
                                Frdata.FilePath = Path.Combine(sPath, NewfileName);
                                //    F = new FileInfo(Path.Combine(sPath, Path.GetFileName(hpf.FileName)));
                                F = new FileInfo(Path.Combine(ServerUploadFolder, sPath, NewfileName));

                                Frdata.FileSize   = (F.Length / 1024).ToString("0.00");
                                Frdata.IsUploaded = 'y';
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        using (System.IO.StreamWriter file =
                                   new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath("~/logEmail.txt"), true))
                        {
                            file.WriteLine(ex.ToString());
                            file.Close();
                        }
                    }
                }
            }
            if (Frdata.IsUploaded == 'y')
            {
                rslt.Data = MobileDataBase.UpdateUploadDataDS(rslt.mUserId, Frdata, OrgId, ImportLicenseDoc, LicenseNumber, IssuanceDate, ExpiryDate, LicenseType);
                //  if (F != null)
                // {
                //     F.Rename(Frdata.NewFileName);
                //}
            }
            return(rslt);
        }
Example #26
0
        public async void Show(Page page, string imageFile = null)
        {
            if (imageFile == null)
            {
                FileResult file    = null;
                string     newFile = null;

                string action = await page.DisplayActionSheet(SelectSourceTitle, CancelButtonTitle, null, TakePhotoTitle, PhotoLibraryTitle);

                try
                {
                    if (action == TakePhotoTitle)
                    {
                        file = await MediaPicker.CapturePhotoAsync(MediaPickerOptions);
                    }
                    else if (action == PhotoLibraryTitle)
                    {
                        file = await MediaPicker.PickPhotoAsync(MediaPickerOptions);
                    }
                    else
                    {
                        Faiure?.Invoke();
                        return;
                    }

                    //Si se capturo correctamente
                    if (file != null)
                    {
                        // save the file into local storage
                        newFile = Path.Combine(FileSystem.CacheDirectory, file.FileName);
                        //Copiarlo llevaba mucho trabajo

                        /*
                         * using (var stream = await file.OpenReadAsync())
                         * using (var newStream = File.OpenWrite(newFile)) {
                         *  await stream.CopyToAsync(newStream);
                         *  stream.Close();
                         *  newStream.Close();
                         * }
                         */
                        //Mover a cache local
                        if (File.Exists(newFile))
                        {
                            File.Delete(newFile);
                        }
                        File.Move(file.FullPath, newFile);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
                }

                if (file == null || newFile == null)
                {
                    Faiure?.Invoke();
                    return;
                }
                if (Device.RuntimePlatform == Device.Android)
                {
                    //Delay for fix Xamarin.Essentials.Platform.CurrentActivity no MediaPicker
                    await Task.Delay(TimeSpan.FromMilliseconds(2000));
                }
                imageFile = newFile;
            }

            // small delay
            await Task.Delay(TimeSpan.FromMilliseconds(100));

            DependencyService.Get <IImageCropperWrapper>().ShowFromFile(this, imageFile);
        }
 protected void SetHeadersAndLog(ActionContext context, FileResult result)
 {
     SetContentType(context, result);
     SetContentDispositionHeader(context, result);
     Logger.FileResultExecuting(result.FileDownloadName);
 }
        /// <summary>
        /// Initializes this file database manifest
        /// </summary>
        private static FileDatabaseManifest GetOrCreateFileDatabaseManifest(
            BackblazeB2AuthorizationSession authorizationSession,
            Config config
            )
        {
            if (SharedFileDatabaseManifest == null)
            {
                lock (SharedFileDatabaseManifestLock)
                {
                    if (SharedFileDatabaseManifest == null)
                    {
                        // Get just the file names on the server
                        ListFilesAction listFilesAction = ListFilesAction.CreateListFileActionForFileNames(
                            authorizationSession,
                            config.BucketID,
                            true
                            );
                        BackblazeB2ActionResult <BackblazeB2ListFilesResult> listFilesActionResult = listFilesAction.Execute();
                        if (listFilesActionResult.HasErrors)
                        {
                            throw new FailedToGetListOfFilesOnB2Exception
                                  {
                                      BackblazeErrorDetails = listFilesActionResult.Errors,
                                  };
                        }
                        FileResult fileDatabaseManifestFileResult = listFilesActionResult.Result.Files
                                                                    .Where(f => f.FileName.Equals(RemoteFileDatabaseManifestName, StringComparison.Ordinal))
                                                                    .SingleOrDefault();
                        if (fileDatabaseManifestFileResult == null)
                        {
                            SharedFileDatabaseManifest = new FileDatabaseManifest
                            {
                                DataFormatVersionNumber = CurrentDatabaseDataFormatVersion,
                                Files = new Database.File[0]
                            };
                        }
                        else
                        {
                            using (MemoryStream outputStream = new MemoryStream())
                                using (DownloadFileAction manifestFileDownloadAction = new DownloadFileAction(
                                           authorizationSession,
                                           outputStream,
                                           fileDatabaseManifestFileResult.FileID
                                           ))
                                {
                                    BackblazeB2ActionResult <BackblazeB2DownloadFileResult> manifestResultOption =
                                        manifestFileDownloadAction.Execute();
                                    if (manifestResultOption.HasResult)
                                    {
                                        // Now, read string from manifest
                                        outputStream.Flush();
                                        SharedFileDatabaseManifest = DeserializeManifest(
                                            outputStream.ToArray(),
                                            config
                                            );
                                    }
                                    else
                                    {
                                        SharedFileDatabaseManifest = new FileDatabaseManifest
                                        {
                                            DataFormatVersionNumber = CurrentDatabaseDataFormatVersion,
                                            Files = new Database.File[0]
                                        };
                                    }
                                }
                        }
                    }
                }
            }

            return(SharedFileDatabaseManifest);
        }
Example #29
0
 internal SampleBinaryFile(string filename, byte[] fileAsBytes, FileResult fileResult = FileResult.Success)
 {
     Path = filename;
       Bytes = fileAsBytes;
       Result = fileResult;
 }
Example #30
0
        private FileResult HandleFileDelivery(IDownloadInfo downloadInfo, List <Media> relatedMedia)
        {
            var physicalName = StripInvalidCharacters(GetPhysicalName(relatedMedia));

            var type      = GetMediaType(relatedMedia);
            var mediaPath = BuildMediaPath(type.Name, physicalName);

            var filesMoved      = new List <(string OldPath, string NewPath, long Size)>();
            var fileTypesToMove = this.Config.MediaTypes.Concat(this.Config.IncludeSubs ? new List <string> {
                "sub"
            } : new List <string>()).ToArray();

            try
            {
                if (!Directory.Exists(mediaPath))
                {
                    Directory.CreateDirectory(mediaPath);
                }

                foreach (var file in downloadInfo.Files.Where(x => fileTypesToMove.Contains(Path.GetExtension(x).Substring(1))))
                {
                    if (!File.Exists(file))
                    {
                        continue;
                    }

                    var newPath = Path.Combine(mediaPath, Path.GetFileName(file));
                    var size    = new FileInfo(file).Length;
                    for (int i = 1; i <= 4; i++)
                    {
                        try
                        {
                            File.Move(file, newPath);
                            filesMoved.Add((file, newPath, size));
                            break;
                        }
                        catch (IOException e) when((e.HResult & 0x0000FFFF) == 32 && i <= 3)  // ERROR_SHARING_VIOLATION
                        {
                            System.Threading.Tasks.Task.Delay(5000 * i).Wait();
                        }
                        catch (IOException e) when((e.HResult & 0x0000FFFF) == 183 && i <= 3) // ERROR_ALREADY_EXISTS
                        {
                            if (File.Exists(file) && File.Exists(newPath) && new FileInfo(file).Length > new FileInfo(newPath).Length)
                            {
                                File.Delete(newPath);
                                System.Threading.Tasks.Task.Delay(5000).Wait();
                                continue;
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                foreach (var revert in filesMoved)
                {
                    File.Move(revert.NewPath, revert.OldPath);
                }

                if (ex is IOException ioEx && ((ioEx.HResult & 0x0000FFFF) == 32))
                {
                    return(new FileResult {
                        Status = FileResult.ActionStatus.TransientError, Error = ioEx.ToString(), FolderName = physicalName
                    });
                }

                return(new FileResult {
                    Status = FileResult.ActionStatus.Error, Error = ex.ToString(), FolderName = physicalName
                });
            }

            var delivery = new FileResult
            {
                Action     = FileResult.FileAction.Deliver,
                Status     = filesMoved.Any(x => Path.GetExtension(x.NewPath) != ".sub") ? FileResult.ActionStatus.OK : FileResult.ActionStatus.MediaNotFound,
                Files      = filesMoved.OrderByDescending(x => x.Size).Select(x => Path.GetRelativePath(mediaPath, x.NewPath)).ToArray(),
                FolderName = physicalName
            };

            return(delivery);
        }
Example #31
0
        public IHttpActionResult UploadFile([FromUri] SystemFilesView model)
        {
            var result = new FileResult();

            try
            {
                SystemFiles systemFiles = new SystemFiles();

                var FolderName = ConfigurationManager.AppSettings[model.ProjectName];

                if (FolderName == null)
                {
                    FolderName = model.ProjectName;
                }

                var day        = DateTime.Now.ToString("yyyyMMdd");
                var folder     = FolderName + "/" + day;
                var filePath   = AppConfig.FileUploadRootDirectory + "/" + folder;
                var dataLength = 0L;

                if (Directory.Exists(filePath) == false)// 如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(filePath);
                }
                string longName     = Guid.NewGuid().ToString();
                string SaveFileName = longName + model.FileExtension; // 保存文件名称

                using (var destinationStream = File.Create(filePath + "/" + SaveFileName))
                    using (var sourceStream = Request.Content.ReadAsStreamAsync().Result)
                    {
                        // TODO:添加一个BufferStream缓冲,减少I/O压力
                        sourceStream.CopyTo(destinationStream);

                        dataLength = sourceStream.Length;
                    }

                var tobeArchiveDateTime = (model.ArchivePeriod == EnumArchivePeriod.Never || IsImage(model)) ? DateTime.MaxValue : DateTime.Now.AddDays((int)model.ArchivePeriod);

                systemFiles = new SystemFiles()
                {
                    FileId              = Guid.NewGuid(),
                    FileData            = null,
                    FilePath            = folder + "/" + SaveFileName,
                    FileExtension       = model.FileExtension,
                    FileName            = model.FileName,
                    FileLongName        = SaveFileName,
                    FileSize            = (int)dataLength,
                    ProjectName         = model.ProjectName,
                    CreateDate          = DateTime.Now,
                    FileCompressStatus  = EnumFileCompressStatus.Uncompressed,
                    TobeArchiveDateTime = tobeArchiveDateTime
                };

                using (FileCenterDbContext dbContext = new FileCenterDbContext())
                {
                    dbContext.SystemFiles.Add(systemFiles);
                    dbContext.SaveChanges();
                }

                result.Status  = AppConfig.ReturnResult.Status_Success;
                result.Message = AppConfig.ReturnResult.Message_Success;
                result.Result  = JsonConvert.SerializeObject(systemFiles);

                return(Json(result));
            }
            catch (Exception ex)
            {
                result.Status  = AppConfig.ReturnResult.Status_Failure;
                result.Message = ex.Message;

                return(Json(result));
            }
        }
        private IEnumerable<FileResult> SearchDirectory(string directoryPath, string[] directoryFilters, string[] fileFilters, string extensionSearch, string search, string projectName)
        {
            var allDirectoryFiles = new List<FileResult>();
            var allFiles = new List<FileResult>();
            var synchLock = new Object();

            string[] directories;

            try
            {
                directories = Directory.GetDirectories(
                    directoryPath);
            }
            catch (DirectoryNotFoundException ex)
            {
                // just ignore the invalid directory
                directories = new string[0];
            }

            var project = GetProjectName(directoryPath);
            projectName = !String.IsNullOrEmpty(project) ? project : projectName;

            var filteredDirectories = directories.Where(d => directoryFilters.All(df => String.Compare(df, GetDirectoryName(d), StringComparison.InvariantCultureIgnoreCase) != 0)).ToArray();

            Parallel.ForEach(filteredDirectories, () => new List<FileResult>(),
                (directory, state, list) =>
                {
                    var result = SearchDirectory(directory, directoryFilters, fileFilters, extensionSearch, search, projectName);
                    foreach (var file in result)
                    {
                        list.Add(file);
                    }

                    return list;
                },
                list =>
                {
                    lock (synchLock)
                    {
                        allDirectoryFiles.AddRange(list.ToArray());
                    }
                });

            foreach (var file in allDirectoryFiles)
            {
                yield return file;
            }

            string[] files;

            try
            {
                files = Directory.GetFiles(
                    directoryPath);
            }
            catch (DirectoryNotFoundException ex)
            {
                // just ignore the invalid directory
                files = new string[0];
            }

            var filteredFiles = files.Where(f => FilterFile(fileFilters, f)).ToArray();

            Parallel.ForEach(filteredFiles, () => new List<FileResult>(),
                (file, state, list) =>
                {
                    var fileResult = new FileResult(file, projectName);
                    using (var reader = new StreamReader(file))
                    {
                        string line;
                        int lineNumber = 0;
                        while ((line = reader.ReadLine()) != null)
                        {
                            lineNumber++;
                            if (line.ToLower().Contains(search.ToLower()))
                            {
                                var lineResult = new LineResult(line, lineNumber);
                                fileResult.LineResults.Add(lineResult);
                            }
                        }
                    }
                    if (fileResult.LineResults.Any())
                    {
                        list.Add(fileResult);
                    }

                    return list;
                },
                list =>
                {
                    lock (synchLock)
                    {
                        allFiles.AddRange(list.ToArray());
                    }
                });
            foreach (var file in allFiles)
            {
                yield return file;
            }
        }
Example #33
0
 public static void AssertView <T>(FileResult result)
 {
     result.ShouldNotBeNull();
     result.ContentType.ShouldNotBeNull();
     result.FileDownloadName.ShouldNotBeNull();
 }
Example #34
0
        public FileResult GenerateInvoice(OrderModel order, string basePath)
        {
            string html            = AssetsFileLibrary.GetInvoiceTemplate(basePath);
            var    invoiceTemplate = new InvoiceTemplateModel
            {
                CreatedDateLabel     = "Datum vystavení:",
                DueDateLabel         = "Datum splatnosti:",
                PriceWithoutVatLabel = "Cena bez DPH",
                PriceWithVatLabel    = "Cena s DPH",
                TotalPriceLabel      = "Cena celkem s DPH",
                VatLabel             = "DPH",
                InvoiceLabel         = "Faktura",
                ItemsLabel           = "Položky",
                Supplier             = @"Hradištská 216
                            688 01 Uherský Brod
                            IČ: 29032393
                            DIČ: CZ29032393",
                PaymentInfo          = $@"Bankovní účet: 1111111111/0080
                                Variabilní symbol: {order.OrderNumber}
                                Způsob platby: {order.CalculatedData.Payment.SourceData.Name}"
            };

            // base
            html = InsertValue(html, "logoUrl", LogoUrl);
            html = InsertValue(html, "supplier", invoiceTemplate.Supplier);
            html = InsertValue(html, "paymentInfo", invoiceTemplate.PaymentInfo);
            // labels
            html = InsertValue(html, "invoiceLabel", invoiceTemplate.InvoiceLabel);
            html = InsertValue(html, "itemsLabel", invoiceTemplate.ItemsLabel);
            html = InsertValue(html, "priceWithVatLabel", invoiceTemplate.PriceWithVatLabel);
            html = InsertValue(html, "priceWithoutVatLabel", invoiceTemplate.PriceWithoutVatLabel);
            html = InsertValue(html, "vatLabel", invoiceTemplate.VatLabel);
            html = InsertValue(html, "totalPriceLabel", invoiceTemplate.TotalPriceLabel);
            html = InsertValue(html, "createdDateLabel", invoiceTemplate.CreatedDateLabel);
            html = InsertValue(html, "dueDateLabel", invoiceTemplate.DueDateLabel);
            // values
            html = InsertValue(html, "invoiceNumber", order.OrderNumberFormatted);
            html = InsertValue(html, "createdDate", order.CreatedDate.ToString("d.M.yyyy"));
            html = InsertValue(html, "dueDate", order.CreatedDate.AddDays(14).ToString("d.M.yyyy"));

            html = InsertValue(html, "customerNameLine", order.Customer.GetName());
            html = InsertValue(html, "customerStreetLine", order.Customer.GetAddress().GetStreetLine());
            html = InsertValue(html, "customerCityLine", order.Customer.GetAddress().GetCityLine());

            html = InsertValue(html, "totalPrice", order.CalculatedData.Total.TotalPrice.CzkWithVat.ToStringPriceFormat());

            string items = "";

            // generate all products
            if (order.CalculatedData != null)
            {
                List <string> products = order.CalculatedData.Products
                                         .Select(x =>
                                                 GenerateProductItem(
                                                     x.Count,
                                                     x.Product.Name,
                                                     x.TotalPrice))
                                         .ToList();
                items += string.Join(string.Empty, products);

                // add payment method to items
                if (order.CalculatedData.Payment != null)
                {
                    items += GenerateInvoiceItem(order.CalculatedData.Payment.SourceData.Name, order.CalculatedData.Payment.SourceData.TotalPrice);
                }
                // add transport to items
                if (order.CalculatedData.Transport != null)
                {
                    items += GenerateInvoiceItem(order.CalculatedData.Transport.SourceData.Name, order.CalculatedData.Transport.SourceData.TotalPrice);
                }
            }
            html = InsertValue(html, "items", items);

            FileResult result = _documentHtmlLibrary.HtmlToFile(html, $"faktura_{order.OrderNumberFormatted}.pdf");

            return(result);
        }
Example #35
0
        private static void SetContentType(HttpContext httpContext, FileResult result)
        {
            var response = httpContext.Response;

            response.ContentType = result.ContentType;
        }
        protected virtual (RangeItemHeaderValue range, long rangeLength, bool serveBody) SetHeadersAndLog(
            ActionContext context,
            FileResult result,
            long?fileLength,
            DateTimeOffset?lastModified = null,
            EntityTagHeaderValue etag   = null)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            SetContentType(context, result);
            SetContentDispositionHeader(context, result);
            Logger.FileResultExecuting(result.FileDownloadName);

            var request             = context.HttpContext.Request;
            var httpRequestHeaders  = request.GetTypedHeaders();
            var response            = context.HttpContext.Response;
            var httpResponseHeaders = response.GetTypedHeaders();

            if (lastModified.HasValue)
            {
                httpResponseHeaders.LastModified = lastModified;
            }
            if (etag != null)
            {
                httpResponseHeaders.ETag = etag;
            }

            var serveBody         = !HttpMethods.IsHead(request.Method);
            var preconditionState = GetPreconditionState(context, httpRequestHeaders, lastModified, etag);

            if (preconditionState == PreconditionState.NotModified)
            {
                serveBody           = false;
                response.StatusCode = StatusCodes.Status304NotModified;
            }
            else if (preconditionState == PreconditionState.PreconditionFailed)
            {
                serveBody           = false;
                response.StatusCode = StatusCodes.Status412PreconditionFailed;
            }

            if (fileLength.HasValue)
            {
                SetAcceptRangeHeader(context);
                // Assuming the request is not a range request, the Content-Length header is set to the length of the entire file.
                // If the request is a valid range request, this header is overwritten with the length of the range as part of the
                // range processing (see method SetContentLength).
                response.ContentLength = fileLength.Value;
                if (HttpMethods.IsHead(request.Method) || HttpMethods.IsGet(request.Method))
                {
                    if ((preconditionState == PreconditionState.Unspecified ||
                         preconditionState == PreconditionState.ShouldProcess))
                    {
                        if (IfRangeValid(context, httpRequestHeaders, lastModified, etag))
                        {
                            return(SetRangeHeaders(context, httpRequestHeaders, fileLength.Value));
                        }
                    }
                }
            }

            return(range : null, rangeLength : 0, serveBody : serveBody);
        }
Example #37
0
        public NumberIsSkipped()
        {
            var parser = new StreetSpecificationParser();

            _fileResult = parser.ParseStreetSpecification("..\\..\\SpecificationExamples\\NumberIsSkipped.txt");
        }