Example #1
0
        /// <summary>
        /// Tests create view against two options with compare results
        /// </summary>
        private void TestCompareOptions(TestFile testFile, RenderOptions options1, RenderOptions options2)
        {
            var viewOptions1 = new ViewOptions
            {
                FileInfo      = testFile.ToFileInfo(),
                RenderOptions = options1
            };
            var viewResult1 = ViewApi.CreateView(new CreateViewRequest(viewOptions1));
            var response1   = FileApi.DownloadFile(new DownloadFileRequest {
                path = viewResult1.Pages[0].Path
            });

            Assert.Greater(response1.Length, 0);

            Cleanup();

            var viewOptions2 = new ViewOptions
            {
                FileInfo      = testFile.ToFileInfo(),
                RenderOptions = options2
            };
            var viewResult2 = ViewApi.CreateView(new CreateViewRequest(viewOptions2));
            var response2   = FileApi.DownloadFile(new DownloadFileRequest {
                path = viewResult2.Pages[0].Path
            });

            Assert.Greater(response2.Length, 0);

            Assert.AreNotEqual(response1.Length, response2.Length);
        }
Example #2
0
        private void Check(object sender, NavigationEventArgs e)
        {
            LoadProgressBar.Value      = 100;
            LoadProgressBar.Visibility = Visibility.Collapsed;
            label1.Content             = "加载完成";
            document = wb.Document;
            string title = ((HTMLDocument)document).title;

            if (title == null || title == "")
            {
                this.Title = "新标签页 - 极简浏览器";
            }
            else
            {
                this.Title = title + " - 极简浏览器";
            }
            if (wb.Source.ToString( ) != "about:blank")
            {
                UrlTextBox.Text = wb.Source.ToString( );
                string Data = UrlTextBox.Text + " " + this.Title.Replace(" - 极简浏览器", "") + " " + DateTime.Now.Date;
                FileApi.Write(UrlTextBox.Text, FileType.History);
            }
            else
            {
                UrlTextBox.Text = "";
            }
        }
Example #3
0
        public void WordFindAndReplaceTestMultiply()
        {
            var apiKey = new Dictionary <string, string>()
            {
                { "AppSecret", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" },
                { "AppId", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" }
            };

            var config = new Configuration(apiKey: apiKey);

            config.ApiClient = new ApiClient(config);

            var word = new WordApi(config);

            word.WordFindAndReplace("letterlegal5.doc", "letterlegal5_replace2.doc", new List <string> {
                "1", "2"
            }, new List <string> {
                "!", "!"
            });

            var file   = new FileApi(config);
            var result = file.FileList();

            Assert.IsTrue(result.Contains("letterlegal5_replace2.doc"));
        }
        public File[] GetFiles <T>(T entity)
            where T : Entity
        {
            FileApi api = new FileApi(CurrentConfiguration);

            return(new File[] { });
        }
        public void TestCopyMoveFile()
        {
            var testFile = TestFiles.Docx;

            // Create temp folder
            var cRequest = new CreateFolderRequest("temp");
            FolderApi.CreateFolder(cRequest);

            // Copy file
            var destPath = $"temp/{testFile.FileName}";
            var request = new CopyFileRequest(testFile.FullName, destPath);
            FileApi.CopyFile(request);

            // Check copied file
            var eRequest = new ObjectExistsRequest(destPath);
            var eResponse = StorageApi.ObjectExists(eRequest);
            Assert.IsTrue(eResponse.Exists);

            // Move file
            var newDestPath = $"temp/{testFile.FileName.Replace(".", "_1.")}";
            var mRequest = new MoveFileRequest(destPath, newDestPath);
            FileApi.MoveFile(mRequest);

            // Check moved file
            eRequest = new ObjectExistsRequest(newDestPath);
            eResponse = StorageApi.ObjectExists(eRequest);
            Assert.IsTrue(eResponse.Exists);

            // Delete temp folder
            var delRequest = new DeleteFolderRequest("temp", null, true);
            FolderApi.DeleteFolder(delRequest);
        }
        public void BeforeAllTests()
        {
            var config = new Configuration(_appSid, _appKey)
            {
                ApiBaseUrl = _apiBaseUrl
            };

            SignatureApi = new SignApi(config);
            InfoApi      = new InfoApi(config);
            FileApi      = new FileApi(config);
            FolderApi    = new FolderApi(config);
            StorageApi   = new StorageApi(config);

            //Prepare folder for signed files
            DownloadFolder = Path.Combine(GetTestDataPath(), "Downloaded");
            if (Directory.Exists(DownloadFolder))
            {
                ClearFolder(DownloadFolder);
            }
            else
            {
                Directory.CreateDirectory(DownloadFolder);
            }

            UploadTestFiles();
        }
Example #7
0
        /// <summary>
        /// Copy environment variables and network shares to the destination user context
        /// </summary>
        /// <remarks>CopyNetworkShares is *the best I could do*. Too much verbose, asks for passwords, etc. Far from ideal.</remarks>
        /// <returns>a modified args list</returns>
        internal IEnumerable<string> AddCopyEnvironment(IEnumerable<string> args, ElevationRequest.ConsoleMode mode)
        {
            if (Settings.CopyEnvironmentVariables || Settings.CopyNetworkShares)
            {
                var silent = InputArguments.Debug ? string.Empty : "@";
                var sb = new StringBuilder();
                if (Settings.CopyEnvironmentVariables && mode != ElevationRequest.ConsoleMode.TokenSwitch) // TokenSwitch already uses the current env block.
                {
                    foreach (DictionaryEntry envVar in Environment.GetEnvironmentVariables())
                    {
                        if (envVar.Key.ToString().In("prompt"))
                            continue;

                        sb.AppendLine($"{silent}SET {envVar.Key}={envVar.Value}");
                    }
                }
                if (Settings.CopyNetworkShares)
                {
                    foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Network && d.Name.Length == 3))
                    {
                        var tmpSb = new StringBuilder(2048);
                        var size = tmpSb.Capacity;

                        var error = FileApi.WNetGetConnection(drive.Name.Substring(0, 2), tmpSb, ref size);
                        if (error == 0)
                        {
                            sb.AppendLine($"{silent}ECHO Connecting {drive.Name.Substring(0, 2)} to {tmpSb.ToString()} 1>&2");
                            sb.AppendLine($"{silent}NET USE /D {drive.Name.Substring(0, 2)} >NUL 2>NUL");
                            sb.AppendLine($"{silent}NET USE {drive.Name.Substring(0, 2)} {tmpSb.ToString()} 1>&2");
                        }
                    }
                }

                string tempFolder = Path.Combine(
                    Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.Machine), // use machine temp to ensure elevated user has access to temp folder
                    nameof(gsudo));

                var dirSec = new DirectorySecurity();
                dirSec.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, AccessControlType.Allow));
                Directory.CreateDirectory(tempFolder, dirSec);

                string tempBatName = Path.Combine(
                    tempFolder,
                    $"{Guid.NewGuid()}.bat");

                File.WriteAllText(tempBatName, sb.ToString());

                System.Security.AccessControl.FileSecurity fSecurity = new System.Security.AccessControl.FileSecurity();
                fSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                File.SetAccessControl(tempBatName, fSecurity);

                return new string[] {
                    Environment.GetEnvironmentVariable("COMSPEC"),
                    "/c" ,
                    $"\"{tempBatName} & del /q {tempBatName} & {string.Join(" ",args)}\""
                };
            }
            return args;
        }
        public AsposeOCRCloudApiService(IConfiguration config)
        {
            string ClientId     = config["AsposeOCRUserData:ClientId"];
            string ClientSecret = config["AsposeOCRUserData:ClientSecret"];

            OCRCloudApi = new OcrApi(apiKey: ClientSecret, appSid: ClientId);
            OCRFileApi  = new FileApi(apiKey: ClientSecret, appSid: ClientId);
        }
Example #9
0
        private List <AHAItem> InvokeSearch(SearchStreamOptionsRecord options, PaginationRecord pg)
        {
            try
            {
                log.Debug("Search options: " + options.ToJson());
                log.Debug("Search page: " + pg.ToJson());
                this.options = options;
                ObjectApi objectApi = new ObjectApi(session.GetApiClient());
                log.Debug("Calling SearchObjects API");
                SearchObjectsResult result = objectApi.SearchObjects(options.ToJson(), pg.ToJson());
                if (result.Hdr.Rc == 0)
                {
                    pager = result.Pager;
                    List <AHAItem> items   = new List <AHAItem>();
                    List <Record>  records = result.Records;
                    log.Debug(records.Count + " records returned");

                    foreach (var record in records)
                    {
                        String jsonString = record.Json;
                        log.Debug("Record: " + jsonString);
                        log.Debug("Creating AHA item");
                        AHAItem item = itemFromJson(jsonString);
                        log.Debug("AHAItem: " + JsonConvert.SerializeObject(item));

                        if (item.Type.Equals(FILE_TYPE))
                        {
                            log.Debug("Getting additional info for file");
                            FileApi        fileApi        = new FileApi(session.GetApiClient());
                            ViewFileResult viewFileResult = fileApi.ViewFile(item.Key);
                            if (viewFileResult.Hdr.Rc == 0)
                            {
                                FileRecord fileRecord = viewFileResult.File;
                                item.LastUpdater = fileRecord.LastUpdater.DisplayName;
                                item.Version     = fileRecord.UiVersion;
                                log.Debug("Last updater: " + item.LastUpdater);
                                log.Debug("Version: " + item.Version);
                            }
                            else
                            {
                                log.Error("Vmoso error getting additional info for file. Rc=" + viewFileResult.Hdr.Rc);
                            }
                        }

                        items.Add(item);
                    }
                    return(items);
                }
                else
                {
                    throw new Exception("Vmoso error searching objects. Rc=" + result.Hdr.Rc);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error searching objects from Vmoso", ex);
            }
        }
        public void DownloadFiles(Configuration config, string fileName, string fileType, int offset = 0, int count = 0)
        {
            try
            {
                var    fileApi = new FileApi(config);
                Stream file    = new FileStream(ConfigurationManager.AppSettings["SourcePath"] + fileName + "." + fileType, FileMode.Open, FileAccess.Read);
                Stream outFileStream;// = new FileStream("C:/docconversion/downloads/" + fileName + "." + fileType, FileMode.OpenOrCreate, FileAccess.Write);
                Stream metricFileStream = new FileStream(ConfigurationManager.AppSettings["SourcePath"] + "metrics/" + fileName + "-" + fileType + "_" + offset / count + "_Metric.txt", FileMode.OpenOrCreate, FileAccess.Write);
                var    outFile          = new StreamWriter(metricFileStream);

                var timer = new Stopwatch();
                if (count > 0)
                {
                    for (var i = offset; i < offset + count; i++)
                    {
                        //file.Seek(0, SeekOrigin.Begin);
                        timer = Stopwatch.StartNew();
                        var response = fileApi.FileDownloadToStreamWithHttpInfo(fileName + "_" + i + "." + fileType);
                        if (response != null && response.Data != null && response.StatusCode >= 200 && response.StatusCode <= 205)
                        {
                            timer.Stop();
                            outFileStream = new FileStream(ConfigurationManager.AppSettings["SourcePath"] + "downloads/" + fileName + "_" + i + "." + fileType, FileMode.OpenOrCreate, FileAccess.Write);
                            response.Data.CopyTo(outFileStream);
                            outFileStream.Close();
                            outFile.Write("Uploading time: " + timer.ElapsedMilliseconds + ", " + fileName + "_" + i + "." + fileType + "\n\n");
                            Console.WriteLine(fileName + "_" + i + "." + fileType + " download success!");
                        }
                        else
                        {
                            Console.WriteLine("File upload failed!");
                        }
                        if (response.Data != null)
                        {
                            var a = response.Data;
                        }
                    }
                }
                else
                {
                    outFileStream = new FileStream(ConfigurationManager.AppSettings["SourcePath"] + "downloads/" + fileName + "." + fileType, FileMode.OpenOrCreate, FileAccess.Write);
                    var response = fileApi.FileDownloadToStreamWithHttpInfo(fileName + "." + fileType);
                    if (response?.Data != null)
                    {
                        response.Data.CopyTo(outFileStream);
                    }
                    outFileStream.Close();
                }

                outFile.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("File create failed. No such directory or access failure.\n");

                throw;
            }
        }
Example #11
0
        static public Model.FileRecord uploadFile(VmosoSession session, String filePath, String title, String description, bool dominantActivity)
        {
            try {
                String url       = session.Host + "/up/file";
                String userAgent = session.GetApiClient().Configuration.UserAgent;

                WebClient client = new WebClient();
                client.Headers.Add("X-CV-Authorization", session.GetAuthorizationHeader());
                client.Headers.Add("User-Agent", userAgent);

                byte[]  response   = client.UploadFile(url, filePath);
                var     jsonString = System.Text.Encoding.Default.GetString(response);
                dynamic dynObj     = JsonConvert.DeserializeObject(jsonString);
                var     file       = dynObj[0];

                String fileName       = file.name;
                String fileDownloadId = file.fileDownloadId;
                String mimeType       = file.mimeType;
                int    fileSize       = file.filesize;

                FileRecord fr = new FileRecord();
                fr.Type               = "file";
                fr.Name               = title;
                fr.Description        = description;
                fr.Filename           = "1";
                fr.Originalfilename   = fileName;
                fr.SiteSelected       = "1";
                fr.FilestoreDirRoot   = "1";
                fr.FilestoreFilestore = fileDownloadId;
                fr.Mimetype           = mimeType;
                fr.Filesize           = fileSize;
                fr.Downloadable       = "1";
                fr.Simpletype         = "1";
                fr.DvaultItemFlag     = "1";
                fr.DvaultItemStatus   = "1";
                fr.BvrevVersion       = 1;
                fr.BvrevLastUpdater   = 1;
                fr.Trashed            = "0";

                FileApi fileApi = new FileApi(session.GetApiClient());

                CreateFileInput createFileInput = new CreateFileInput(fr, dominantActivity, null);

                CreateFileResult createFileResult = fileApi.CreateFile(createFileInput);
                if (createFileResult.Hdr.Rc == 0)
                {
                    return(createFileResult.File);
                }
                else
                {
                    throw new Exception("Error uploading file. Rc=" + createFileResult.Hdr.Rc);
                }
            } catch (Exception ex)
            {
                throw new Exception("Error uploading file", ex);
            }
        }
        public void TestDownloadFile()
        {
            // Arrange
            var testFile = TestFiles.Docx;
            var request = new DownloadFileRequest { path = testFile.FullName };

            // Act & Assert
            var response = FileApi.DownloadFile(request);
            Assert.Greater(response.Length, 0);
        }
Example #13
0
        public void FileListTestBasicAuth()
        {
            var config = new Configuration(username: "******", password: "******");

            config.ApiClient = new ApiClient(config);
            var client = new FileApi(config);

            var result = client.FileList();

            Assert.IsTrue(result.Any());
        }
Example #14
0
        public void FileDeleteFileTest()
        {
            DeleteFileRequest request = new DeleteFileRequest();

            request.path      = Path.Combine(dataFolder, "TestFile.pdf");
            request.storage   = storageName;
            request.versionId = null;
            var response = FileApi.DeleteFile(request);

            Assert.AreEqual(200, response.Code);
        }
Example #15
0
        public void FileGetDownloadTest()
        {
            GetDownloadRequest request = new GetDownloadRequest();

            request.path      = Path.Combine(dataFolder, "TestFile.pdf");
            request.storage   = storageName;
            request.versionId = null;
            var response = FileApi.GetDownload(request);

            Assert.IsNotNull(response);
        }
Example #16
0
        private Stream?VerifierExtraLoadHandler(string arg)
        {
            DebugTools.AssertNotNull(_loaderArgs);

            if (_loaderArgs !.FileApi.TryOpen(arg, out var stream))
            {
                return(stream);
            }

            return(null);
        }
        static void TranslateDocument(Configuration conf)
        {
            // request parameters for translation
            string     name      = "test.docx";
            string     folder    = "";
            string     pair      = "en-fr";
            string     format    = "docx";
            string     outformat = "";
            string     storage   = "First Storage";
            string     saveFile  = "translated_d.docx";
            string     savePath  = "";
            bool       masters   = false;
            List <int> elements  = new List <int>();

            // local paths to upload and download files
            string uploadPath   = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + "/" + name;
            string downloadPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + "/" + saveFile;

            TranslationApi api     = new TranslationApi(conf);
            FileApi        fileApi = new FileApi(conf);


            Stream stream = File.Open(uploadPath, FileMode.Open);

            UploadFileRequest uploadRequest = new UploadFileRequest {
                File = stream, path = name, storageName = storage
            };
            FilesUploadResult uploadResult = fileApi.UploadFile(uploadRequest);

            Console.WriteLine("Files uploaded: " + uploadResult.Uploaded.Count);

            TranslateDocumentRequest request  = api.CreateDocumentRequest(name, folder, pair, format, outformat, storage, saveFile, savePath, masters, elements);
            TranslationResponse      response = api.RunTranslationTask(request);

            Console.WriteLine(response.Message);
            foreach (var key in response.Details.Keys)
            {
                Console.WriteLine(key + ": " + response.Details[key]);
            }

            DownloadFileRequest downloadRequest = new DownloadFileRequest {
                storageName = storage, path = saveFile
            };
            Stream result = fileApi.DownloadFile(downloadRequest);

            Console.WriteLine("Translated file downloaded");

            using (FileStream file = new FileStream(downloadPath, FileMode.Create, FileAccess.Write))
            {
                result.CopyTo(file);
            }
            Console.WriteLine("Translated file saved");
        }
Example #18
0
        public static void Run()
        {
            try
            {
                // Create necessary API instances
                var editApi = new EditApi(Common.GetConfig());
                var fileApi = new FileApi(Common.GetConfig());

                // The document already uploaded into the storage.
                // Load it into editable state
                var loadOptions = new SpreadsheetLoadOptions
                {
                    FileInfo = new FileInfo
                    {
                        FilePath = "Spreadsheet/four-sheets.xlsx"
                    },
                    OutputPath     = "output",
                    WorksheetIndex = 0
                };

                var loadResult = editApi.Load(new LoadRequest(loadOptions));

                // Download html document
                var stream     = fileApi.DownloadFile(new DownloadFileRequest(loadResult.HtmlPath));
                var htmlString = new StreamReader(stream, Encoding.UTF8).ReadToEnd();

                // Edit something...
                htmlString = htmlString.Replace("This is sample sheet", "This is sample sheep");

                // Upload html back to storage
                fileApi.UploadFile(new UploadFileRequest(loadResult.HtmlPath,
                                                         new MemoryStream(Encoding.UTF8.GetBytes(htmlString))));

                // Save html back to xlsx
                var saveOptions = new SpreadsheetSaveOptions
                {
                    FileInfo      = loadOptions.FileInfo,
                    OutputPath    = "output/edited.xlsx",
                    HtmlPath      = loadResult.HtmlPath,
                    ResourcesPath = loadResult.ResourcesPath
                };

                var saveResult = editApi.Save(new SaveRequest(saveOptions));

                // Done.
                Console.WriteLine("Document edited: " + saveResult.Path);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
        public static void Run()
        {
            try
            {
                // Create necessary API instances
                var editApi = new EditApi(Common.GetConfig());
                var fileApi = new FileApi(Common.GetConfig());

                // The document already uploaded into the storage.
                // Load it into editable state
                var loadOptions = new PresentationLoadOptions
                {
                    FileInfo = new FileInfo
                    {
                        FilePath = "Presentation/with-notes.pptx"
                    },
                    OutputPath  = "output",
                    SlideNumber = 0
                };

                var loadResult = editApi.Load(new LoadRequest(loadOptions));

                // Download html document
                var stream     = fileApi.DownloadFile(new DownloadFileRequest(loadResult.HtmlPath));
                var htmlString = new StreamReader(stream, Encoding.UTF8).ReadToEnd();

                // Edit something...
                htmlString = htmlString.Replace("Slide sub-heading", "Hello world!");

                // Upload html back to storage
                fileApi.UploadFile(new UploadFileRequest(loadResult.HtmlPath,
                                                         new MemoryStream(Encoding.UTF8.GetBytes(htmlString))));

                // Save html back to pptx
                var saveOptions = new PresentationSaveOptions
                {
                    FileInfo      = loadOptions.FileInfo,
                    OutputPath    = "output/edited.pptx",
                    HtmlPath      = loadResult.HtmlPath,
                    ResourcesPath = loadResult.ResourcesPath
                };

                var saveResult = editApi.Save(new SaveRequest(saveOptions));

                // Done.
                Console.WriteLine("Document edited: " + saveResult.Path);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
Example #20
0
 private void button1_Click1(object sender, RoutedEventArgs e)
 {
     if (FileApi.Clear(FileType.BookMark) != true)
     {
         ShowFileError();
     }
     else
     {
         History his = new History( );
         his.Show( );
         this.Close( );
     }
 }
Example #21
0
 private void HistoryClear(object sender, RoutedEventArgs e)
 {
     if (FileApi.Clear(FileType.History) != true)
     {
         ShowFileError();
     }
     else
     {
         History his = new History( );
         his.Show( );
         this.Close( );
     }
 }
Example #22
0
 public InputStreamsApi(IBitmovinApiClientFactory apiClientFactory)
 {
     _apiClient    = apiClientFactory.CreateClient <IInputStreamsApiClient>();
     Type          = new TypeApi(apiClientFactory);
     AudioMix      = new AudioMixApi(apiClientFactory);
     Ingest        = new IngestApi(apiClientFactory);
     Sidecar       = new SidecarApi(apiClientFactory);
     Concatenation = new ConcatenationApi(apiClientFactory);
     File          = new FileApi(apiClientFactory);
     Trimming      = new TrimmingApi(apiClientFactory);
     Subtitles     = new SubtitlesApi(apiClientFactory);
     Captions      = new CaptionsApi(apiClientFactory);
 }
Example #23
0
        public void FilePutCreateTest()
        {
            string           path    = Path.Combine(dataFolder, "folder2/TestFile1.pdf");
            PutCreateRequest request = new PutCreateRequest();

            request.path      = Path.Combine(dataFolder, "folder4/TestFile1.pdf");
            request.File      = FileApi.GetDownload(new GetDownloadRequest(path, null, storageName));
            request.storage   = destStorageName;
            request.versionId = null;
            var response = FileApi.PutCreate(request);

            Assert.AreEqual(200, response.Code);
        }
Example #24
0
        public void FilePutCopyTest()
        {
            PutCopyRequest request = new PutCopyRequest();

            request.path        = Path.Combine(dataFolder, "/folder2/TestFile1.pdf");
            request.storage     = storageName;
            request.versionId   = null;
            request.newdest     = Path.Combine(dataFolder, "folder3/TestFile1.pdf");
            request.destStorage = destStorageName;
            var response = FileApi.PutCopy(request);

            Assert.AreEqual(200, response.Code);
        }
Example #25
0
        private GitLabClient(Uri uri, string privateToken)
        {
            var clientFactory = new ClientFactory(uri, new PrivateTokenAuthenticator(privateToken));

            var requestFactory = new RequestFactory(clientFactory);

            Branches = new BranchesApi(requestFactory);
            Commits  = new CommitsApi(requestFactory);
            Files    = new FileApi(requestFactory);
            Issues   = new IssueApi(requestFactory);
            Projects = new ProjectApi(requestFactory);
            Users    = new UserApi(requestFactory);
        }
Example #26
0
        public void FilePostMoveFileTest()
        {
            PostMoveFileRequest request = new PostMoveFileRequest();

            request.src         = Path.Combine(dataFolder, "TestFile1.pdf");
            request.storage     = storageName;
            request.dest        = Path.Combine(dataFolder, "TestFile2.pdf");
            request.destStorage = destStorageName;
            request.versionId   = null;
            var response = FileApi.PostMoveFile(request);

            Assert.AreEqual(200, response.Code);
        }
        public void StorageDownloadFile()
        {
            // Arrange
            var testFile = TestFiles.PdfStorage.FirstOrDefault(x => x.Name.Equals("01_pages.pdf"));
            var request  = new DownloadFileRequest {
                path = testFile.Path
            };

            // Act & Assert
            var response = FileApi.DownloadFile(request);

            Assert.Greater(response.Length, 0);
        }
Example #28
0
        static public Model.FileRecord uploadNewVersion(VmosoSession session, String fileKey, String filePath)
        {
            try
            {
                FileApi        fileApi        = new FileApi(session.GetApiClient());
                ViewFileResult viewFileResult = fileApi.ViewFile(fileKey);
                if (viewFileResult.Hdr.Rc == 0)
                {
                    FileRecord fileRecord = viewFileResult.File;

                    String url       = session.Host + "/up/file";
                    String userAgent = session.GetApiClient().Configuration.UserAgent;

                    WebClient client = new WebClient();
                    client.Headers.Add("X-CV-Authorization", session.GetAuthorizationHeader());
                    client.Headers.Add("User-Agent", userAgent);

                    byte[]  response   = client.UploadFile(url, filePath);
                    var     jsonString = System.Text.Encoding.Default.GetString(response);
                    dynamic dynObj     = JsonConvert.DeserializeObject(jsonString);
                    var     file       = dynObj[0];

                    String fileName       = file.name;
                    String fileDownloadId = file.fileDownloadId;
                    String mimeType       = file.mimeType;
                    int    fileSize       = file.filesize;

                    fileRecord.FilestoreFilestore = fileDownloadId;
                    fileRecord.Filesize           = fileSize;

                    UpdateFileInput  updateFileInput  = new UpdateFileInput(fileRecord, null);
                    UpdateFileResult updateFileResult = fileApi.UpdateFile(fileKey, updateFileInput);
                    if (updateFileResult.Hdr.Rc == 0)
                    {
                        return(updateFileResult.Updated);
                    }
                    else
                    {
                        throw new Exception("Error updating file. Rc=" + viewFileResult.Hdr.Rc);
                    }
                }
                else
                {
                    throw new Exception("Error getting file. Rc=" + viewFileResult.Hdr.Rc);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error uploading new version", ex);
            }
        }
Example #29
0
        public ShareFileItem createFile(FileInfo fileInfo, String title, String description, List <String> spaceKeys, Bitmap icon)
        {
            try
            {
                FileRecord fileRecord = VmosoFileUtils.uploadFile(session, fileInfo.FullName, title, description, true);

                if (spaceKeys != null)
                {
                    SpaceApi          spaceApi    = new SpaceApi(session.GetApiClient());
                    ShareObjectInput  shareInput  = new ShareObjectInput(null, spaceKeys, null);
                    ShareObjectResult shareResult = spaceApi.ShareObject(fileRecord.Key, shareInput);
                    if (shareResult.Hdr.Rc == 0)
                    {
                        FileApi        fileApi        = new FileApi(session.GetApiClient());
                        ViewFileResult viewFileResult = fileApi.ViewFile(fileRecord.Key);
                        if (viewFileResult.Hdr.Rc == 0)
                        {
                            fileRecord = viewFileResult.File;
                        }
                        else
                        {
                            throw new Exception("Vmoso error getting created link. Rc=" + viewFileResult.Hdr.Rc);
                        }
                    }
                    else
                    {
                        throw new Exception("Vmoso error sharing link. Rc=" + shareResult.Hdr.Rc);
                    }
                }

                ShareFileItem item = new ShareFileItem(fileRecord.Name, fileRecord.Description);
                item.Key      = fileRecord.Key;
                item.FileInfo = fileInfo;
                item.SetIcon(icon);
                item.Record = fileRecord;

                List <ShareSpace> itemSpaces = new List <ShareSpace>();
                foreach (DisplayRecord spaceDisplayRecord in fileRecord.Destinations)
                {
                    ShareSpace space = new ShareSpace(spaceDisplayRecord.Key, spaceDisplayRecord.DisplayName, null);
                    itemSpaces.Add(space);
                }

                item.Spaces = itemSpaces;
                return(item);
            } catch (Exception ex)
            {
                throw new Exception("Error creating file", ex);
            }
        }
Example #30
0
        static string RecognizeFromStorage(Configuration conf)
        {
            string name = "10.png";

            OcrApi  api     = new OcrApi(conf);
            FileApi fileApi = new FileApi(conf /* or AppSid & AppKey*/);

            fileApi.UploadFile(new UploadFileRequest(name, System.IO.File.OpenRead(name)));

            GetRecognizeDocumentRequest request = new GetRecognizeDocumentRequest(name);
            OCRResponse response = api.GetRecognizeDocument(request);

            return(response.Text);
        }