コード例 #1
0
        public async Task <FileInfoDTO> CreateAsync(CreateFileRequest file, Stream data)
        {
            if (!Directory.Exists(StorageFolderPath))
            {
                Directory.CreateDirectory(StorageFolderPath);
            }

            var fileInfoDto = FileMapper.ConvertToFileInfoDTO(file);

            var fileInfo = await _db.Files.CreateAsync(FileMapper.ConvertToFileInfo(fileInfoDto));

            var filePath = GetAbsoluteFilePath(fileInfo);


            if (!File.Exists(filePath))
            {
                using (var fileStream = File.Create(filePath))
                {
                    using (data)
                    {
                        if (data.CanSeek)
                        {
                            data.Seek(0, SeekOrigin.Begin);
                        }

                        await data.CopyToAsync(fileStream);
                    }
                }
                await _db.SaveAsync(); // don't move to other place.
            }
            return(await GetFileInfoAsync(fileInfo.Id));
        }
コード例 #2
0
        public Response CreateFile(CreateFileRequest createRequest)
        {
            var service  = CreateChanel();
            var response = service.Create(createRequest);

            return(response);
        }
コード例 #3
0
        private static async Task <PullRequest> CreatePullRequest(Comment comment)
        {
            // Create the Octokit client
            var github = new GitHubClient(new ProductHeaderValue("PostCommentToPullRequest"),
                                          new Octokit.Internal.InMemoryCredentialStore(new Credentials(config.GitHubToken)));

            // Get a reference to our GitHub repository
            var repoOwnerName = config.PullRequestRepository.Split('/');
            var repo          = await github.Repository.Get(repoOwnerName[0], repoOwnerName[1]);

            // Create a new branch from the default branch
            var defaultBranch = await github.Repository.Branch.Get(repo.Id, repo.DefaultBranch);

            var newBranch = await github.Git.Reference.Create(repo.Id, new NewReference($"refs/heads/comment-{comment.id}", defaultBranch.Commit.Sha));

            // Create a new file with the comments in it
            var fileRequest = new CreateFileRequest($"Comment by {comment.name} on {comment.post_id}", comment.ToYaml(), newBranch.Ref)
            {
                Committer = new Committer(comment.name, comment.email ?? config.CommentFallbackCommitEmail ?? "*****@*****.**", comment.date)
            };
            await github.Repository.Content.CreateFile(repo.Id, $"_data/comments/{comment.post_id}/{comment.id}.yml", fileRequest);

            // Create a pull request for the new branch and file
            return(await github.Repository.PullRequest.Create(repo.Id, new NewPullRequest(fileRequest.Message, newBranch.Ref, defaultBranch.Name)
            {
                Body = $"{comment.message}"
            }));
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: safern/corefxlab
    static async ValueTask <bool> CopyLocalFileToStorageFile(StorageClient client, string localFilePath, string storagePath)
    {
        // TODO (pri 3): make file i/o more efficient
        FileInfo fileInfo = new FileInfo(localFilePath);

        var             createRequest = new CreateFileRequest(storagePath, fileInfo.Length);
        StorageResponse response      = await client.SendRequest(createRequest).ConfigureAwait(false);

        if (response.StatusCode == 201)
        {
            using (var bytes = new FileStream(localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
            {
                var putRequest = new PutRangeRequest(storagePath, bytes);
                response = await client.SendRequest(putRequest).ConfigureAwait(false);

                if (response.StatusCode == 201)
                {
                    return(true);
                }
            }
        }

        Log.TraceEvent(TraceEventType.Error, 0, "Response Status Code {0}", response.StatusCode);
        return(false);
    }
コード例 #5
0
        private async static Task <StringBuilder> GetCrateFileRequestContent(string fileName)
        {
            CreateFileRequest request = new CreateFileRequest
            {
                Title    = fileName,
                MimeType = "text/plain",
                Parents  = new List <Parent>()
                {
                    new Parent {
                        Id = Config.VictorinaFolderId
                    }
                }
            };

            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.NullValueHandling = NullValueHandling.Ignore;
            string fileData = await JsonConvert.SerializeObjectAsync(request, Formatting.None, settings);

            StringBuilder requestContent = new StringBuilder();

            requestContent.Append("--" + Boundary + Environment.NewLine);
            requestContent.Append("Content-Type: " + "application/json" + Environment.NewLine);
            requestContent.Append(Environment.NewLine);
            requestContent.Append(fileData + Environment.NewLine);
            requestContent.Append("--" + Boundary + Environment.NewLine);
            requestContent.Append(Environment.NewLine);
            requestContent.Append(Environment.NewLine);
            requestContent.Append(fileName + Environment.NewLine);
            requestContent.Append("--" + Boundary + "--" + Environment.NewLine);
            requestContent.Append(Environment.NewLine);

            return(requestContent);
        }
コード例 #6
0
 public async Task <File> EditFile(int id, CreateFileRequest request)
 {
     return(await SendRequest <File>(
                $"downloads/files/{id}",
                HttpMethod.Post,
                request));
 }
コード例 #7
0
        private static async Task <PullRequest> CreateCommentAsPullRequest(Comment comment)
        {
            // Create the Octokit client
            var github = new GitHubClient(new ProductHeaderValue("PostCommentToPullRequest"),
                                          new Octokit.Internal.InMemoryCredentialStore(new Credentials(ConfigurationManager.AppSettings["GitHubToken"])));

            // Get a reference to our GitHub repository
            var repoOwnerName = ConfigurationManager.AppSettings["PullRequestRepository"].Split('/');
            var repo          = await github.Repository.Get(repoOwnerName[0], repoOwnerName[1]);

            // Create a new branch from the default branch
            var defaultBranch = await github.Repository.Branch.Get(repo.Id, repo.DefaultBranch);

            var newBranch = await github.Git.Reference.Create(repo.Id, new NewReference($"refs/heads/comment-{comment.id}", defaultBranch.Commit.Sha));

            // Create a new file with the comments in it
            var fileRequest = new CreateFileRequest($"Comment by {comment.name} on {comment.post_id}", new SerializerBuilder().Build().Serialize(comment), newBranch.Ref)
            {
                Committer = new Committer(comment.name, comment.email ?? ConfigurationManager.AppSettings["CommentFallbackCommitEmail"] ?? "*****@*****.**", comment.date)
            };
            await github.Repository.Content.CreateFile(repo.Id, $"_data/comments/{comment.post_id}/{comment.id}.yml", fileRequest);

            // Create a pull request for the new branch and file
            return(await github.Repository.PullRequest.Create(repo.Id, new NewPullRequest(fileRequest.Message, newBranch.Ref, defaultBranch.Name)
            {
                Body = $"avatar: <img src=\"{comment.avatar}\" width=\"64\" height=\"64\" />\n\n{comment.message}"
            }));
        }
コード例 #8
0
        public async Task AddComment(Comment comment, ModerationAnalysisReport report, KnownCommenterResponse knownCommenterResponse)
        {
            string yaml = CommentSerializer.SerializeToYaml(comment);

            var message = $"Add comment to '{comment.Slug}' by '{comment.Name}'";
            var path    = Path.Combine(_commentDataPath, comment.Slug, $"comment-{comment.Date.Ticks}.yml");
            var branch  = _branch;

            if (report.NeedsModeration)
            {
                branch = $"sc2g-{comment.Slug}-{comment.Date.Ticks}";
                await CreateNewBranch(branch);
            }

            var createFileRequest = new CreateFileRequest(message, yaml, branch);
            await _github.Repository.Content.CreateFile(_owner, _repo, path, createFileRequest);

            if (!knownCommenterResponse.IsKnownCommenter)
            {
                await CreateOrUpdateKnownCommentersFile(knownCommenterResponse, branch);
            }

            if (report.NeedsModeration)
            {
                var newPullRequest = new NewPullRequest(message, branch, _branch);
                newPullRequest.Body = report.ReasonForModeration;
                await _github.Repository.PullRequest.Create(_owner, _repo, newPullRequest);
            }
        }
コード例 #9
0
 public async Task <File> CreateFile(CreateFileRequest request)
 {
     return(await SendRequest <File>(
                $"downloads/files",
                HttpMethod.Post,
                request));
 }
コード例 #10
0
        public IActionResult AddNewFile()
        {
            var file          = Request.Form.Files[0];
            var detailsDecode = JObject.Parse(Request.Form["aditionalDetails"]);

            var folderName = Path.Combine("Resources", "AdditionalFiles");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
            var fullPath   = Path.Combine(pathToSave, file.FileName);

            if (file.Length > 0)
            {
                var dbPath = Path.Combine(folderName, file.FileName);

                using (var stream = System.IO.File.Create(fullPath))
                {
                    file.CopyTo(stream);
                }

                string referenceType     = detailsDecode["referenceType"].ToString();
                string referenceTypeName = detailsDecode["referenceTypeName"].ToString();

                var additionalFile = new CreateFileRequest
                {
                    Name              = file.FileName,
                    DbPath            = dbPath,
                    ReferenceType     = referenceType,
                    ReferenceTypeName = referenceTypeName
                };
                additionalFileRepository.Create(additionalFile.returnFile());
            }

            return(Ok(new ApiResponse("Added succesfully!")));
        }
コード例 #11
0
        public Response UpdateFile(CreateFileRequest updateRequest)
        {
            var service  = CreateChanel();
            var response = service.Update(updateRequest);

            return(response);
        }
コード例 #12
0
        public Response Update(CreateFileRequest request)
        {
            var fileTransferResponse = CheckFileRequest(request);

            if (fileTransferResponse.ResponseStatus != true)
            {
                return(fileTransferResponse);
            }
            CreateSyncFolder();
            var path = GetFullFilePath(request.FileName);

            try
            {
                Logger.Logger.Log($"About to update {path}");
                var stream = new MemoryStream(request.Content);
                SaveFileStream(path, stream);
                return(CreateResponse(request.FileName, "File was updated", true));
            }
            catch (Exception ex)
            {
                Logger.Logger.Log(
                    $"Exception while updating {path}, exception is {ex.Message}, inner exception is {ex.InnerException}");
                return(CreateResponse(request.FileName, ex.Message, false));
            }
        }
コード例 #13
0
ファイル: CommandExecutor.cs プロジェクト: thnetii/utils
        private async Task UploadRepositoryContent(
            RepositoryContentChangeTracker changeTracker, string path,
            string commitMessage, string sourceContentBase64,
            CancellationToken cancelToken)
        {
            RepositoryContentEntry targetEntry;

            try
            {
                targetEntry = await GetRepositoryContentEntry(changeTracker.Reference, path)
                              .ConfigureAwait(continueOnCapturedContext: false);
            }
            catch (NotFoundException) { targetEntry = null; }
            if (cancelToken.IsCancellationRequested)
            {
                return;
            }

            var(client, owner, name) = (
                GitHubClient.Repository.Content,
                changeTracker.Reference.RepositoryOwner,
                changeTracker.Reference.RepositoryName
                );
            Task <RepositoryContentChangeSet> changeSetTask;

            if (targetEntry is null)
            {
                var uploadOptions = new CreateFileRequest(
                    commitMessage,
                    sourceContentBase64,
                    null,
                    convertContentToBase64: false
                    );

                changeSetTask = client.CreateFile(
                    owner, name, path, uploadOptions);
            }
            else
            {
                UpdateFileRequest uploadOptions = new UpdateFileRequest(
                    commitMessage,
                    sourceContentBase64,
                    targetEntry.Leaf?.Sha,
                    null,
                    convertContentToBase64: false
                    );
                changeSetTask = client.UpdateFile(
                    owner, name, path, uploadOptions);
            }

            var changeSetResult = await changeSetTask.ConfigureAwait(false);

            changeTracker.Reference = new RepositoryReference
            {
                RepositoryOwner = owner,
                RepositoryName  = name,
                TreeReference   = changeSetResult.Commit.Sha
            };
        }
コード例 #14
0
        /// <summary>
        /// Creates a commit that creates a new file in a repository.
        /// </summary>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="path">The path to the file</param>
        /// <param name="request">Information about the file to create</param>
        /// <returns></returns>
        public IObservable<RepositoryContentChangeSet> CreateFile(string owner, string name, string path, CreateFileRequest request)
        {
            Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(path, "path");
            Ensure.ArgumentNotNull(request, "request");

            return _client.Repository.Content.CreateFile(owner, name, path, request).ToObservable();
        }
コード例 #15
0
        /// <summary>
        /// Creates an entity which is a file in a system.
        /// </summary>
        /// <param name="createFileRequest">The file parameter.</param>
        /// <returns>Success HTTP Status Code 201</returns>
        public async Task <HttpResponse <FileInfoResponse> > CreateFileInfoAsync(CreateFileRequest createFileRequest)
        {
            var headers            = RequestHeadersBuilder.GetDefaultHeaders().GetHeaderWithQbToken(this.quickbloxClient.Token);
            var createFileResponse = await HttpService.PostAsync <FileInfoResponse, CreateFileRequest>(this.quickbloxClient.ApiEndPoint,
                                                                                                       QuickbloxMethods.CreateFileMethod,
                                                                                                       createFileRequest,
                                                                                                       headers);

            return(createFileResponse);
        }
コード例 #16
0
        public async Task <ActionResult> CreateFileAsync([FromBody] CreateFileRequest createRequest)
        {
            var response = await _fileService.CreateAsync(createRequest.Name, createRequest.Content);

            if (response.HasError)
            {
                return(BadRequest());
            }
            return(Created(response.Result.Id, ToJsonObject(response.Result)));
        }
コード例 #17
0
ファイル: FileController.cs プロジェクト: hasmbly/SiUpin
 public async Task <IActionResult> Register([FromForm] CreateFileRequest request)
 {
     try
     {
         return(Ok(new Success(await Mediator.Send(request), "Successfully")));
     }
     catch (Exception exception)
     {
         return(StatusCode((int)HttpStatusCode.InternalServerError, new InternalServerError(exception.Message)));
     }
 }
コード例 #18
0
        private async Task <FileInfoDTO> GetFileInfo(SharepointPostImages image, int postId)
        {
            var fileRequest = new CreateFileRequest
            {
                Name        = postId.ToString() + image.Name,
                ContentType = image.ContentType,
                SizeKB      = Convert.ToInt32(image.file.Length)
            };

            return(await _fileService.CreateAsync(fileRequest, image.file));
        }
コード例 #19
0
ファイル: HiarcClient.cs プロジェクト: hiarcdb/hiarc
        public async Task <File> CreateFile(string filePath, Dictionary <string, object> metadata = null, string storageService = null, string asUserKey = null, string bearerToken = null, bool logToConsole = true)
        {
            using System.IO.Stream fileStream = System.IO.File.OpenRead(filePath);
            sw.Restart();
            var key      = GenerateKey("file");
            var fileName = System.IO.Path.GetFileName(filePath);

            var multipart = new MultipartFormDataContent();
            var sc        = new StreamContent(fileStream);

            sc.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            multipart.Add(sc, "file", fileName);

            var createFileRequest = new CreateFileRequest()
            {
                Key = key, Name = fileName, Description = "This is a brand new file", Metadata = metadata, StorageService = storageService
            };
            var jsonContent = JsonContent(createFileRequest);

            jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            multipart.Add(jsonContent, "request");

            var response = await Client(asUserKey, bearerToken).PostAsync("files", multipart);

            sw.Stop();
            if (response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync();

                var newFile = JsonSerializer.Deserialize <File>(body, jsonOptions);

                if (logToConsole)
                {
                    Console.WriteLine($"Created New File: {ToJson(newFile)}, Elapsed={sw.ElapsedMilliseconds}ms");
                }
                ;
                return(newFile);
            }
            else
            {
                try
                {
                    var body = await response.Content.ReadAsStringAsync();

                    var error = JsonSerializer.Deserialize <Error>(body, jsonOptions);
                    throw new Exception($"StatusCode: {response.StatusCode}, Message: {error.Message}");
                }
                catch
                {
                    throw new Exception($"Status Code: {response.StatusCode}");
                }
            }
        }
コード例 #20
0
    public IObjects Get(IObjects request)
    {
        CreateFileRequest t = (CreateFileRequest)request;

        CreateNewFile(t.newfile);
        // создали файл. нужо добавить права в файл прав
        WatchingFileRights wfr = new WatchingFileRights();

        wfr.Add(t.newfile, t.newrights);

        return(t);
    }
コード例 #21
0
        public async Task <ImageUploadResult> UploadPublicImage(byte[] imageBytes)
        {
            var imageUploadResult = new ImageUploadResult();

            var createFileRequest = new CreateFileRequest()
            {
                Blob = new BlobRequest()
                {
                    Name     = $"image_{Guid.NewGuid()}.jpeg",
                    IsPublic = true
                }
            };

            var createFileInfoResponse = await quickbloxClient.ContentClient.CreateFileInfoAsync(createFileRequest);

            if (createFileInfoResponse.StatusCode != HttpStatusCode.Created)
            {
                return(null);
            }

            imageUploadResult.BlodId = createFileInfoResponse.Result.Blob.Id;

            var uploadFileRequest = new UploadFileRequest
            {
                BlobObjectAccess = createFileInfoResponse.Result.Blob.BlobObjectAccess,
                FileContent      = new BytesContent()
                {
                    Bytes       = imageBytes,
                    ContentType = "image/jpg",
                }
            };

            var uploadFileResponse = await quickbloxClient.ContentClient.FileUploadAsync(uploadFileRequest);

            if (uploadFileResponse.StatusCode != HttpStatusCode.Created)
            {
                return(null);
            }

            imageUploadResult.Url = uploadFileResponse.Result.Location;

            var blobUploadCompleteRequest = new BlobUploadCompleteRequest
            {
                BlobUploadSize = new BlobUploadSize()
                {
                    Size = (uint)imageBytes.Length
                }
            };
            var response = await quickbloxClient.ContentClient.FileUploadCompleteAsync(createFileInfoResponse.Result.Blob.Id, blobUploadCompleteRequest);

            return(imageUploadResult);
        }
コード例 #22
0
        public async Task FileUploadSuccessTest()
        {
            var settings = new CreateFileRequest()
            {
                Blob = new BlobRequest()
                {
                    Name = String.Format("museum_{0}.jpeg", Guid.NewGuid()),
                }
            };

            var createFileInfoResponse = await this.client.ContentClient.CreateFileInfoAsync(settings);

            Assert.AreEqual(createFileInfoResponse.StatusCode, HttpStatusCode.Created);

            var uploadFileRequest = new UploadFileRequest();

            uploadFileRequest.BlobObjectAccess = createFileInfoResponse.Result.Blob.BlobObjectAccess;

            var uri         = new Uri("ms-appx:///Modules/ContentModule/Assets/1.jpg");
            var storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);

            var stream = await storageFile.OpenReadAsync();

            var bytes = new byte[stream.Size];

            using (var dataReader = new DataReader(stream))
            {
                await dataReader.LoadAsync((uint)stream.Size);

                dataReader.ReadBytes(bytes);
            }

            uploadFileRequest.FileContent = new BytesContent()
            {
                Bytes       = bytes,
                ContentType = "image/jpg",
            };

            var uploadFileResponse = await this.client.ContentClient.FileUploadAsync(uploadFileRequest);

            Assert.AreEqual(uploadFileResponse.StatusCode, HttpStatusCode.Created);

            var blobUploadCompleteRequest = new BlobUploadCompleteRequest();

            blobUploadCompleteRequest.BlobUploadSize = new BlobUploadSize()
            {
                Size = (uint)bytes.Length
            };
            var uploadFileCompleteResponse = await this.client.ContentClient.FileUploadCompleteAsync(createFileInfoResponse.Result.Blob.Id, blobUploadCompleteRequest);

            Assert.AreEqual(uploadFileCompleteResponse.StatusCode, HttpStatusCode.OK);
        }
コード例 #23
0
        public async Task <int?> UploadPrivateImageAsync(byte[] imageBytes)
        {
            var createFileRequest = new CreateFileRequest()
            {
                Blob = new BlobRequest()
                {
                    Name     = String.Format("image_{0}.jpeg", Guid.NewGuid()),
                    IsPublic = false
                }
            };

            var createFileInfoResponse = await client.ContentClient.CreateFileInfoAsync(createFileRequest);

            if (await HandleResponse(createFileInfoResponse, HttpStatusCode.Created))
            {
                var uploadFileRequest = new UploadFileRequest
                {
                    BlobObjectAccess = createFileInfoResponse.Result.Blob.BlobObjectAccess,
                    FileContent      = new BytesContent()
                    {
                        Bytes       = imageBytes,
                        ContentType = "image/jpg",
                    }
                };

                var uploadFileResponse = await client.ContentClient.FileUploadAsync(uploadFileRequest);

                if (!await HandleResponse(createFileInfoResponse, HttpStatusCode.Created))
                {
                    return(null);
                }

                var blobUploadCompleteRequest = new BlobUploadCompleteRequest
                {
                    BlobUploadSize = new BlobUploadSize()
                    {
                        Size = (uint)imageBytes.Length
                    }
                };
                var response = await client.ContentClient.FileUploadCompleteAsync(createFileInfoResponse.Result.Blob.Id, blobUploadCompleteRequest);

                if (!await HandleResponse(response, HttpStatusCode.OK))
                {
                    return(null);
                }
                return(createFileInfoResponse.Result.Blob.Id);
            }
            else
            {
                return(null);
            }
        }
コード例 #24
0
ファイル: GitController.cs プロジェクト: fungler/SDDBackend
        public static async Task createFile(string pushMessage, string fileContent, string path, string repo)
        {
            var access_token = System.Environment.GetEnvironmentVariable("SCD_Access");
            var tokenAuth    = new Credentials(access_token);
            var client       = new GitHubClient(new ProductHeaderValue("marshmallouws"));

            client.Credentials = tokenAuth;

            var createFileRequest  = new CreateFileRequest(pushMessage, fileContent);
            var repositoryResponse = await client.Repository.Get("marshmallouws", repo);

            await client.Repository.Content.CreateFile(repositoryResponse.Id, path, createFileRequest);
        }
コード例 #25
0
ファイル: FileMapper.cs プロジェクト: boolbinos/InTouch
 public static FileInfoDTO ConvertToFileInfoDTO(CreateFileRequest createRequest)
 {
     if (createRequest == null)
     {
         throw new ArgumentNullException();
     }
     return(new FileInfoDTO
     {
         Name = createRequest.Name,
         Id = createRequest.Id,
         SizeKB = createRequest.SizeKB,
         ContentType = createRequest.ContentType
     });
 }
コード例 #26
0
        public async Task CreateFileInfoSuccessTest()
        {
            var settings = new CreateFileRequest()
            {
                Blob = new BlobRequest()
                {
                    Name = "museum.jpeg",
                }
            };

            var createFileInfoResponse = await this.client.ContentClient.CreateFileInfoAsync(settings);

            Assert.AreEqual(createFileInfoResponse.StatusCode, HttpStatusCode.Created);
        }
コード例 #27
0
        private CreateFileRequest GetCreateFileRequest(FileActionData data)
        {
            var fileFullName  = $"{_syncFolder}\\{data.FileName}";
            var bytes         = File.ReadAllBytes(fileFullName);
            var checkSum      = _fileService.CalculateCheckSum(bytes);
            var createRequest = new CreateFileRequest
            {
                FileName = data.FileName,
                Content  = bytes,
                CheckSum = checkSum
            };

            return(createRequest);
        }
コード例 #28
0
ファイル: FileMapper.cs プロジェクト: boolbinos/InTouch
        public static CreateFileRequest ConvertToCreateFileRequest(FileInfoDTO file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }
            var createFileRequest = new CreateFileRequest
            {
                ContentType = file.ContentType,
                Name        = file.Name,
                SizeKB      = file.SizeKB
            };

            return(createFileRequest);
        }
コード例 #29
0
ファイル: GitController.cs プロジェクト: fungler/SDDBackend
        public static async Task CopyFile(string instName, string oldName, string repo, string fileContent)
        {
            var pushMessage  = "Copy: " + oldName + " as " + instName;
            var path         = "./installations/" + instName + "/" + instName + ".json";
            var access_token = System.Environment.GetEnvironmentVariable("SCD_Access");
            var tokenAuth    = new Credentials(access_token);
            var client       = new GitHubClient(new ProductHeaderValue("marshmallouws"));

            client.Credentials = tokenAuth;

            var createFileRequest  = new CreateFileRequest(pushMessage, fileContent);
            var repositoryResponse = await client.Repository.Get("marshmallouws", repo);

            await client.Repository.Content.CreateFile(repositoryResponse.Id, path, createFileRequest);
        }
コード例 #30
0
        public async Task <CreateFileResponse> Post(CreateFileRequest request)
        {
            if (!await recaptchaVerifier.VerifyAsync(request.RecaptchaToken, Request.RemoteIp))
            {
                throw new InvalidOperationException($"An error occurred validating the parameters.");
            }

            var jobId    = Guid.NewGuid();
            var settings = mapper.Map <CreateFileRequest, Settings>(request);
            await jobScheduler.ScheduleJob <FileCreator, Settings>(jobId, settings);

            return(new CreateFileResponse {
                JobId = jobId
            });
        }
コード例 #31
0
        /// <inheritdoc />
        public async Task <RepositoryContentChangeSet> CreateFileAsync(
            string organizationName,
            string repositoryName,
            string path,
            CreateFileRequest createFileRequest)
        {
            ArgumentCheck.StringIsNotNullOrWhiteSpace(organizationName, nameof(organizationName));
            ArgumentCheck.StringIsNotNullOrWhiteSpace(repositoryName, nameof(repositoryName));
            ArgumentCheck.StringIsNotNullOrWhiteSpace(path, nameof(path));

            return(await gitHubClient.Repository.Content.CreateFile(
                       organizationName,
                       repositoryName,
                       path,
                       createFileRequest));
        }
コード例 #32
0
        /// <summary>
        /// Creates a commit that creates a new file in a repository.
        /// </summary>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="path">The path to the file</param>
        /// <param name="request">Information about the file to create</param>
        public IObservable<RepositoryContentChangeSet> CreateFile(int repositoryId, string path, CreateFileRequest request)
        {
            Ensure.ArgumentNotNullOrEmptyString(path, "path");
            Ensure.ArgumentNotNull(request, "request");

            return _client.Repository.Content.CreateFile(repositoryId, path, request).ToObservable();
        }
コード例 #33
0
		public async Task<int?> UploadPrivateImageAsync(byte[] imageBytes)
		{
			var createFileRequest = new CreateFileRequest()
			{
				Blob = new BlobRequest()
				{
					Name = String.Format("image_{0}.jpeg", Guid.NewGuid()),
					IsPublic = false
				}
			};

			var createFileInfoResponse = await client.ContentClient.CreateFileInfoAsync(createFileRequest);

			if (await HandleResponse (createFileInfoResponse, HttpStatusCode.Created)) {
				var uploadFileRequest = new UploadFileRequest {
					BlobObjectAccess = createFileInfoResponse.Result.Blob.BlobObjectAccess,
					FileContent = new BytesContent () {
						Bytes = imageBytes,
						ContentType = "image/jpg",
					}
				};

				var uploadFileResponse = await client.ContentClient.FileUploadAsync (uploadFileRequest);

				if (!await HandleResponse (createFileInfoResponse, HttpStatusCode.Created))
					return null;

				var blobUploadCompleteRequest = new BlobUploadCompleteRequest {
					BlobUploadSize = new BlobUploadSize () { Size = (uint)imageBytes.Length }
				};
				var response = await client.ContentClient.FileUploadCompleteAsync (createFileInfoResponse.Result.Blob.Id, blobUploadCompleteRequest);
				if (!await HandleResponse (response, HttpStatusCode.OK))
					return null;
				return createFileInfoResponse.Result.Blob.Id;
			} else {
				return null;
			}
		}