示例#1
9
        public static void upload(String content, String filename, byte[] file, Action<RestResponse> callback)
        {
            RestClient client = WbtoApi.GetClient();

            RestRequest request = new RestRequest("/api/upload.json", Method.POST);
            request.AddParameter("source", Constants.SOURCE);
            request.AddParameter("content", content);
            request.AddFile("file", file, filename);

            client.ExecuteAsync(request, callback);
        }
		/// <summary>
		/// Add log to server
		/// </summary>
		/// <param name="param"></param>
		public void AddLog(LogParameter param)
		{
			var request = new RestRequest("/api/v1/add_log", Method.POST)
			{
				AlwaysMultipartFormData = true
			};
			request.AddHeader("Content-Type", "multipart/form-data");
			if (param.Type.HasValue)
				request.AddParameter("type", LogTypeExt.DisplayName(param.Type.Value)); // adds to POST or URL querystring based on Method
			if (param.UserId != null)
				request.AddParameter("user_id", param.UserId);
			if (param.FilePath != null)
				request.AddFile("image_file", param.FilePath);
			client.Execute(request);
		}
        private string ExecuteJobRequest(RestClient client)
        {
            var req = new RestRequest(@"1/job", Method.POST);
            req.AlwaysMultipartFormData = true;

            req.AddParameter("apikey", ApiKey);

            req.AddParameter("job", JsonConvert.SerializeObject(_batch));

            foreach (var v in _files)
            {
                req.AddFile(v.Key, v.Value);
            }

            string resp = null;
            client.ExecuteAsync(req, response => { resp = response.Content; });

            DateTime timeoutTime = DateTime.Now + TimeoutSpan;
            while (string.IsNullOrEmpty(resp) && DateTime.Now < timeoutTime)
            {
                System.Threading.Thread.Sleep(1000);
            }

            if (resp == null)
            {
                throw new TimeoutException("Initial job request timed out");
            }

            return resp;
        }
示例#4
1
        public static RestRequest GetUploadRequest(string filename)
        {
            var request = new RestRequest("/path/data/", Method.POST);
            request.AddFile("file", filename);

            return request;
        }
        public void UploadFile(string path, string projectName, MediaItem mediaItem)
        {
            var fullPath = path + mediaItem.Filename;
            var request = new RestRequest("UploadMediaItem");
            request.AddParameter("path", mediaItem.Filename);

            request.AddParameter("project", projectName);

            request.AddFile(mediaItem.Filename, fullPath);
            var res=Client.Post(request);
        }
示例#6
0
        /// <summary>
        /// Uploads a file, if the request fails this overload will delete the note record
        /// </summary>
        /// <param name="module">Notes</param>
        /// <param name="id">Record ID</param>
        /// <param name="filePath">Path to file on local disk</param>
        /// <param name="deleteOnFailure">Bool: deletes record if upload fails</param>
        /// <returns>Bool</returns>
        public bool UploadFile(string module, string id, string filePath, bool deleteOnFailure)
        {
            var request = new RestRequest("{module}/{id}/file/filename", Method.POST);
            request.AddUrlSegment("module", module);
            request.AddUrlSegment("id", id);

            request.AddParameter("format", "sugar-html-json");
            request.AddParameter("delete_if_fails", deleteOnFailure);

            if (deleteOnFailure)
            {
                request.AddParameter("oauth_token", Token);
            }

            if (!File.Exists(filePath))
            {
                //@todo create a SugarFileException class
                throw new SugarException("Can not locate file path. Path attempted = " + filePath);
            }

            request.AddFile("filename", filePath);//?

            FileUploadResponse response = Execute<FileUploadResponse>(request);

            return ! string.IsNullOrEmpty(response.filename.name);
        }
        /*
         * This method is used to create  or POST the document for a given user in the SignNow Application
         */
        public Document Create(Oauth2Token token, Document documentPath)
        {
            Document document = null;
            try
            {
                string requestBody = JsonConvert.SerializeObject(documentPath.FilePath, Formatting.Indented);
            var client = new RestClient();
            client.BaseUrl = config.GetApiBase();

            var request = new RestRequest("/document", Method.POST)
                    .AddHeader("Accept", "application/json")
                    .AddHeader("Authorization", "Bearer " + token.AccessToken)
                    .AddHeader("Content-Type","multipart/form-data");
                request.AddFile("file", documentPath.FilePath);

            var httpResponse = client.Execute(request);
       
            string json = httpResponse.Content.ToString();
            document = JsonConvert.DeserializeObject<Document>(json);
            }
            catch(Exception ex)
            {
                Console.WriteLine(string.Format("Exception: {0}", ex.Message));
                throw;
            }
            return document;
        }
示例#8
0
        public PonyShotsResponse UploadScreenshot(string shotPath)
        {
            RestClient restClient = new RestClient(UploadUrl);
            RestRequest restRequest = new RestRequest(Method.POST);
            restRequest.AddParameter("username", Username);
            restRequest.AddParameter("apikey", ApiKey);
            restRequest.AddFile("image", shotPath, "image/png");
            var resp = restClient.Execute(restRequest);

            JPSResponse jValue = JsonConvert.DeserializeObject<JPSResponse>(resp.Content);
            PonyShotsResponse psResp = new PonyShotsResponse();

            psResp.RawResponse = resp.Content;
            psResp.Error = jValue.error;

            if (!psResp.Error)
            {   
                psResp.Slug = jValue.slug;
            }
            else
            {
                psResp.ErrorMessage = jValue.message;
            }

            return psResp;
        }
示例#9
0
        private void PostLogFile(string macAddress, Guid requestId, Guid logFileId, string fileName)
        {
            string path = GetFilePath(fileName);

            if (!File.Exists(path))
            {
                Logger.Instance.Write("PostLogFile", LogLevel.Medium, "PostLog failed as the log file does not exist.");
                RequestComponent.GetInstance().FinishRequest(macAddress, RequestInputModel.From(requestId, false));
                return;
            }

            var request = new RestRequest("v1/signboards/{macAddress}/logFiles/{logFileId}/file", Method.POST);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddUrlSegment("macAddress", macAddress);
            request.AddUrlSegment("logFileId", logFileId.ToString());
            request.AddBody(DeviceLogModel.From(fileName));
            request.AddFile("file", File.ReadAllBytes(path), Path.GetFileName(path), "multipart/form-data");

            Client.ExecuteAsync<DeviceLogResponseModel>(request, (response) =>
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Logger.Instance.Write("PostLogFile", LogLevel.Low, "Uploaded  log file successfully.");
                    RequestComponent.GetInstance().FinishRequest(macAddress, RequestInputModel.From(requestId, true));
                    return;
                }
                else
                {
                    Logger.Instance.Write("PostLog", LogLevel.Medium, "PostLog request failed. ");
                    RequestComponent.GetInstance().FinishRequest(macAddress, RequestInputModel.From(requestId, false));
                    return;
                }
            });
        }
示例#10
0
        // Creates and sets up a RestRequest prior to a call.
        private RestRequest PrepareRequest(
            String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
            Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
            Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams)
        {
            var request = new RestRequest(path, method);
   
            // add path parameter, if any
            foreach(var param in pathParams)
                request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); 

            // add header parameter, if any
            foreach(var param in headerParams)
                request.AddHeader(param.Key, param.Value);

            // add query parameter, if any
            foreach(var param in queryParams)
                request.AddQueryParameter(param.Key, param.Value);

            // add form parameter, if any
            foreach(var param in formParams)
                request.AddParameter(param.Key, param.Value);

            // add file parameter, if any
            foreach(var param in fileParams)
                request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);

            if (postBody != null) // http body (model) parameter
                request.AddParameter("application/json", postBody, ParameterType.RequestBody);
    
            return request;
        }
        public KrakenResponse Upload(KrakenRequest kr, string fileName, string fileExtension)
        {
            var request = new RestRequest("upload", Method.POST);

            if (kr.File.Length == 0)
            {
                return new KrakenResponse()
                {
                    Success = false,
                    Error = "File parameter was not provided"
                };
            }

            kr.Auth = _auth;

            request.AddFile("image_bytes", kr.File, fileName + fileExtension);

            kr.File = null;

            string json = JsonConvert.SerializeObject(kr, serializerSettings);

            request.AddParameter("json", json);

            var result = Request(request);

            return result;
        }
        public IRestResponse<_REST_StylesetHashInfo> RESTUploadUserLook(long lookId, long matchUserLookId, string filePath1, string filePath2, string filePath3, string MembershipId)
        {
            var Client = new RestClient();
            Client.BaseUrl = baseUri;
            MembershipId = "2011003539244269";
            var Request = new RestRequest("/api/userLook", Method.POST);
            Request.AddParameter("membershipId", MembershipId);
            Request.AddParameter("lookId", lookId);
            Request.AddParameter("matchUserLookId", matchUserLookId);
            Request.AddFile("front", filePath1);
            Request.AddFile("noface", filePath2);
            Request.AddFile("back", filePath3);

            IRestResponse<_REST_StylesetHashInfo> rj = Client.Execute<_REST_StylesetHashInfo>(Request);

            return rj;
        }
示例#13
0
 public Models.Deployment Create(Stream depfile, string filename)
 {
     var request = new RestRequest("repository/deployments", Method.POST);
     request.AddFile("deployfile", (s) => { depfile.CopyTo(s); }, filename);
     var response = base.Client.Execute<Models.Deployment>(request);
     base.HandleError(response);
     return response.Data;
 }
 /// <summary>
 /// Uploads a document and obtains the document's ID.
 /// The document uploaded through this call is referred to as transient since it is available only for 7 days after the upload. 
 /// The returned transient document ID can be used to refer to the document in api calls like POST /agreements where uploaded file needs to be referred. 
 /// The transient document request is a multipart request consisting of three parts - filename, mime type and the file stream. 
 /// You can only upload one file at a time in this request.
 /// </summary>
 /// <param name="file">The file part of the multipart request for document upload. You can upload only one file at a time.</param>
 /// <param name="filename">A name for the document being uploaded.</param>
 /// <param name="mimeType">The mime type of the document being uploaded. If not specified here then mime type is picked up from the file object. If mime type is not present there either then mime type is inferred from file name extension.</param>
 public virtual Task<TransientDocumentResponse> CreateAsync(string filename, string mimeType, byte[] file)
 {
     var request = new RestRequest(Method.POST);
     request.JsonSerializer = new Serialization.NewtonSoftSerializer();
     request.AlwaysMultipartFormData = true;
     request.Resource = "transientDocuments";
     request.AddParameter("File-Name", filename);
     request.AddParameter("Mime-Type", filename);
     request.AddFile("File", file, filename);
     return this.Sdk.ExecuteAsync<TransientDocumentResponse>(request);
 }
        // Creates and sets up a RestRequest prior to a call.
        private RestRequest PrepareRequest(
            String path, RestSharp.Method method, Dictionary <String, String> queryParams, Object postBody,
            Dictionary <String, String> headerParams, Dictionary <String, String> formParams,
            Dictionary <String, FileParameter> fileParams, Dictionary <String, String> pathParams,
            String contentType)
        {
            var request = new RestRequest(path, method);

            request.JsonSerializer = new NewtonsoftJsonSerializer();
            // add path parameter, if any
            foreach (var param in pathParams)
            {
                request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
            }

            // add header parameter, if any
            foreach (var param in headerParams)
            {
                request.AddHeader(param.Key, param.Value);
            }

            // add query parameter, if any
            foreach (var param in queryParams)
            {
                request.AddQueryParameter(param.Key, param.Value);
            }

            // add form parameter, if any
            foreach (var param in formParams)
            {
                request.AddParameter(param.Key, param.Value);
            }

            // add file parameter, if any
            foreach (var param in fileParams)
            {
                request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
            }

            if (postBody != null) // http body (model or byte[]) parameter
            {
                if (postBody.GetType() == typeof(String))
                {
                    request.AddParameter("application/json", postBody, ParameterType.RequestBody);
                }
                else if (postBody.GetType() == typeof(byte[]))
                {
                    request.AddParameter(contentType, postBody, ParameterType.RequestBody);
                }
            }

            return(request);
        }
示例#16
0
		public RestRequest CreateUploadFileRequest(string path, string filename, byte[] fileData)
		{
			var request = new RestRequest (Method.POST);
			request.Resource = "{version}/files/dropbox{path}";
			request.AddParameter ("version", _version, ParameterType.UrlSegment);
			request.AddParameter ("path", path, ParameterType.UrlSegment);
			//Need to add the "file" parameter with the file name
			request.AddParameter ("file", filename);

			request.AddFile ("file", fileData, filename);

			return request;
		}
        private static RestRequest MakeRestRequest(TestFlightPackage package)
        {
            var request = new RestRequest(c_TestFlightApiPath, Method.POST);

            request.AddParameter("api_token", package.ApiToken);
            request.AddParameter("team_token", package.TeamToken);
            request.AddParameter("notes", package.Notes);
            request.AddParameter("distribution_lists", package.DistributionLists);
            request.AddParameter("notify", package.Notify);
            request.AddParameter("replace", package.Replace);
            request.AddFile("file", package.File);

            return request;
        }
        public HockeyAppResponse UploadFileAsync(string apiToken, string appId, string version, string notes,
            string notesType, string status,
            string notify, string tags, string teams, string users, string mandatory, string commitSha,
            string buildServerUrl,
            string repositoryUrl, string filePath, string symbolPath)
        {
            var request = new RestRequest($"/api/2/apps/{appId}/app_versions/{version}");

            request.AddHeader("X-HockeyAppToken", apiToken);

            request.AlwaysMultipartFormData = true;

            if (!string.IsNullOrEmpty(notes)) request.AddParameter("notes", notes);
            if (!string.IsNullOrEmpty(notesType)) request.AddParameter("notes_type", notesType);
            if (!string.IsNullOrEmpty(status)) request.AddParameter("status", status);
            if (!string.IsNullOrEmpty(notify)) request.AddParameter("notify", notify);
            if (!string.IsNullOrEmpty(tags)) request.AddParameter("tags", tags);
            if (!string.IsNullOrEmpty(teams)) request.AddParameter("teams", teams);
            if (!string.IsNullOrEmpty(users)) request.AddParameter("users", users);
            if (!string.IsNullOrEmpty(mandatory)) request.AddParameter("mandatory", mandatory);
            if (!string.IsNullOrEmpty(commitSha)) request.AddParameter("commit_sha", commitSha);
            if (!string.IsNullOrEmpty(buildServerUrl)) request.AddParameter("build_server_url", buildServerUrl);
            if (!string.IsNullOrEmpty(repositoryUrl)) request.AddParameter("repository_url", repositoryUrl);

            request.AddFile("ipa", filePath);

            if (!string.IsNullOrEmpty(symbolPath)) request.AddFile("dsym", symbolPath);

            request.Timeout = 3600000; // larger request timeout

            var response = _restClient.Put<HockeyAppResponse>(request);

            if (response.ErrorException != null)
                throw response.ErrorException;

            return response.Data;
        }
 public override string Create(string localFilePath)
 {
     if (false == File.Exists(localFilePath))
     {
         throw new ArgumentException(Resources.BlobstoreClient_LocalFileDoesNotExist_Fmt, localFilePath);
     }
     var request = new RestRequest(GetUrl(), Method.POST);
     request.AddFile("content", localFilePath);
     IRestResponse response = client.Execute(request);
     if (response.StatusCode != HttpStatusCode.OK)
     {
         throw new BlobstoreException(Resources.BlobstoreClient_CouldNotCreateObject_Fmt, response.StatusCode, response.Content);
     }
     return response.Content;
 }
示例#20
0
		void PostToTwitter ()
		{
			//Goto https://apps.twitter.com/ and create a new app to post to.
			using (var pool = new NSAutoreleasePool ()) {
				using (NSData imageData = _state.DisplayImageView.Image.AsPNG ()) {
					Byte[] myByteArray = new Byte[imageData.Length];
					System.Runtime.InteropServices.Marshal.Copy (imageData.Bytes, myByteArray, 0, Convert.ToInt32 (imageData.Length));
					var client = new RestClient ("https://api.twitter.com");
					//Get all 4 token and secret vallues from your twitter add @ https://apps.twitter.com/
					client.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForProtectedResource ("CustomerKey","CustomerSecret", "Token", "TokenSecret");
					var request = new RestRequest ("/1.1/statuses/update_with_media.json", Method.POST);
					request.AddFile ("media[]", myByteArray, "share.jpg");
					client.Execute (request);
				}
			}
		}
示例#21
0
        //TODO: gzip https://service.sumologic.com/ui/help/Default.htm#cshid=4036
        static void StreamToUrl(string content)
        {
            var client = new RestClient { BaseUrl = "https://collectors.sumologic.com" };
            var request = new RestRequest
            {
                Resource = ConfigurationManager.AppSettings["SumoLogicResource"],
                Method = Method.POST
            };
            request.AddFile("someName", Encoding.UTF8.GetBytes(content), "someFileName");

            client.ExecuteAsync(request, response =>
            {
                Console.WriteLine("Response status: {0}", response.ResponseStatus);
                Console.WriteLine("Response status code: {0}", response.StatusCode);
            });
        }
示例#22
0
        public SabnzbdAddResponse DownloadNzb(byte[] nzbData, string filename, string category, int priority, SabnzbdSettings settings)
        {
            var request = new RestRequest(Method.POST);
            var action = string.Format("mode=addfile&cat={0}&priority={1}", Uri.EscapeDataString(category), priority);

            request.AddFile("name", nzbData, filename, "application/x-nzb");

            SabnzbdAddResponse response;

            if (!Json.TryDeserialize<SabnzbdAddResponse>(ProcessRequest(request, action, settings), out response))
            {
                response = new SabnzbdAddResponse();
                response.Status = true;
            }

            return response;
        }
        public OrderItem CreateWithData(long orderId,OrderItemRequest orderItem, Stream fileData)
        {
            var request = new RestRequest
              {
                  Resource = _orderItemPath,
                  Method = Method.POST
              };
              request.AddParameter("orderId", orderId, ParameterType.UrlSegment);
              request.AddObject(orderItem, "Type", "Url", "Copies", "Sizing", "PriceToUser", "Md5Hash");

              byte[] allData = new byte[fileData.Length];
              fileData.Read(allData,0,allData.Length);
              request.AddFile("image",allData,"image.jpg");
              var response = Client.ExecuteWithErrorCheck<OrderItem>(request);
              fileData.Dispose();
              return response.Data;
        }
示例#24
0
        public SabnzbdAddResponse DownloadNzb(Stream nzb, string title, string category, int priority, SabnzbdSettings settings)
        {
            var request = new RestRequest(Method.POST);
            var action = String.Format("mode=addfile&cat={0}&priority={1}", category, priority);

            request.AddFile("name", ReadFully(nzb), title, "application/x-nzb");

            SabnzbdAddResponse response;

            if (!Json.TryDeserialize<SabnzbdAddResponse>(ProcessRequest(request, action, settings), out response))
            {
                response = new SabnzbdAddResponse();
                response.Status = true;
            }

            return response;
        }
示例#25
0
        /// <summary>
        /// Send request.
        /// </summary>
        public static RestResponse SendRemoteRequest(Request _request, RestRequest request, String URL)
        {
            // Create client
            var client = new RestClient(URL);

            // Authentication?
            Server server = _request.ParentScenario.ParentServer;
            if (server.Authentication)
                client.Authenticator = new HttpBasicAuthenticator (server.AuthName, server.AuthPassword);

            // Add files
            foreach (var f in _request.Files)
                request.AddFile(f.FileName, f.FilePath);

            // Get response
            return (RestResponse) client.Execute(request);
        }
示例#26
0
        private void ConfigureMultipart(RestSharp.RestRequest request,
                                        string fileParamName, RestMultipart restMultipart)
        {
            RestMultipart.RestMultipartType type = restMultipart.Type;
            switch (type)
            {
            case RestMultipart.RestMultipartType.FILE:
                string fileName = null;
                try
                {
                    fileName = restMultipart.Value;
                    using (var fileContent = new FileStream(fileName, FileMode.Open))
                    {
                        request.AddFile(fileName, fileContent.CopyTo, fileName,
                                        restMultipart.ContentType);
                    }

                    LOG.Info("Configure Multipart file upload paramName={0} :  ContentType={1} for  file={2} ",
                             new string[] { fileParamName, restMultipart.ContentType, fileName });
                    break;
                }
                catch (FileNotFoundException e)
                {
                    throw new System.ArgumentException("File not found: " + fileName, e);
                }

            case RestMultipart.RestMultipartType.STRING:
                // According to a comment on RestSharp issue 524,
                //  https://github.com/restsharp/RestSharp/issues/524 , it's only possible to
                //  add string data in multipart form data using ParameterType GetOrPost.
                //  ParameterType RequestBody doesn't work.
                request.AddParameter(fileParamName, restMultipart.Value,
                                     restMultipart.ContentType, ParameterType.GetOrPost);
                LOG.Info("Configure Multipart String upload paramName={0}:  ContentType={1} ",
                         fileParamName, restMultipart.ContentType);
                break;

            default:
                throw new System.ArgumentException("Unknonw Multipart Type: " + type);
                break;
            }
        }
示例#27
0
        /// <summary>
        /// Builds the HTTP request that will be sent.
        /// </summary>
        /// <param name="requestDetails">The RestClient.RestRequest containing details of the request
        /// to send.</param>
        /// <returns>A RestSharp.RestRequest object containing details of the request to send.</returns>
        /// <remarks>Loosely based on RestClient.RestClientImpl.configureHttpMethod, which is
        /// designed around the Apache HttpClient library, written in Java.  This is very different
        /// from the .NET System.Net library so cannot be ported directly; the HttpClient must be
        /// rewritten from scratch.</remarks>
        private RestSharp.RestRequest BuildRequest(Data.RestRequest requestDetails)
        {
            Uri resourceUri = GetResourceUri(requestDetails);

            RestSharp.Method httpMethod = GetHttpMethod(requestDetails);

            RestSharp.RestRequest request = new RestSharp.RestRequest(resourceUri, httpMethod);

            AddHttpRequestHeaders(request, requestDetails);

            // Request type doesn't expect a body (eg GET, DELETE).
            if (!IsEntityEnclosingMethod(httpMethod))
            {
                return(request);
            }

            // Simple file upload.
            string fileName = requestDetails.FileName;

            if (!string.IsNullOrWhiteSpace(fileName))
            {
                if (!File.Exists(fileName))
                {
                    throw new ArgumentException("File not found: " + fileName);
                }
                request.AddFile("file", fileName);
                return(request);
            }

            // Multipart file upload.
            LinkedHashMap <string, Data.RestMultipart>
            multipartFiles = requestDetails.MultipartFileNames;

            if ((multipartFiles != null) && (multipartFiles.Count > 0))
            {
                ConfigureRequestMultipartFileUpload(request, requestDetails, multipartFiles);
                return(request);
            }

            if (string.IsNullOrWhiteSpace(requestDetails.Body))
            {
                return(request);
            }

            // Request includes a body, eg standard POST or PUT.
            string contentType = requestDetails.ContentType;

            if (contentType != null)
            {
                if (contentType.Trim().Length == 0)
                {
                    contentType = null;
                }
                else
                {
                    contentType = contentType.ToLower();
                }
            }

            string body = requestDetails.Body.Trim();

            if (string.IsNullOrWhiteSpace(contentType))
            {
                // RestSharp has only two DataFormats: Json and Xml.

                if (body.StartsWith("{") || body.StartsWith("["))
                {
                    request.RequestFormat = DataFormat.Json;
                    contentType           = "application/json";
                }
                else
                {
                    request.RequestFormat = DataFormat.Xml;
                    contentType           = "application/xml";
                }
            }
            else if (contentType.Contains("json"))
            {
                request.RequestFormat = DataFormat.Json;
                contentType           = requestDetails.ContentType;
            }
            else
            {
                request.RequestFormat = DataFormat.Xml;
                contentType           = requestDetails.ContentType;
            }

            // requestDetails.Body is a string, and RestRequest.AddBody, AddJsonBody
            //  and AddXmlBody take objects as arguments, not strings.  Although they
            //  won't throw exceptions, the result is not as expected if an object is
            //  serialized to JSON or XML before being passed to one of the AddBody
            //  methods.
            //
            //  For example, if a Book object is serialized to JSON and the JSON string
            //  is passed to AddBody or AddJsonBody the body sent across the wire is:
            //
            //  "{\"Id\":10,\"Title\":\"The Meaning of Liff\",\"Year\":1983}"
            //
            //  when it should be:
            //
            //  {Id: 10, Title: "The Meaning of Liff", Year: 1983}

            //  The incorrect format of the JSON in the request body will prevent it
            //  from being desrialized correctly at the server end.

            // Instead of using one of the AddBody methods, use
            //  AddParameter(..., ..., ParameterType.RequestBody)
            //  which can handle objects serialized to JSON or XML strings.
            request.AddParameter(contentType, body, ParameterType.RequestBody);

            return(request);
        }
示例#28
0
 public Request AddFile(string parameter, string fileName, byte[] contents)
 {
     _RestRequest.AddFile(parameter, contents, fileName);
     return(this);
 }
示例#29
-1
 public static bool DeliverEvergreenMessage(string emailMessage, string to, string attachment)
 {
     try
     {
         //Deliver email to Evergreen
         var client = new RestClient();
         client.BaseUrl = "https://api.mailgun.net/v2";
         client.Authenticator = new HttpBasicAuthenticator("api", Supplier.MailgunApiKey);
         RestRequest request = new RestRequest();
         request.AddParameter("domain", Supplier.MailgunDomain, ParameterType.UrlSegment);
         request.Resource = "{domain}/messages";
         request.AddParameter("from", Supplier.CompanyName + " <*****@*****.**>");
         request.AddParameter("to", to);
         request.AddParameter("subject", "New Order Notification");
         request.AddParameter("html", emailMessage);
         request.AddFile("attachment", attachment);
         request.Method = Method.POST;
         var response = client.Execute(request);
         if (response.StatusCode == System.Net.HttpStatusCode.OK)
         {
             return true;
         }
     }
     catch (Exception ex)
     {
         Log.WriteErrorLog(ex);
     }
     return false;
 }
示例#30
-1
    public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
      Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {

      var request = new RestRequest(Path, Method);

      UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);

      // add default header, if any
      foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap)
        request.AddHeader(defaultHeader.Key, defaultHeader.Value);

      // add header parameter, if any
      foreach(KeyValuePair<string, string> param in HeaderParams)
        request.AddHeader(param.Key, param.Value);
     
      // add query parameter, if any
      foreach(KeyValuePair<string, string> param in QueryParams)
        request.AddQueryParameter(param.Key, param.Value);

      // add form parameter, if any
      foreach(KeyValuePair<string, string> param in FormParams)
        request.AddParameter(param.Key, param.Value);

      // add file parameter, if any
      foreach(KeyValuePair<string, string> param in FileParams)
        request.AddFile(param.Key, param.Value);

      if (PostBody != null) {
        request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter
      }

      return (Object) await restClient.ExecuteTaskAsync(request);

    }
示例#31
-1
        public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings)
        {
            var request = new RestRequest("/command/upload", Method.POST);
            request.AddFile("torrents", fileContent, fileName);

            var client = BuildClient(settings);
            var response = ProcessRequest(client, request, settings);
            response.ValidateResponse(client);
        }
示例#32
-1
        public ImageFile UploadImage(string imageName, string imagePath)
        {
            var request = new RestRequest(Method.POST)
                {
                    Resource = "/assets/image/content"
                };

            var image = ResourceHelper.GetEmbeddedResource(imagePath);
            request.AddFile(imageName, image, imageName, "image/jpeg");

            var response = _client.Execute<ImageFile>(request);
            return response.Data;
        }
示例#33
-5
		public RestRequest CreateUploadFileRequest(string path, string filename, Stream fileStream)
		{
			var request = new RestRequest (Method.POST);
            //Don't want these to timeout (Maybe use something better here?)
            request.Timeout = int.MaxValue;
			request.Resource = "{version}/files/dropbox{path}";
			request.AddParameter ("version", _version, ParameterType.UrlSegment);
			request.AddParameter ("path", path, ParameterType.UrlSegment);
			//Need to add the "file" parameter with the file name
			request.AddParameter ("file", filename);

			request.AddFile ("file", s => StreamUtils.CopyStream (fileStream, s), filename);

			return request;
		}
        protected void BaseSaveCategoryImageTest()
        {
            var allNames = this.GetCategoryNames()
                               .Deserialize<IEnumerable<string>>();

            var client = new RestClient(this.BaseServiceAddress);

            var request = new RestRequest("/categories/image/{categoryName}", Method.PUT);
            request.AddUrlSegment("categoryName", allNames.First());
            request.AddFile("categoryImage", new byte[100], string.Empty, "application/octet-stream");

            var response = client.Execute(request);

            Assert.IsTrue(response.ResponseStatus == ResponseStatus.Completed);
            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
        }