コード例 #1
0
ファイル: NetworkHelper.cs プロジェクト: nguoichiase/ShareX
        /// <summary>
        /// Write Multipart Form Data to a Stream, content-type should be set before this!
        /// </summary>
        /// <param name="formDataStream">Stream to write the multipart form data to</param>
        /// <param name="boundary">String boundary for the multipart/form-data</param>
        /// <param name="postParameters">Parameters to include in the multipart form data</param>
        public static void WriteMultipartFormData(Stream formDataStream, string boundary, IDictionary <string, object> postParameters)
        {
            bool needsClrf = false;

            foreach (var param in postParameters)
            {
                // Add a CRLF to allow multiple parameters to be added.
                // Skip it on the first parameter, add it to subsequent parameters.
                if (needsClrf)
                {
                    formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n"));
                }

                needsClrf = true;

                if (param.Value is IBinaryContainer)
                {
                    IBinaryContainer binaryParameter = (IBinaryContainer)param.Value;
                    binaryParameter.WriteFormDataToStream(boundary, param.Key, formDataStream);
                }
                else
                {
                    string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                                                    boundary,
                                                    param.Key,
                                                    param.Value);
                    formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData));
                }
            }

            // Add the end of the request.  Start with a newline
            string footer = "\r\n--" + boundary + "--\r\n";

            formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
        }
コード例 #2
0
 public void upload(IBinaryContainer attachment)
 {
     config.LastUsedJira = selectedIssue.Key;
     jiraConnector.addAttachment(selectedIssue.Key, jiraFilenameBox.Text, attachment);
     if (jiraCommentBox.Text != null && jiraCommentBox.Text.Length > 0)
     {
         jiraConnector.addComment(selectedIssue.Key, jiraCommentBox.Text);
     }
 }
コード例 #3
0
ファイル: JiraForm.cs プロジェクト: zhk/greenshot
        public async Task UploadAsync(IBinaryContainer attachment)
        {
            attachment.Filename = jiraFilenameBox.Text;
            await _jiraConnector.AttachAsync(_selectedIssue.Key, attachment);

            if (!string.IsNullOrEmpty(jiraCommentBox.Text))
            {
                await _jiraConnector.AddCommentAsync(_selectedIssue.Key, jiraCommentBox.Text);
            }
        }
コード例 #4
0
ファイル: JiraConnector.cs プロジェクト: Vistritium/greenshot
        /// <summary>
        ///     Attach the content to the jira
        /// </summary>
        /// <param name="issueKey"></param>
        /// <param name="content">IBinaryContainer</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task AttachAsync(string issueKey, IBinaryContainer content, CancellationToken cancellationToken = default)
        {
            await CheckCredentialsAsync(cancellationToken);

            using (var memoryStream = new MemoryStream())
            {
                content.WriteToStream(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);
                await _jiraClient.Attachment.AttachAsync(issueKey, memoryStream, content.Filename, content.ContentType, cancellationToken).ConfigureAwait(false);
            }
        }
コード例 #5
0
 public void addAttachment(string issueKey, string filename, IBinaryContainer attachment)
 {
     checkCredentials();
     try {
         jira.addBase64EncodedAttachmentsToIssue(credentials, issueKey, new string[] { filename }, new string[] { attachment.ToBase64String(Base64FormattingOptions.InsertLineBreaks) });
     } catch (Exception ex1) {
         LOG.WarnFormat("Failed to upload by using method addBase64EncodedAttachmentsToIssue, error was {0}", ex1.Message);
         try {
             LOG.Warn("Trying addAttachmentsToIssue instead");
             jira.addAttachmentsToIssue(credentials, issueKey, new string[] { filename }, (sbyte[])(Array)attachment.ToByteArray());
         } catch (Exception ex2) {
             LOG.WarnFormat("Failed to use alternative method, error was: {0}", ex2.Message);
             throw;
         }
     }
 }
コード例 #6
0
        public void AddAttachment(string fileName, IBinaryContainer attachment)
        {
            var file = attachment.ToBase64String(Base64FormattingOptions.InsertLineBreaks);

            LOG.DebugFormat("adding image {0}", file);

            using (var client = new WebClient())
            {
                client.UploadValues(url,
                                    new NameValueCollection()
                {
                    { "imageBase64String", file },
                    { "fileName", fileName },
                    { "ticketNr", "Test ticket" }
                });
            }
        }
コード例 #7
0
ファイル: JiraForm.cs プロジェクト: logtcn/greenshot
		public void upload(IBinaryContainer attachment) {
			config.LastUsedJira = selectedIssue.Key;
			jiraConnector.addAttachment(selectedIssue.Key, jiraFilenameBox.Text, attachment);
			if (jiraCommentBox.Text != null && jiraCommentBox.Text.Length > 0) {
				jiraConnector.addComment(selectedIssue.Key, jiraCommentBox.Text);
			}
		}
コード例 #8
0
        public void addAttachment(long pageId, string mime, string comment, string filename, IBinaryContainer image)
        {
            checkCredentials();
            RemoteAttachment attachment = new RemoteAttachment();

            // Comment is ignored, see: http://jira.atlassian.com/browse/CONF-9395
            attachment.comment     = comment;
            attachment.fileName    = filename;
            attachment.contentType = mime;
            confluence.addAttachment(credentials, pageId, attachment, image.ToByteArray());
        }
コード例 #9
0
ファイル: OAuthHelper.cs プロジェクト: neooleg/greenshot
        /// <summary>
        /// Make the actual OAuth request, all oauth parameters are passed as header (default) and the others are placed in the url or post data.
        /// Any additional parameters added after the Sign call are not in the signature, this could be by design!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="requestURL"></param>
        /// <param name="headers"></param>
        /// <param name="parameters"></param>
        /// <param name="postData">IBinaryParameter</param>
        /// <returns>Response from server</returns>
        private string MakeRequest(HTTPMethod method, string requestURL, IDictionary<string, string> headers, IDictionary<string, object> parameters, IBinaryContainer postData)
        {
            if (parameters == null) {
                throw new ArgumentNullException("parameters");
            }
            IDictionary<string, object> requestParameters;
            // Add oAuth values as HTTP headers, if this is allowed
            StringBuilder authHeader = null;
            if (UseHTTPHeadersForAuthorization) {
                authHeader = new StringBuilder();
                requestParameters = new Dictionary<string, object>();
                foreach (string parameterKey in parameters.Keys) {
                    if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
                        authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
                    } else if (!requestParameters.ContainsKey(parameterKey)) {
                        requestParameters.Add(parameterKey, parameters[parameterKey]);
                    }
                }
                // Remove trailing comma and space and add it to the headers
                if (authHeader.Length > 0) {
                    authHeader.Remove(authHeader.Length - 2, 2);
                }
            } else {
                requestParameters = parameters;
            }

            if (HTTPMethod.GET == method || postData != null) {
                if (requestParameters.Count > 0) {
                    // Add the parameters to the request
                    requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
                }
            }
            // Create webrequest
            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestURL, method);
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.UserAgent = _userAgent;

            if (UseHTTPHeadersForAuthorization && authHeader != null) {
                LOG.DebugFormat("Authorization: OAuth {0}", authHeader);
                webRequest.Headers.Add("Authorization: OAuth " + authHeader);
            }

            if (headers != null) {
                foreach(string key in headers.Keys) {
                    webRequest.Headers.Add(key, headers[key]);
                }
            }

            if ((HTTPMethod.POST == method || HTTPMethod.PUT == method) && postData == null && requestParameters.Count > 0) {
                if (UseMultipartFormData) {
                    NetworkHelper.WriteMultipartFormData(webRequest, requestParameters);
                } else {
                    StringBuilder form = new StringBuilder();
                    foreach (string parameterKey in requestParameters.Keys) {
                        if (parameters[parameterKey] is IBinaryContainer) {
                            IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer;
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)));
                        } else {
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
                        }
                    }
                    // Remove trailing &
                    if (form.Length > 0) {
                        form.Remove(form.Length - 1, 1);
                    }
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(form.ToString());
                    using (var requestStream = webRequest.GetRequestStream()) {
                        requestStream.Write(data, 0, data.Length);
                    }
                }
            } else if (postData != null) {
                postData.Upload(webRequest);
            } else {
                webRequest.ContentLength = 0;
            }

            string responseData;
            try {
                responseData = NetworkHelper.GetResponseAsString(webRequest);
                LOG.DebugFormat("Response: {0}", responseData);
            } catch (Exception ex) {
                LOG.Error("Couldn't retrieve response: ", ex);
                throw;
            } finally {
                webRequest = null;
            }

            return responseData;
        }
コード例 #10
0
ファイル: OAuthHelper.cs プロジェクト: neooleg/greenshot
        /// <summary>
        /// Submit a web request using oAuth.
        /// </summary>
        /// <param name="method">GET or POST</param>
        /// <param name="signUrl">The full url, including the querystring for the signing</param>
        /// <param name="requestURL">The full url, including the querystring for the request</param>
        /// <param name="headers">Headers for the request</param>
        /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
        /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
        /// <param name="postData">Data to post (MemoryStream)</param>
        /// <returns>The web server response.</returns>
        public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary<string, string> headers, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, IBinaryContainer postData)
        {
            if (parametersToSign == null) {
                parametersToSign = new Dictionary<string, object>();
            }
            int retries = 2;
            Exception lastException = null;
            while (retries-- > 0) {
                // If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one
                if (string.IsNullOrEmpty(Token)) {
                    if (!AutoLogin || !Authorize()) {
                        throw new Exception("Not authorized");
                    }
                }
                try {
                    Sign(method, signUrl, parametersToSign);

                    // Join all parameters
                    IDictionary<string, object> newParameters = new Dictionary<string, object>();
                    foreach(var parameter in parametersToSign) {
                        newParameters.Add(parameter);
                    }
                    if (additionalParameters != null) {
                        foreach(var parameter in additionalParameters) {
                            newParameters.Add(parameter);
                        }
                    }
                    return MakeRequest(method, requestURL, headers, newParameters, postData);
                } catch (WebException wEx) {
                    lastException = wEx;
                    if (wEx.Response != null) {
                        HttpWebResponse response = wEx.Response as HttpWebResponse;
                        if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) {
                            Token = null;
                            TokenSecret = null;
                            // Remove oauth keys, so they aren't added double
                            List<string> keysToDelete = new List<string>();
                            foreach (string parameterKey in parametersToSign.Keys) {
                                if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
                                    keysToDelete.Add(parameterKey);
                                }
                            }
                            foreach(string keyToDelete in keysToDelete) {
                                parametersToSign.Remove(keyToDelete);
                            }
                            continue;
                        }
                    }
                    throw;
                }
            }
            if (lastException != null) {
                throw lastException;
            }
            throw new Exception("Not authorized");
        }
コード例 #11
0
ファイル: OAuthHelper.cs プロジェクト: neooleg/greenshot
 /// <summary>
 /// Submit a web request using oAuth.
 /// </summary>
 /// <param name="method">GET or POST</param>
 /// <param name="signUrl">The full url, including the querystring for the signing</param>
 /// <param name="requestURL">The full url, including the querystring for the request</param>
 /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
 /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
 /// <param name="postData">Data to post (MemoryStream)</param>
 /// <returns>The web server response.</returns>
 public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, IBinaryContainer postData)
 {
     return MakeOAuthRequest(method, signUrl, requestURL, null, parametersToSign, additionalParameters, postData);
 }
コード例 #12
0
ファイル: OAuthHelper.cs プロジェクト: oneminot/greenshot
        /// <summary>
        /// Make the actual OAuth request, all oauth parameters are passed as header (default) and the others are placed in the url or post data.
        /// Any additional parameters added after the Sign call are not in the signature, this could be by design!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="requestURL"></param>
        /// <param name="headers"></param>
        /// <param name="parameters"></param>
        /// <param name="postData">IBinaryParameter</param>
        /// <returns>Response from server</returns>
        private string MakeRequest(HTTPMethod method, string requestURL, IDictionary <string, string> headers, IDictionary <string, object> parameters, IBinaryContainer postData)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            IDictionary <string, object> requestParameters;
            // Add oAuth values as HTTP headers, if this is allowed
            StringBuilder authHeader = null;

            if (UseHTTPHeadersForAuthorization)
            {
                authHeader        = new StringBuilder();
                requestParameters = new Dictionary <string, object>();
                foreach (string parameterKey in parameters.Keys)
                {
                    if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX))
                    {
                        authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}", parameters[parameterKey])));
                    }
                    else if (!requestParameters.ContainsKey(parameterKey))
                    {
                        requestParameters.Add(parameterKey, parameters[parameterKey]);
                    }
                }
                // Remove trailing comma and space and add it to the headers
                if (authHeader.Length > 0)
                {
                    authHeader.Remove(authHeader.Length - 2, 2);
                }
            }
            else
            {
                requestParameters = parameters;
            }

            if (HTTPMethod.GET == method || postData != null)
            {
                if (requestParameters.Count > 0)
                {
                    // Add the parameters to the request
                    requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
                }
            }
            // Create webrequest
            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestURL);

            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.UserAgent = _userAgent;
            webRequest.Timeout   = 100000;

            if (UseHTTPHeadersForAuthorization && authHeader != null)
            {
                LOG.DebugFormat("Authorization: OAuth {0}", authHeader);
                webRequest.Headers.Add("Authorization: OAuth " + authHeader);
            }

            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    webRequest.Headers.Add(key, headers[key]);
                }
            }

            if ((HTTPMethod.POST == method || HTTPMethod.PUT == method) && postData == null && requestParameters.Count > 0)
            {
                if (UseMultipartFormData)
                {
                    NetworkHelper.WriteMultipartFormData(webRequest, requestParameters);
                }
                else
                {
                    StringBuilder form = new StringBuilder();
                    foreach (string parameterKey in requestParameters.Keys)
                    {
                        if (parameters[parameterKey] is IBinaryContainer)
                        {
                            IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer;
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)));
                        }
                        else
                        {
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}", parameters[parameterKey])));
                        }
                    }
                    // Remove trailing &
                    if (form.Length > 0)
                    {
                        form.Remove(form.Length - 1, 1);
                    }
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(form.ToString());
                    using (var requestStream = webRequest.GetRequestStream()) {
                        requestStream.Write(data, 0, data.Length);
                    }
                }
            }
            else if (postData != null)
            {
                postData.Upload(webRequest);
            }
            else
            {
                webRequest.ContentLength = 0;
            }

            string responseData;

            try {
                responseData = NetworkHelper.GetResponse(webRequest);
                LOG.DebugFormat("Response: {0}", responseData);
            } catch (Exception ex) {
                LOG.Error("Couldn't retrieve response: ", ex);
                throw;
            } finally {
                webRequest = null;
            }

            return(responseData);
        }
コード例 #13
0
ファイル: OAuthHelper.cs プロジェクト: oneminot/greenshot
        /// <summary>
        /// Submit a web request using oAuth.
        /// </summary>
        /// <param name="method">GET or POST</param>
        /// <param name="signUrl">The full url, including the querystring for the signing</param>
        /// <param name="requestURL">The full url, including the querystring for the request</param>
        /// <param name="headers">Headers for the request</param>
        /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
        /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
        /// <param name="postData">Data to post (MemoryStream)</param>
        /// <returns>The web server response.</returns>
        public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary <string, string> headers, IDictionary <string, object> parametersToSign, IDictionary <string, object> additionalParameters, IBinaryContainer postData)
        {
            if (parametersToSign == null)
            {
                parametersToSign = new Dictionary <string, object>();
            }
            int       retries       = 2;
            Exception lastException = null;

            while (retries-- > 0)
            {
                // If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one
                if (string.IsNullOrEmpty(Token))
                {
                    if (!AutoLogin || !Authorize())
                    {
                        throw new Exception("Not authorized");
                    }
                }
                try {
                    Sign(method, signUrl, parametersToSign);

                    // Join all parameters
                    IDictionary <string, object> newParameters = new Dictionary <string, object>();
                    foreach (var parameter in parametersToSign)
                    {
                        newParameters.Add(parameter);
                    }
                    if (additionalParameters != null)
                    {
                        foreach (var parameter in additionalParameters)
                        {
                            newParameters.Add(parameter);
                        }
                    }
                    return(MakeRequest(method, requestURL, headers, newParameters, postData));
                } catch (WebException wEx) {
                    lastException = wEx;
                    if (wEx.Response != null)
                    {
                        HttpWebResponse response = wEx.Response as HttpWebResponse;
                        if (response != null && response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            Token       = null;
                            TokenSecret = null;
                            // Remove oauth keys, so they aren't added double
                            List <string> keysToDelete = new List <string>();
                            foreach (string parameterKey in parametersToSign.Keys)
                            {
                                if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX))
                                {
                                    keysToDelete.Add(parameterKey);
                                }
                            }
                            foreach (string keyToDelete in keysToDelete)
                            {
                                parametersToSign.Remove(keyToDelete);
                            }
                            continue;
                        }
                    }
                    throw;
                }
            }
            if (lastException != null)
            {
                throw lastException;
            }
            throw new Exception("Not authorized");
        }
コード例 #14
0
ファイル: OAuthHelper.cs プロジェクト: oneminot/greenshot
 /// <summary>
 /// Submit a web request using oAuth.
 /// </summary>
 /// <param name="method">GET or POST</param>
 /// <param name="signUrl">The full url, including the querystring for the signing</param>
 /// <param name="requestURL">The full url, including the querystring for the request</param>
 /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
 /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
 /// <param name="postData">Data to post (MemoryStream)</param>
 /// <returns>The web server response.</returns>
 public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary <string, object> parametersToSign, IDictionary <string, object> additionalParameters, IBinaryContainer postData)
 {
     return(MakeOAuthRequest(method, signUrl, requestURL, null, parametersToSign, additionalParameters, postData));
 }
コード例 #15
0
ファイル: Confluence.cs プロジェクト: logtcn/greenshot
		public void addAttachment(long pageId, string mime, string comment, string filename, IBinaryContainer image) {
			checkCredentials();
			RemoteAttachment attachment = new RemoteAttachment();
			// Comment is ignored, see: http://jira.atlassian.com/browse/CONF-9395
			attachment.comment = comment;
			attachment.fileName = filename;
			attachment.contentType = mime;
			confluence.addAttachment(credentials, pageId, attachment, image.ToByteArray());
		}
コード例 #16
0
ファイル: Jira.cs プロジェクト: logtcn/greenshot
		public void addAttachment(string issueKey, string filename, IBinaryContainer attachment) {
			checkCredentials();
			try {
				jira.addBase64EncodedAttachmentsToIssue(credentials, issueKey, new string[] { filename }, new string[] { attachment.ToBase64String(Base64FormattingOptions.InsertLineBreaks) });
			} catch (Exception ex1) {
				LOG.WarnFormat("Failed to upload by using method addBase64EncodedAttachmentsToIssue, error was {0}", ex1.Message);
				try {
					LOG.Warn("Trying addAttachmentsToIssue instead");
					jira.addAttachmentsToIssue(credentials, issueKey, new string[] { filename }, (sbyte[])(Array)attachment.ToByteArray());
				} catch (Exception ex2) {
					LOG.WarnFormat("Failed to use alternative method, error was: {0}", ex2.Message);
					throw;
				}
			}
		}