Exemplo n.º 1
0
        public async Task <FilesResult> LoadSelectedFile()
        {
            FilesResult           result = new FilesResult();
            ExternalStorageDevice sdCard = (await ExternalStorage.GetExternalStorageDevicesAsync()).FirstOrDefault();

            if (sdCard != null)
            {
                IEnumerable <ExternalStorageFile> files = await sdCard.RootFolder.GetFilesAsync();

                if (SelectedFile.Name.EndsWith(".txt"))
                {
                    System.IO.Stream fileStream = await SelectedFile.OpenForReadAsync();

                    //Read the entire file into the FileText property
                    using (StreamReader streamReader = new StreamReader(fileStream))
                    {
                        FileText = streamReader.ReadToEnd();
                    }

                    fileStream.Close();
                    result.Success = true;
                }
                else
                {
                    result.Success = false;
                    result.Message = "Invalid file type. Can only open text files with a '.txt' extension";
                }
            }

            return(result);
        }
Exemplo n.º 2
0
 private void AddAttachmentClick()
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() =>
     {
         FilesResult selectedFilesNoFilter = this._selectFilesService.GetSelectedFilesNoFilter(this.HandInDirectory);
         if (!selectedFilesNoFilter.HasSelected)
         {
             return;
         }
         List <HandInFileModel> selectedAttachments = selectedFilesNoFilter.HandInFileModels.ToList <HandInFileModel>();
         try
         {
             List <HandInFileModel> list = selectedAttachments.Where <HandInFileModel>((Func <HandInFileModel, bool>)(e => this._fileService.GetSizeInBytes(e.Path) > this.MaxHandInFileSizeInBytes)).ToList <HandInFileModel>();
             if (list.Any <HandInFileModel>())
             {
                 this._messenger.Send <OnOkPopupOpened>(new OnOkPopupOpened(new OkPopupViewModel(string.Format(this._languageService.GetString("HandInFileSelectorAttachmentsExceedsFileLimitMessageText"), (object)(this.MaxHandInFileSizeInBytes / 1048576L), (object)string.Join("\n", list.Select <HandInFileModel, string>((Func <HandInFileModel, string>)(e => e.Name)).ToArray <string>())), this._languageService.GetString("HandInFileSelectorFilesExceedsFileLimitOkButtonText"), this._messenger)));
                 if (list.Count == selectedAttachments.Count)
                 {
                     return;
                 }
                 selectedAttachments = selectedAttachments.Except <HandInFileModel>((IEnumerable <HandInFileModel>)list).ToList <HandInFileModel>();
             }
         }
         catch (Exception ex)
         {
             this._loggerService.Log("Could not check filesize of selected files: " + string.Join(", ", selectedAttachments.Select <HandInFileModel, string>((Func <HandInFileModel, string>)(s => s.Path)).ToArray <string>()), ex);
             return;
         }
         List <HandInFileModel> duplicateHandInFiles = selectedAttachments.Where <HandInFileModel>((Func <HandInFileModel, bool>)(e => this.AnyExistingHandInFilesForName(e, (IEnumerable <HandInFileModel>)selectedAttachments))).ToList <HandInFileModel>();
         if (duplicateHandInFiles.Any <HandInFileModel>())
         {
             this._messenger.Send <OnOkCancelPopupOpened>(new OnOkCancelPopupOpened(new OkCancelPopupViewModel(this._languageService.GetString("HandInFileSelectorAddDuplicatesMessageText"), this._languageService.GetString("HandInFileSelectorDuplicatesAddButtonText"), this._languageService.GetString("HandInFileSelectorDuplicatesCancelButtonText"), this._messenger), (Action <bool>)(isOkSelected =>
             {
                 if (!isOkSelected)
                 {
                     return;
                 }
                 List <HandInFileModel> list = selectedAttachments.Where <HandInFileModel>((Func <HandInFileModel, bool>)(sf => duplicateHandInFiles.Select <HandInFileModel, string>((Func <HandInFileModel, string>)(a => a.Path)).All <string>((Func <string, bool>)(a => a != sf.Path)))).ToList <HandInFileModel>();
                 List <HandInFileModel> existingHandInFiles = this.SelectedAttachments.Select <HandInFileViewModel, HandInFileModel>((Func <HandInFileViewModel, HandInFileModel>)(e => e.HandInFileModel)).ToList <HandInFileModel>();
                 if (this.SelectedMainDocument?.HandInFileModel != null)
                 {
                     existingHandInFiles.Add(this.SelectedMainDocument.HandInFileModel);
                 }
                 existingHandInFiles.AddRange((IEnumerable <HandInFileModel>)selectedAttachments);
                 IEnumerable <HandInFileModel> collection = duplicateHandInFiles.Select <HandInFileModel, HandInFileModel>((Func <HandInFileModel, HandInFileModel>)(a => this.GetNewHandInFileModel(a, existingHandInFiles)));
                 list.AddRange(collection);
                 this.AddAttachments((IEnumerable <HandInFileModel>)list);
             })));
         }
         else
         {
             this.AddAttachments((IEnumerable <HandInFileModel>)selectedAttachments);
         }
     }));
 }
Exemplo n.º 3
0
 public async Task <FilesResult> GetFilesAsync(string siteId, string documentLibraryId)
 {
     try
     {
         var drives = await _graphServiceClient.Sites[siteId].Drives[documentLibraryId].Root.Children.Request()
                      .WithUsernamePassword(_username, _password).GetAsync();
         return(FilesResult.Success(drives.AsEnumerable().Select(Contracts.Files.File.FromView).ToList()));
     }
     catch (ServiceException e)
     {
         return(FilesResult.Failed(e.InnerException?.Message ?? e.Error?.Message ?? e.Message));
     }
 }
Exemplo n.º 4
0
        public async Task <FilesResult> ListAsync(Proxy proxy, string api, string status, int offset, int limit)
        {
            return(await Task.Factory.StartNew(() =>
            {
                HttpWebRequest webRequest = WebRequest.Create("https://api.printful.com/files") as HttpWebRequest;

                if (proxy != null)
                {
                    webRequest.Proxy = proxy.Get();
                    webRequest.Credentials = proxy.GetCredential();
                }
                webRequest.Method = "GET";
                webRequest.ContentType = "application/json; charset=utf-8";
                webRequest.Headers.Add("Authorization", "Basic " + Manager.API.Encode(api));

                string data = $"status={status}&offset={offset}&limit={limit}"; //replace <value>
                byte[] data_form = Encoding.UTF8.GetBytes(data);

                webRequest.ContentLength = data_form.Length;
                Stream newStream = webRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data_form, 0, data_form.Length);
                newStream.Close();

                WebResponse response = webRequest.GetResponse();
                if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
                {
                    // Get the stream containing content returned by the server.
                    Stream dataStream = response.GetResponseStream();
                    if (dataStream != null)
                    {
                        // Open the stream using a StreamReader for easy access.
                        StreamReader reader = new StreamReader(dataStream);
                        // Read the content.
                        string responseFromServer = reader.ReadToEnd();
                        // Display the content.
                        FilesResult result =
                            JsonConvert.DeserializeObject <FilesResult>(responseFromServer, Converter.Settings);

                        return result;
                    }
                }
                return null;
            }));
        }
Exemplo n.º 5
0
 private void ChooseMainDocumentClick()
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() =>
     {
         FilesResult selectedFile = this._selectFilesService.GetSelectedFile(this.HandInDirectory, this._languageService.GetString("HandInFileSelectorValidExtensionsText"), (IEnumerable <string>) this.AllowedFileExtensions);
         if (!selectedFile.HasSelected || !selectedFile.HandInFileModels.Any <HandInFileModel>())
         {
             return;
         }
         HandInFileModel selectedMainDocument = selectedFile.HandInFileModels.First <HandInFileModel>();
         try
         {
             if (this._fileService.GetSizeInBytes(selectedMainDocument.Path) > this.MaxHandInFileSizeInBytes)
             {
                 this._messenger.Send <OnOkPopupOpened>(new OnOkPopupOpened(new OkPopupViewModel(string.Format(this._languageService.GetString("HandInFileSelectorMainDocumentExceedsFileLimitMessageText"), (object)(this.MaxHandInFileSizeInBytes / 1048576L)), this._languageService.GetString("HandInFileSelectorFilesExceedsFileLimitOkButtonText"), this._messenger)));
                 return;
             }
         }
         catch (Exception ex)
         {
             return;
         }
         if (this.SelectedAttachments.Any <HandInFileViewModel>((Func <HandInFileViewModel, bool>)(e => e.HandInFileModel?.Name == selectedMainDocument.Name)))
         {
             this._messenger.Send <OnOkCancelPopupOpened>(new OnOkCancelPopupOpened(new OkCancelPopupViewModel(this._languageService.GetString("HandInFileSelectorAddDuplicatesMessageText"), this._languageService.GetString("HandInFileSelectorDuplicatesAddButtonText"), this._languageService.GetString("HandInFileSelectorDuplicatesCancelButtonText"), this._messenger), (Action <bool>)(isOkSelected =>
             {
                 if (!isOkSelected)
                 {
                     return;
                 }
                 List <HandInFileViewModel> list = this.SelectedAttachments.ToList <HandInFileViewModel>();
                 HandInFileModel newMainDocument = this.GetNewHandInFileModel(selectedMainDocument, list.Select <HandInFileViewModel, HandInFileModel>((Func <HandInFileViewModel, HandInFileModel>)(e => e.HandInFileModel)).ToList <HandInFileModel>());
                 DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.SetMainDocument(newMainDocument)));
             })));
         }
         else
         {
             this.SetMainDocument(selectedMainDocument);
         }
     }));
 }
Exemplo n.º 6
0
        public async Task <FilesResult> GetFiles()
        {
            FilesResult result = new FilesResult();

            ExternalStorageDevice sdCard = (await ExternalStorage.GetExternalStorageDevicesAsync()).FirstOrDefault();

            if (sdCard != null)
            {
                IEnumerable <ExternalStorageFile> files = await sdCard.RootFolder.GetFilesAsync();

                ExternalStorageFile file = files.FirstOrDefault();
                Files          = new ObservableCollection <ExternalStorageFile>(files.Where(f => f.Name.EndsWith(".txt")).ToList());
                result.Success = true;
            }
            else
            {
                result.Success = false;
                result.Message = "An SD card was not detected.";
            }
            return(result);
        }
Exemplo n.º 7
0
        public async Task GetFiles_Returns_BadRequestObjectResult_When_AnErrorOccurred()
        {
            // Arrange
            var req    = TestFactory.CreateHttpRequest();
            var logger = TestFactory.CreateLogger(LoggerTypes.List);

            var documentLibraryId = "documentLibraryId1";

            _fileServiceMock.Setup(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId))).ReturnsAsync(FilesResult.Failed("An error occurred."));

            // Act
            var httpActionResult = await _controller.GetFiles(req, documentLibraryId, logger);

            // Assert
            Assert.IsInstanceOf(typeof(BadRequestObjectResult), httpActionResult);

            _fileServiceMock.Verify(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId)), Times.Once);

            var result = ((BadRequestObjectResult)httpActionResult);

            Assert.IsNotNull(result);
            Assert.AreEqual("An error occurred.", result.Value);
        }
Exemplo n.º 8
0
        public async Task GetFiles_Returns_EmptyArray_When_NoFilesFound()
        {
            // Arrange
            var req               = TestFactory.CreateHttpRequest();
            var logger            = TestFactory.CreateLogger(LoggerTypes.List);
            var documentLibraryId = "documentLibraryId1";
            var files             = new List <File>();

            _fileServiceMock.Setup(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId))).ReturnsAsync(FilesResult.Success(files));

            // Act
            var httpActionResult = await _controller.GetFiles(req, documentLibraryId, logger);

            // Assert
            Assert.IsInstanceOf(typeof(OkObjectResult), httpActionResult);

            _fileServiceMock.Verify(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId)), Times.Once);

            var result = ((OkObjectResult)httpActionResult).Value as FileModelInfo[];

            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Length);
        }
Exemplo n.º 9
0
        public async Task GetFiles_Returns_Files_When_Found()
        {
            // Arrange
            var req               = TestFactory.CreateHttpRequest();
            var logger            = TestFactory.CreateLogger(LoggerTypes.List);
            var documentLibraryId = "documentLibraryId1";
            var files             = new List <File>
            {
                new File
                {
                    Id             = "Id1",
                    Name           = "FileName1",
                    Description    = "FileDescription1",
                    CreatedAt      = new DateTimeOffset(new DateTime(2020, 3, 4)),
                    LastModifiedAt = new DateTimeOffset(new DateTime(2020, 3, 4)),
                    DownloadUrl    = "https://downloadurl1",
                    Size           = 250L
                },
                new File
                {
                    Id             = "Id2",
                    Name           = "FileName2",
                    Description    = "FileDescription2",
                    CreatedAt      = new DateTimeOffset(new DateTime(2020, 3, 5)),
                    LastModifiedAt = new DateTimeOffset(new DateTime(2020, 3, 5)),
                    DownloadUrl    = "https://downloadurl2",
                    Size           = 500L
                }
            };

            _fileServiceMock.Setup(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId))).ReturnsAsync(FilesResult.Success(files));

            // Act
            var httpActionResult = await _controller.GetFiles(req, documentLibraryId, logger);

            // Assert
            Assert.IsInstanceOf(typeof(OkObjectResult), httpActionResult);

            _fileServiceMock.Verify(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId)), Times.Once);

            var result = ((OkObjectResult)httpActionResult).Value as FileModelInfo[];

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Length);
            Assert.AreEqual("Id1", result[0].Id);
            Assert.AreEqual("FileName1", result[0].Name);
            Assert.AreEqual("FileDescription1", result[0].Description);
            Assert.AreEqual(new DateTime(2020, 3, 4), result[0].CreatedAt);
            Assert.AreEqual(new DateTime(2020, 3, 4), result[0].LastModifiedAt);
            Assert.AreEqual("https://downloadurl1", result[0].DownloadUrl);
            Assert.AreEqual(250L, result[0].Size);
            Assert.AreEqual("Id2", result[1].Id);
            Assert.AreEqual("FileName2", result[1].Name);
            Assert.AreEqual("FileDescription2", result[1].Description);
            Assert.AreEqual(new DateTime(2020, 3, 5), result[1].CreatedAt);
            Assert.AreEqual(new DateTime(2020, 3, 5), result[1].LastModifiedAt);
            Assert.AreEqual("https://downloadurl2", result[1].DownloadUrl);
            Assert.AreEqual(500L, result[1].Size);
        }