public async Task <IActionResult> DeleteFile([FromBody] FileObject file) { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); await FilesApi.DeleteFileAsync(accessToken, tenantId, file.Id ?? Guid.Empty); return(Redirect("/")); }
public void FileDeleteShouldCallCorrectEndpoint() { var requestHandlerMock = PathAndExecRequestMock <ResponseBase>("/files.delete?file=foo"); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.Delete("foo"); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void FileInfoShouldCallCorrectEndpoint() { var requestHandlerMock = PathAndExecRequestMock <FileResponse>("/files.info?file=foo&count=30&page=1"); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.Info("foo", 30); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void FileInfoShouldCallCorrectEndpoint() { var requestHandlerMock = PathAndExecRequestMock<FileResponse>("/files.info?file=foo&count=30&page=1"); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.Info("foo", 30); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void FileDeleteShouldCallCorrectEndpoint() { var requestHandlerMock = PathAndExecRequestMock<ResponseBase>("/files.delete?file=foo"); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.Delete("foo"); requestHandlerMock.Verify(); Assert.NotNull(result); }
public async Task <IActionResult> GetAssociation(Guid id) { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); var response = await FilesApi.GetFileAssociationsAsync(accessToken, tenantId, id); return(Ok(response)); }
public async Task <IActionResult> CreateAssociation([FromBody] Association association) { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); await FilesApi.CreateFileAssociationAsync(accessToken, tenantId, association.FileId ?? Guid.Empty, association); return(Redirect("/")); }
public async Task <IActionResult> GetFiles() { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); var response = await FilesApi.GetFilesAsync(accessToken, tenantId); var filesItems = response.Items; return(Ok(filesItems)); }
public void ParsePathParameters() { var path = "/users/{id}.json"; var parameters = new Dictionary <string, object>() { { "id", 1234 }, }; var resultPath = FilesApi.ParsePathParameters(path, parameters); Assert.AreEqual("/users/1234.json", resultPath); }
public async Task <IActionResult> CreateFolder([FromBody] XeroFolder createFolder) { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); var folder = new Folder(); folder.Name = createFolder.Name; var test = await FilesApi.CreateFolderAsync(accessToken, tenantId, folder); return(Redirect("/")); }
public async Task <IActionResult> GetFile(Guid id) { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); var response = await FilesApi.GetFileContentAsync(accessToken, tenantId, id); using (var memoryStream = new MemoryStream()) { response.CopyTo(memoryStream); return(Ok(memoryStream.ToArray())); } }
public async Task <IActionResult> GetConnection() { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = GetTenantId(accessToken); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); List <Connection> connections = await client.GetFromJsonAsync <List <Connection> >("https://api.xero.com/connections"); return(Ok(connections.FirstOrDefault())); } }
public static void DownloadFile(UserInfo userInfo, QueueItemAttachment attachment, string directoryPath, int count = 0) { var apiInstance = GetAttachmentsApiInstance(userInfo.Token, userInfo.ServerUrl); try { var response = apiInstance.ExportQueueItemAttachmentAsyncWithHttpInfo(attachment.Id.ToString(), userInfo.ApiVersion, userInfo.OrganizationId, attachment.QueueItemId.ToString()).Result; string value; var headers = response.Headers.TryGetValue("Content-Disposition", out value); string fileName; if (headers == true) { string[] valueArray = value.Split('='); string[] fileNameArray = valueArray[1].Split(';'); fileName = fileNameArray[0]; } else { var fileId = attachment.FileId; var fileApiInstance = new FilesApi(userInfo.ServerUrl); fileApiInstance.Configuration.AccessToken = userInfo.Token; var driveApiInstance = new DrivesApi(userInfo.ServerUrl); driveApiInstance.Configuration.AccessToken = userInfo.Token; string filter = "IsDefault eq true"; var driveResponse = driveApiInstance.ApiVapiVersionStorageDrivesGetAsyncWithHttpInfo(userInfo.ApiVersion, userInfo.OrganizationId, filter).Result.Data.Items.FirstOrDefault(); var fileResponse = fileApiInstance.GetFileFolderAsyncWithHttpInfo(attachment.FileId.ToString(), userInfo.ApiVersion, userInfo.OrganizationId, driveResponse.Id.ToString()).Result.Data; fileName = fileResponse.Name; } var data = response.Data; byte[] fileArray = data.ToArray(); System.IO.File.WriteAllBytes(SystemFile.Path.Combine(directoryPath, fileName), fileArray); } catch (Exception ex) { if (ex.GetType().GetProperty("ErrorCode").GetValue(ex, null).ToString() == "401" && count < 2) { UtilityMethods.RefreshToken(userInfo); count++; DownloadFile(userInfo, attachment, directoryPath, count); } else if (ex.Message != "One or more errors occurred.") { throw new InvalidOperationException("Exception when calling QueueItemAttachmentsApi.ExportQueueItemAttachment: " + ex.Message); } else { throw new InvalidOperationException(ex.InnerException.Message); } } }
/// <summary> /// TODO: Добавить DI. /// </summary> static void Main(string[] args) { IConnectionStateManager connectionStateManager = new ConnectionStateManager(); IFileManager fileManager = new FileManager(new FileSystemService()); var apiController = new ApiController(); var settingsManager = new SettingsManager(); ISyncTableDataBase syncDb = new SyncTableDataBase(); IUserTableDataBase userDb = new UserTableDataBase(); var telegramService = new TelegramService(settingsManager.Settings.Token, settingsManager.Settings.Telegram_id); telegramService.Configure("/clean_folders", "clean empty folders", () => { var ls = userDb.GetAvailableFolders(); var removedList = fileManager.RemoveEmptyDirectories(ls); var sb = new StringBuilder(); sb.AppendLine("Removed dictionaries:"); sb.AppendJoin(Environment.NewLine, removedList); SendToTelegram(sb.ToString()); }); var syncModule = new CoreModule(fileManager, syncDb, connectionStateManager, userDb); syncModule.Initialize(apiController); syncModule.SendMessage += (o, s) => SendToTelegram(s); var attachModule = new FilesApi(new FilesService(connectionStateManager, syncDb), connectionStateManager); attachModule.Initialize(apiController); attachModule.SendMessage += (o, s) => SendToTelegram(s); var configModule = new ConfigurationModule(userDb, syncDb); configModule.Initialize(apiController); configModule.SendMessage += (o, s) => SendToTelegram(s); var ws = new WsService(connectionStateManager, apiController, IPAddress.Parse(settingsManager.Settings.IpAddress), settingsManager.Settings.HttpPort, settingsManager.Settings.HttpsPort); ws.Start(); void SendToTelegram(string message) { telegramService.SendTextMessageAsync(message); } // TODO: Добавить CancellationToken Console.ReadKey(true); ws.Stop(); }
public async Task <IActionResult> UploadFile([FromBody] XeroUpload file) { var FilesApi = new FilesApi(); var accessToken = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty); var tenantId = await GetTenantId(accessToken); if (file.FolderId == null || file.FolderId == Guid.Empty) { await FilesApi.UploadFileAsync(accessToken, tenantId, file.FileContent, file.FileName, file.FileName, file.ContentType); } else { await FilesApi.UploadFileToFolderAsync(accessToken, tenantId, file.FolderId ?? Guid.Empty, file.FileContent, file.FileName, file.FileName, file.ContentType); } return(Redirect("/")); }
public void FileListShouldCallCorrectEndpoint() { var requestHandlerMock = ExecRequestMock<FilesResponse>("/files.list"); var request = new FilesListRequest { Types = "all" }; requestHandlerMock.Setup(r => r.BuildRequestParams(request)) .Returns<Dictionary<string, string>>(null) .Verifiable(); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.List(request); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void FileListShouldCallCorrectEndpoint() { var requestHandlerMock = ExecRequestMock <FilesResponse>("/files.list"); var request = new FilesListRequest { Types = "all" }; requestHandlerMock.Setup(r => r.BuildRequestParams(request)) .Returns <Dictionary <string, string> >(null) .Verifiable(); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.List(request); requestHandlerMock.Verify(); Assert.NotNull(result); }
public static void DownloadFileAsset(string token, string serverUrl, string organizationId, SDKAsset asset, string directoryPath, string apiVersion) { var apiInstance = GetApiInstance(token, serverUrl); try { var response = apiInstance.ExportAssetAsyncWithHttpInfo(asset.Id.ToString(), apiVersion, organizationId).Result; string value; var headers = response.Headers.TryGetValue("Content-Disposition", out value); string fileName; if (headers == true) { string[] valueArray = value.Split('='); string[] fileNameArray = valueArray[1].Split(';'); fileName = fileNameArray[0]; } else { var fileId = asset.FileId; var fileApiInstance = new FilesApi(serverUrl); fileApiInstance.Configuration.AccessToken = token; var driveApiInstance = new DrivesApi(serverUrl); driveApiInstance.Configuration.AccessToken = token; string filter = "IsDefault eq true"; var driveResponse = driveApiInstance.ApiVapiVersionStorageDrivesGetAsyncWithHttpInfo(apiVersion, organizationId, filter).Result.Data.Items.FirstOrDefault(); var fileResponse = fileApiInstance.GetFileFolderAsyncWithHttpInfo(asset.FileId.ToString(), apiVersion, organizationId, driveResponse.Id.ToString()).Result.Data; fileName = fileResponse.Name; } MemoryStream data = response.Data; byte[] file = data.ToArray(); IOFile.WriteAllBytes(Path.Combine(directoryPath, fileName), file); } catch (Exception ex) { if (ex.Message != "One or more errors occurred.") { throw new InvalidOperationException("Exception when calling AssetsApi.ExportAsset: " + ex.Message); } else { throw new InvalidOperationException(ex.InnerException.Message); } } }
public void FileUploadShouldCallCorrectEndpoint() { var requestHandlerMock = ExecRequestMock<FileResponse>("/files.upload"); var request = new FileUploadRequest { Filename = "hello.txt", FileData = Encoding.ASCII.GetBytes("hello world") }; requestHandlerMock.Setup(r => r.BuildRequestParams(request)) .Returns<Dictionary<string, string>>(null) .Verifiable(); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.Upload(request); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void FileUploadShouldCallCorrectEndpoint() { var requestHandlerMock = ExecRequestMock <FileResponse>("/files.upload"); var request = new FileUploadRequest { Filename = "hello.txt", FileData = Encoding.ASCII.GetBytes("hello world") }; requestHandlerMock.Setup(r => r.BuildRequestParams(request)) .Returns <Dictionary <string, string> >(null) .Verifiable(); var subject = new FilesApi(requestHandlerMock.Object); var result = subject.Upload(request); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void Init() { instance = new FilesApi(); }
public void Startup(IContext context, IService service) { ConnectionString = context.Environment.ConnectionString; DataApi = context.DataApi; AdminApi = context.AdminApi; FilesApi = context.FilesApi; Dao = new Dao(ConnectionString, DataApi); PollDao = new PollDao(ConnectionString, DataApi); ItemDao = new ItemDao(ConnectionString, DataApi); LogDao = new LogDao(ConnectionString, DataApi); FieldDao = new FieldDao(ConnectionString, DataApi); FieldItemDao = new FieldItemDao(ConnectionString, DataApi); service .AddContentLinks(new List <HyperLink> { //new PluginContentLink //{ // Text = "编辑投票", // Href = "http://localhost:3000?pageType=edit_items" //}, //new PluginContentLink //{ // Text = "查看投票", // Href = "http://localhost:3000?pageType=view_items" //} new HyperLink { Text = "编辑投票", NavigateUrl = "build/index.html" }, new HyperLink { Text = "查看投票", NavigateUrl = $"{nameof(PageResults)}.aspx" } }) .AddDatabaseTable(PollDao.TableName, PollDao.Columns) .AddDatabaseTable(ItemDao.TableName, ItemDao.Columns) .AddDatabaseTable(LogDao.TableName, LogDao.Columns) .AddDatabaseTable(FieldDao.TableName, FieldDao.Columns) .AddDatabaseTable(FieldItemDao.TableName, FieldItemDao.Columns) .AddStlElementParser(StlPoll.ElementName, StlPoll.Parse) ; service.ContentTranslateCompleted += (sender, args) => { var pollInfo = PollDao.GetPollInfo(args.SiteId, args.ChannelId, args.ContentId); if (pollInfo == null) { return; } pollInfo.PublishmentSystemId = args.TargetSiteId; pollInfo.ChannelId = args.TargetChannelId; pollInfo.ContentId = args.TargetContentId; pollInfo.TimeToStart = DateTime.Now; pollInfo.TimeToEnd = DateTime.Now.AddYears(1); PollDao.Insert(pollInfo); }; service.ContentDeleteCompleted += (sender, args) => { PollDao.Delete(args.SiteId, args.ChannelId, args.ContentId); }; service.ApiGet += (sender, args) => { var request = args.Request; if (!string.IsNullOrEmpty(args.Name) && !string.IsNullOrEmpty(args.Id)) { if (args.Name == "code") { var response = new HttpResponseMessage(); var random = new Random(); var validateCode = ""; char[] s = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; for (var i = 0; i < 4; i++) { validateCode += s[random.Next(0, s.Length)].ToString(); } var validateimage = new Bitmap(75, 25, PixelFormat.Format32bppRgb); var colors = Utils.Colors[random.Next(0, 5)]; var g = Graphics.FromImage(validateimage); g.FillRectangle(new SolidBrush(Color.FromArgb(240, 243, 248)), 0, 0, 100, 100); //矩形框 g.DrawString(validateCode, new Font(FontFamily.GenericSerif, 18, FontStyle.Bold | FontStyle.Italic), new SolidBrush(colors), new PointF(10, 0)); //字体/颜色 for (var i = 0; i < 100; i++) { var x = random.Next(validateimage.Width); var y = random.Next(validateimage.Height); validateimage.SetPixel(x, y, Color.FromArgb(random.Next())); } g.Save(); var ms = new MemoryStream(); validateimage.Save(ms, ImageFormat.Png); request.SetCookie("ss-poll:" + args.Id, validateCode, DateTime.Now.AddDays(1)); response.Content = new ByteArrayContent(ms.ToArray()); response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); response.StatusCode = HttpStatusCode.OK; return(response); } if (args.Name == "logs") { var limit = request.GetQueryInt("limit"); var offset = request.GetQueryInt("offset"); var pollId = Convert.ToInt32(args.Id); var totalCount = LogDao.GetCount(pollId); var logs = LogDao.GetPollLogInfoList(pollId, totalCount, limit, offset); return(new { Logs = logs, TotalCount = totalCount }); } } if (string.IsNullOrEmpty(args.Name) && string.IsNullOrEmpty(args.Id)) { var siteId = request.GetQueryInt("siteId"); var channelId = request.GetQueryInt("channelId"); var contentId = request.GetQueryInt("contentId"); var pollInfo = PollDao.GetPollInfo(siteId, channelId, contentId); if (pollInfo == null) { pollInfo = new PollInfo { PublishmentSystemId = siteId, ChannelId = channelId, ContentId = contentId, IsImage = true, IsUrl = false, IsTimeout = false, IsCheckbox = true }; pollInfo.Id = PollDao.Insert(pollInfo); } var itemInfoList = ItemDao.GetItemInfoList(pollInfo.Id, out int totalCount); return(new { Poll = pollInfo, Items = itemInfoList, TotalCount = totalCount }); } throw new Exception("请求的资源不在服务器上"); }; service.ApiDelete += (sender, args) => { if (!string.IsNullOrEmpty(args.Name) && !string.IsNullOrEmpty(args.Id) && args.Name == "item") { var itemId = Convert.ToInt32(args.Id); ItemDao.Delete(itemId); return(new {}); } throw new Exception("请求的资源不在服务器上"); }; service.ApiPost += (sender, args) => { var request = args.Request; if (!string.IsNullOrEmpty(args.Name) && !string.IsNullOrEmpty(args.Id)) { if (Utils.EqualsIgnoreCase(args.Name, nameof(StlPoll.ApiSubmit))) { return(StlPoll.ApiSubmit(request, args.Id)); } } if (!string.IsNullOrEmpty(args.Name)) { var siteId = request.GetQueryInt("siteId"); if (args.Name.ToLower() == "item") { var itemInfo = new ItemInfo { PollId = request.GetPostInt("pollId"), Title = request.GetPostString("title"), SubTitle = request.GetPostString("subTitle"), ImageUrl = request.GetPostString("imageUrl"), LinkUrl = request.GetPostString("linkUrl"), Count = request.GetPostInt("count") }; itemInfo.Id = ItemDao.Insert(itemInfo); return(itemInfo); } if (args.Name.ToLower() == "image") { var errorMessage = string.Empty; var imageUrl = string.Empty; try { if (request.HttpRequest.Files.Count > 0) { var postedFile = request.HttpRequest.Files[0]; var filePath = postedFile.FileName; var fileExtName = Path.GetExtension(filePath).ToLower(); var localFilePath = FilesApi.GetUploadFilePath(siteId, filePath); if (fileExtName != ".jpg" && fileExtName != ".png") { errorMessage = "上传图片格式不正确!"; } else { postedFile.SaveAs(localFilePath); imageUrl = FilesApi.GetSiteUrlByFilePath(localFilePath); } } } catch (Exception ex) { errorMessage = ex.Message; } if (!string.IsNullOrEmpty(errorMessage)) { throw new Exception(errorMessage); } return(imageUrl); } } throw new Exception("请求的资源不在服务器上"); }; service.ApiPut += (sender, args) => { var request = args.Request; if (!string.IsNullOrEmpty(args.Name) && !string.IsNullOrEmpty(args.Id)) { var pollId = Convert.ToInt32(args.Id); //if (name.ToLower() == "poll") //{ // var pollInfo = Main.PollDao.GetPollInfo(pollId); // pollInfo.IsImage = context.GetPostBool("isImage"); // pollInfo.IsUrl = context.GetPostBool("isUrl"); // pollInfo.IsTimeout = context.GetPostBool("isTimeout"); // pollInfo.IsCheckbox = context.GetPostBool("isCheckbox"); // pollInfo.TimeToStart = Convert.ToDateTime(context.GetPostString("timeToStart")); // pollInfo.TimeToEnd = Convert.ToDateTime(context.GetPostString("timeToEnd")); // pollInfo.CheckboxMin = context.GetPostInt("checkboxMin"); // pollInfo.CheckboxMax = context.GetPostInt("checkboxMax"); // pollInfo.IsProfile = context.GetPostBool("isProfile"); // pollInfo.IsResult = context.GetPostBool("isResult"); // Main.PollDao.Update(pollInfo); // return pollInfo; //} if (args.Name.ToLower() == "item") { var itemInfo = ItemDao.GetItemInfo(pollId); itemInfo.Title = request.GetPostString("title"); itemInfo.SubTitle = request.GetPostString("subTitle"); itemInfo.ImageUrl = request.GetPostString("imageUrl"); itemInfo.LinkUrl = request.GetPostString("linkUrl"); itemInfo.Count = request.GetPostInt("count"); ItemDao.Update(itemInfo); return(itemInfo); } } throw new Exception("请求的资源不在服务器上"); }; }
public FilesApiTests() { instance = new FilesApi(); }