public Obj SendRequest(string strURL, string strReqData, MethodType type) { if (HSDKConfiguration.SoapRequest) { strReqData = GetSoapMessage(strURL, strReqData, type); type = MethodType.POST; strURL = HSDKConfiguration.LobbyUrl + "/soap"; } logMessage("Request XML from TestClient to HSDK Server (" + type.ToString() + ") to ...", SmartPlus_LOG_TYPE.TRACE); logMessage(strURL, SmartPlus_LOG_TYPE.TRACE); logMessage(strReqData, SmartPlus_LOG_TYPE.REQUEST); string response; if (HSDKConfiguration.CertFilePath == "") { response = HTTPStub.PostRequestToURL(strURL, strReqData, type.ToString(), HSDKConfiguration.Username, HSDKConfiguration.Password); } else { response = HTTPStub.PostRequestToURL(strURL, strReqData, type.ToString(), HSDKConfiguration.Username, HSDKConfiguration.Password, X509Certificate.CreateFromCertFile(HSDKConfiguration.CertFilePath)); } if (response == "") { throw new Exception("HSDK Server responded with empty XML."); } if (HSDKConfiguration.SoapRequest) { XmlDocument xmlDoc = new XmlDocument(); XmlNamespaceManager xmlNSMgr = new XmlNamespaceManager(xmlDoc.NameTable); xmlNSMgr.AddNamespace("ha", "http://schemas.xmlsoap.org/soap/envelope/"); xmlDoc.LoadXml(response); response = xmlDoc.SelectSingleNode("/ha:Envelope/ha:Body/*", xmlNSMgr).OuterXml; } logMessage("Response XML from HSDK Server to TestClient...", SmartPlus_LOG_TYPE.TRACE); logMessage(response, SmartPlus_LOG_TYPE.RESPONSE); Obj obj = oBIXDecoder.fromString(response); if (obj.isErr()) { if (obj.Display.Equals("No License to access WatchService") || obj.Display.Equals("No License to access AlarmService")) { //Let the oBIX tree discovery continue, even if no license for WatchService. ShowStatusBar(obj.Display, MessageType.Error); } else { throw new Exception(obj.Display); } } return(obj); }
private MethodCallExpression BuildMethodCallExpression( MethodType method, Expression caller, LambdaExpression argument) { var types = new List <Type> { caller.Type.IsGenericType?caller.Type.GenericTypeArguments[0] : caller.Type }; if (method == MethodType.Any) { return(Expression.Call(typeof(Enumerable), "Any", types.ToArray(), caller, argument)); } if (method == MethodType.Count) { return(Expression.Call(typeof(Enumerable), "Count", types.ToArray(), caller, argument)); } if (method == MethodType.OrderBy || method == MethodType.OrderByDescending) { var methodName = method.ToString(); if (OderByCount > 0) { methodName = methodName.Replace("OderBy", "ThenBy"); } types.Add(argument.ReturnType); OderByCount++; return(Expression.Call( typeof(Queryable), methodName, types.ToArray(), caller, Expression.Quote(argument))); } if (method == MethodType.Where) { return(Expression.Call(typeof(Queryable), "Where", types.ToArray(), caller, Expression.Quote(argument))); } if (method == MethodType.Select) { types.Add(argument.ReturnType); return(Expression.Call(typeof(Queryable), "Select", types.ToArray(), caller, Expression.Quote(argument))); } throw new Exception(method.ToString()); }
public static T CallRestService <T>(string url, string inputMessage, MethodType methodType) { InputMessage = inputMessage; T returnObject = default(T); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = methodType.ToString(); request.ContentType = "text/xml"; if (!string.IsNullOrWhiteSpace(InputMessage)) { AddRequest(request.GetRequestStream()); } HttpWebResponse response = request.GetResponse() as HttpWebResponse; // For void calls. if (response.StatusCode == HttpStatusCode.NoContent) { return(default(T)); } Stream result = response.GetResponseStream(); returnObject = ConvertToObject <T>(result); return(returnObject); }
/// <summary> /// Generates the signature. /// </summary> /// <param name="t">The tokens.</param> /// <param name="httpMethod">The HTTP method.</param> /// <param name="url">The URL.</param> /// <param name="prm">The parameters.</param> /// <returns>The signature.</returns> internal static string GenerateSignature(Tokens t, MethodType httpMethod, Uri url, IEnumerable <KeyValuePair <string, string> > prm) { var key = Encoding.UTF8.GetBytes( string.Format("{0}&{1}", UrlEncode(t.ConsumerSecret), UrlEncode(t.AccessTokenSecret))); var prmstr = prm.Select(x => new KeyValuePair <string, string>(UrlEncode(x.Key), UrlEncode(x.Value))) .Concat( url.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => { var s = x.Split('='); return(new KeyValuePair <string, string>(s[0], s[1])); }) ) .OrderBy(x => x.Key).ThenBy(x => x.Value) .Select(x => x.Key + "=" + x.Value) .JoinToString("&"); var msg = Encoding.UTF8.GetBytes( string.Format("{0}&{1}&{2}", httpMethod.ToString().ToUpperInvariant(), UrlEncode(url.GetComponents(UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped)), UrlEncode(prmstr) )); return(Convert.ToBase64String(SecurityUtils.HmacSha1(key, msg))); }
private void DisplayResponse(object response, MethodType method, TaskType task) { richTextBox1.Text = ""; richTextBox1.Text += $"{Constants.methodLabel}:{method.ToString()}{Environment.NewLine}" + $"{Constants.taskLabel}:{task.ToString()}{Environment.NewLine}"; switch (task) { case TaskType.NonRandomized: var castedNonRandResponse = response as Tuple <int[], double, Matrix>; richTextBox1.Text += $"{Constants.bestDecisionsLabel}: {string.Format("{0}", string.Join(", ", castedNonRandResponse.Item1))}" + $"{Environment.NewLine}"; richTextBox1.Text += $"{Constants.bestLossLabel}:{castedNonRandResponse.Item2}{Environment.NewLine}"; richTextBox1.Text += $"{Constants.anchorMatrixLabel}:{Environment.NewLine}{GetMatrixText(castedNonRandResponse.Item3)}"; break; case TaskType.Randomized: var castedRandResponse = response as Tuple <double[], double, PointF, Matrix, PointF[], Tuple <int, PointF>[], Tuple <int, PointF>[], Tuple <MathFunction, MathFunction> >; richTextBox1.Text += $"{Constants.randomizedDecisionlabel}:{string.Format("({0})", string.Join(", ", castedRandResponse.Item1))}" + $"{Environment.NewLine}"; richTextBox1.Text += $"{Constants.bestLossLabel}:{castedRandResponse.Item2}{Environment.NewLine}"; richTextBox1.Text += $"{Constants.anchorMatrixLabel}:{Environment.NewLine}{GetMatrixText(castedRandResponse.Item4)}{Environment.NewLine}"; break; case TaskType.Statistical: break; } }
public static string ComposeStringToSign(MethodType method, Dictionary <string, string> queries) { IDictionary <string, string> sortedDictionary = new SortedDictionary <string, string>(queries, StringComparer.Ordinal); var canonicalizedQueryString = new StringBuilder(); foreach (var p in sortedDictionary) { canonicalizedQueryString.Append("&") .Append(AcsURLEncoder.PercentEncode(p.Key)).Append("=") .Append(AcsURLEncoder.PercentEncode(p.Value)); } var stringToSign = new StringBuilder(); stringToSign.Append(method.ToString()); stringToSign.Append(Separator); stringToSign.Append(AcsURLEncoder.PercentEncode("/")); stringToSign.Append(Separator); stringToSign.Append(AcsURLEncoder.PercentEncode( canonicalizedQueryString.ToString().Substring(1))); return(stringToSign.ToString()); }
public static void Request(MethodType method, string uri, string body, CallBack<string> callBack) { try { Init("8aa5b8b5-f769-11e3-954e-06a6fa0000b9", "6ef2e5c0-3ef1-11e4-ae91-06a6fa0000b9"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(APIEndpoint + uri); request.Method = method.ToString(); request.ContentType = "applications/json"; if (PlayerPrefs.HasKey("access_token")) request.Headers["Authorization"] = "Bearer " + PlayerPrefs.GetString("access_token"); if(request.Method == "POST" || request.Method == "PUT") { StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(body); writer.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); callBack(responseFromServer); } catch(Exception e) { Debug.Log(e.Message); } }
protected UiFormInput GetDropDownInput(string controller, MethodType type, string area , string inputName, string inputTranslate, FieldType fieldType) { //باید لیست باشد var uiinputmethosd = new List <UiInputMethod>(); //خود ورودی var WorkgroupId = new UiInput { Name = inputName, Translate = inputTranslate, FieldType = fieldType, UiInputMethods = uiinputmethosd }; // متد اتصال ورودی var uiinputMethod = new UiInputMethod { ControllerName = controller, MethodName = type.ToString(), SubSystemName = area, UiInput = WorkgroupId, DefineControllerMethod = new DefineControllerMethod { MethodType = type } }; uiinputmethosd.Add(uiinputMethod); return(new UiFormInput { UiInput = WorkgroupId }); }
public Packet(ActionType actionType, MethodType method = MethodType.Json, Json?json = null) { Action = actionType; if (json == null) { Data = new byte[2] { Version, (byte)actionType }; return; } Method = method; Json = json; switch (Method) { case MethodType.Json: var str = json.ToString(); var byteAryForStr = _encoding.GetBytes(str); Data = new byte[byteAryForStr.Length + 3]; Data[0] = Version; Data[1] = (byte)actionType; Data[2] = (byte)method; Array.Copy(byteAryForStr, 0, Data, 3, byteAryForStr.Length); break; default: throw new ArgumentException("unknown MethodType: " + Method.ToString()); } }
private Tuple <HttpStatusCode, string> GetResponse(string data, string parameters, MethodType method) { var request2 = (HttpWebRequest)WebRequest.Create("http://localhost:8080" + parameters); request2.Method = method.ToString(); if (method == MethodType.PUT) { using (var writer = new StreamWriter(request2.GetRequestStream())) { writer.Write(data); } } var result = ""; var response2 = (HttpWebResponse)request2.GetResponse(); using (var stream = new StreamReader(response2.GetResponseStream())) { result = stream.ReadToEnd(); } response2.Close(); return(new Tuple <HttpStatusCode, string>(response2.StatusCode, result)); }
private HttpWebRequest CreateBaseRequest(string request, object headerObj, MethodType method) { HttpWebRequest baseHttpWebRequest = (HttpWebRequest)WebRequest.Create($"{baseUrl}{request}"); baseHttpWebRequest.Method = method.ToString(); if (credential != null) { baseHttpWebRequest.Credentials = credential; } switch (method) { case MethodType.GET: GET(ref baseHttpWebRequest); break; case MethodType.POST: POST(ref baseHttpWebRequest, headerObj); break; case MethodType.PUT: PUT(ref baseHttpWebRequest); break; case MethodType.DELETE: DELETE(ref baseHttpWebRequest); break; } return(baseHttpWebRequest); }
/// </summary> /// <param name="typeName">Çağıralacak metodun bulunduğu dll ismi. örn: Royal.Operation</param> /// <param name="typeName">Çağıralacak class. Namespace ile birlikte yazılacak. örn: Royal.Operation.AsinBusiness</param> /// <param name="methodName">Çağıralacak metod. Sadece metod ismi. Örn: GetAsins()</param> /// <param name="methodType">Static metodları çağırmak için Static. Instance oluşturup çağırılan metodlar için Standard.</param> /// <param name="arguments">metoda gönderilecek parametreler.</param> /// <returns>object döner, null döner. gün gelir hesap döner....</returns> public T InvokeMethod <T>(string assemblyName, string typeName, string methodName, MethodType methodType, Object[] arguments) { string url = ConfigHelper.Instance.GetApiUrl(); if (apiUrl != string.Empty) { url = apiUrl; } RestClient client = new RestClient(url); var request = new RestRequest("api/App/Invoker", Method.POST); request.AddHeader("Authorization", this.accesskey); List <Criteria> parameters = new List <Criteria>(); parameters.Add(new Criteria { Key = "TypeName", Value = typeName }); parameters.Add(new Criteria { Key = "AssemblyName", Value = assemblyName }); parameters.Add(new Criteria { Key = "MethodName", Value = methodName }); parameters.Add(new Criteria { Key = "MethodType", Value = methodType.ToString() }); parameters.Add(new Criteria { Key = "Arguments", Value = arguments }); request.AddJsonBody(parameters); IRestResponse response = client.Execute(request); // ServiceResponse<object> sr = SimpleJson.DeserializeObject<ServiceResponse<object>>(res.Content); //ServiceResponse<object> sr = new RestSharp.Deserializers.JsonDeserializer().Deserialize<ServiceResponse<object>>(res); // ServiceResponse <Object> serviceResponse2 = JsonHelper.Instance.DeserializeObject <ServiceResponse <Object> >(response.Content); if (serviceResponse2.ResponseCode == 1) { if (serviceResponse2.ResponseObject == null) { return((T)Convert.ChangeType(serviceResponse2.ResponseObject, typeof(T))); } string jsonString = serviceResponse2.ResponseObject.ToString(); try { T xx = JsonHelper.Instance.DeserializeObject <T>(jsonString); return(xx); } catch (Newtonsoft.Json.JsonReaderException) { return((T)Convert.ChangeType(serviceResponse2.ResponseObject, typeof(T))); } } else { throw new Exception(serviceResponse2.ResponseMessage); } }
private static WebRequest SetupConnection(Uri url, MethodType methodType) { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = methodType.ToString().ToUpperInvariant(); request.Headers.Add("Accept-Encoding", "gzip"); request.AutomaticDecompression = DecompressionMethods.GZip; return(request); }
private static WebRequest SetupConnection(Uri url, MethodType methodType) { var request = WebRequest.Create(url); request.Method = methodType.ToString().ToUpperInvariant(); request.Headers.Add("Accept-Encoding", "gzip"); return(request); }
public string GenerateCode(CodeGenStyle style = null) { if (style == null) { style = new CodeGenStyle(); } var builder = new StringBuilder(); if (Comment != null) { builder.AppendLine(Comment.GenerateCode(style)); } foreach (var attribute in Attributes) { builder.AppendLine(attribute.GenerateCode(style)); } builder.Append(style.Indent); builder.Append(Scope.ToString().ToLower()); builder.Append(" "); if (MethodType != MethodType.Normal) { builder.Append(MethodType.ToString().ToLower()); builder.Append(" "); } if (Async) { builder.Append("async "); } var genericList = GenericTypes.Select(gt => gt.Name).ToTypeParamList(); var argList = string.Join(", ", Parameters); builder.AppendLine($"{ReturnType} {Name}{genericList}({argList})"); foreach (var constrainedGeneric in GenericTypes.Where(gt => gt.Constraint != null)) { style.IndentCount++; builder.AppendLine($"{style.Indent}where {constrainedGeneric.Name} : {constrainedGeneric.Constraint}"); style.IndentCount--; } builder.AppendLine($"{style.Indent}{{"); style.IndentCount++; builder.AppendLine(style.IndentMultilineString(Body)); style.IndentCount--; builder.Append($"{style.Indent}}}"); return(builder.ToString()); }
protected TResponse Request <T, TResponse>(MethodType method, string uri, T request) { string httpMethod = method.ToString(), data = string.Empty; if (request != null) { data = JsonConvert.SerializeObject(request, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); } var webRequest = (HttpWebRequest)WebRequest.Create(_config.Endpoint + uri); webRequest.KeepAlive = false; webRequest.ProtocolVersion = HttpVersion.Version10; webRequest.Method = httpMethod; byte[] postBytes = Encoding.ASCII.GetBytes(data); webRequest.ContentType = "application/json"; webRequest.ContentLength = postBytes.Length; webRequest.Credentials = new NetworkCredential(_config.Username, _config.Password); if (postBytes.Length > 0) { using (Stream requestStream = webRequest.GetRequestStream()) { requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); } } HttpWebResponse response; try { response = (HttpWebResponse)webRequest.GetResponse(); string httpResponse = new StreamReader(response.GetResponseStream()).ReadToEnd(); var result = JsonConvert.DeserializeObject <TResponse>(httpResponse); return(result); } catch (WebException e) { var responseData = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); throw new Exception(); } }
protected TResponse Request <T, TResponse>(MethodType method, string uri, T request) { string httpMethod = method.ToString(), data = string.Empty; if (request != null) { data = JsonConvert.SerializeObject(request, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); } var webRequest = (HttpWebRequest)WebRequest.Create(_config.Endpoint + uri); webRequest.KeepAlive = false; webRequest.ProtocolVersion = HttpVersion.Version10; webRequest.Method = httpMethod; byte[] postBytes = Encoding.ASCII.GetBytes(data); webRequest.ContentType = "application/json"; webRequest.ContentLength = postBytes.Length; //webRequest.Credentials = new NetworkCredential(_config.Username, _config.Password); string credentialsFormatted = string.Format("{0}:{1}", _config.Username, _config.Password); byte[] credentialBytes = Encoding.ASCII.GetBytes(credentialsFormatted); string basicCredentials = Convert.ToBase64String(credentialBytes); webRequest.Headers["Authorization"] = "Basic " + basicCredentials; if (postBytes.Length > 0) { using (Stream requestStream = webRequest.GetRequestStream()) { requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); } } HttpWebResponse response; response = (HttpWebResponse)webRequest.GetResponse(); string httpResponse = new StreamReader(response.GetResponseStream()).ReadToEnd(); var result = JsonConvert.DeserializeObject <TResponse>(httpResponse); return(result); }
public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "form"; output.Attributes.SetAttribute("method", MethodType.ToString()); output.Attributes.SetAttribute("data-ajax", "true"); output.Attributes.SetAttribute("data-ajax-url", this.Action); if (!string.IsNullOrEmpty(this.OnSuccess)) { output.Attributes.SetAttribute("data-ajax-success", OnSuccess); } if (!string.IsNullOrEmpty(this.OnComplete)) { output.Attributes.SetAttribute("data-ajax-complete", this.OnComplete); } }
/// <summary> /// На консоль. /// </summary> public void ToConsole() { const int smesh = 3; Console.ForegroundColor = ConsoleColor.White; Console.Write($"{"",3 * smesh}'"); Console.ForegroundColor = ConsoleColor.Blue; Console.Write($"{MethodType.ToString()}"); Console.ForegroundColor = ConsoleColor.White; Console.Write($"' - "); Console.ForegroundColor = ConsoleColor.White; Console.Write($"{MethodAttribute.About}"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(); }
private void HandleFailure(HttpResponseMessage response, LogContext logContext, MethodType methodType) { string errorMessage = GetErrorDescription(response.Content, logContext, methodType); logger?.LogError( logContext.EventId, "{CorrelationId} {HttpMethod} Response {HttpCode} ({HttpReason}) {ErrorMessage}", logContext.CorrelationId, methodType.ToString().ToUpperInvariant(), (int)response.StatusCode, response.ReasonPhrase, errorMessage); throw ExceptionMapper.Map((int)response.StatusCode, response.ReasonPhrase, errorMessage); }
private WebRequest CreateWebRequest(MethodType methodType) { Enforce.NotNullOrEmpty(Url); string requestUrl = (methodType == MethodType.Get && Parameters.Count > 0) ? Url + "?" + Parameters.ToQueryParameter() : Url; var req = WebRequest.CreateHttp(requestUrl); req.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(methodType); req.Headers["X-User-Agent"] = AppBootstrapper.UserAgentVersion; req.Method = methodType.ToString().ToUpper(); if (methodType == MethodType.Post) req.ContentType = "application/x-www-form-urlencoded"; return req; }
private string GenerateSignature(Uri uri, MethodType methodType, Token token, IEnumerable<KeyValuePair<string, object>> parameters) { var hmacKeyBase = ConsumerSecret.UrlEncode() + "&" + ((token == null) ? "" : token.Secret).UrlEncode(); using (var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(hmacKeyBase))) { var stringParameter = parameters.OrderBy(p => p.Key) .ThenBy(p => p.Value) .ToQueryParameter(); var signatureBase = methodType.ToString().ToUpper() + "&" + uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped).UrlEncode() + "&" + stringParameter.UrlEncode(); var hash = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase)); return Convert.ToBase64String(hash).UrlEncode(); } }
private string GenerateSignature(Uri uri, MethodType methodType, Token token, IEnumerable <KeyValuePair <string, object> > parameters) { var hmacKeyBase = ConsumerSecret.UrlEncode() + "&" + ((token == null) ? "" : token.Secret).UrlEncode(); using (var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(hmacKeyBase))) { var stringParameter = parameters.OrderBy(p => p.Key) .ThenBy(p => p.Value) .ToQueryParameter(); var signatureBase = methodType.ToString().ToUpper() + "&" + uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped).UrlEncode() + "&" + stringParameter.UrlEncode(); var hash = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase)); return(Convert.ToBase64String(hash).UrlEncode()); } }
private T Execute <T>(MethodType type, string parameters) { try { T data; HttpWebRequest request = WebRequest.CreateHttp($"{baseURL}/{parameters}"); request.Method = type.ToString(); try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string json = reader.ReadToEnd(); data = JsonConvert.DeserializeObject <T>(json); } } } } catch (WebException e) { HttpWebResponse webResponse = (HttpWebResponse)e.Response; if (webResponse.StatusCode == HttpStatusCode.NotFound) { data = default(T); } else { throw; } } return(data); } catch (Exception e) { return(default(T)); } finally { } }
bool SendRequest(string method, MethodType type, string body, out string answer) { var webRequest = (HttpWebRequest)WebRequest.Create(BuildUrl(method)); webRequest.Timeout = 1000; webRequest.Method = type.ToString(); answer = string.Empty; try { if (body != null) { var data = Encoding.UTF8.GetBytes(body); webRequest.ContentLength = data.Length; var requestStream = webRequest.GetRequestStream(); using (var writer = new StreamWriter(requestStream)) { writer.Write(body); } } var webResponse = (HttpWebResponse)webRequest.GetResponse(); var responseStream = webResponse.GetResponseStream(); if (responseStream != null && responseStream.CanRead) { using (var streamReader = new StreamReader(responseStream)) { answer = streamReader.ReadToEnd(); return(true); } } return(true); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.ReceiveFailure || ex.Status == WebExceptionStatus.NameResolutionFailure) { answer = string.Empty; return(false); } throw; } }
private WebRequest CreateWebRequest(MethodType methodType) { Enforce.NotNullOrEmpty(Url); string requestUrl = (methodType == MethodType.Get && Parameters.Count > 0) ? Url + "?" + Parameters.ToQueryParameter() : Url; var req = WebRequest.CreateHttp(requestUrl); req.Headers[HttpRequestHeader.Authorization] = GetAuthorizationHeader(methodType); req.Headers["X-User-Agent"] = AppBootstrapper.UserAgentVersion; req.Method = methodType.ToString().ToUpper(); if (methodType == MethodType.Post) { req.ContentType = "application/x-www-form-urlencoded"; } return(req); }
private void LogPostMethodCall(MethodType methodType, LogContext logContext, HttpResponseMessage response, string responseContent) { string httpMethod = methodType.ToString().ToUpperInvariant(); logger?.LogInformation( logContext.EventId, "{CorrelationId} {HttpMethod} Response {HttpCode} {HttpReason}", logContext.CorrelationId, httpMethod, (int)response.StatusCode, response.ReasonPhrase); logger?.LogDebug( logContext.EventId, "{CorrelationId} {HttpMethod} Response Body\n{ResponseBody}", logContext.CorrelationId, httpMethod, responseContent); }
/// <summary> /// Processing request data before action /// </summary> /// <param name="request"></param> /// <param name="methodType"></param> /// <returns></returns> private static CleantalkRequest Preprocessing(CleantalkRequest request, MethodType methodType) { if (string.IsNullOrWhiteSpace(request.AuthKey)) { throw new ArgumentNullException("AuthKey is empty"); } switch (methodType) { case MethodType.check_message: //nothing to do break; case MethodType.check_newuser: if (string.IsNullOrWhiteSpace(request.SenderNickname)) { throw new ArgumentNullException("SenderNickname is empty"); } if (string.IsNullOrWhiteSpace(request.SenderEmail)) { throw new ArgumentNullException("SenderEmail is empty"); } break; case MethodType.send_feedback: if (string.IsNullOrWhiteSpace(request.Feedback)) { throw new ArgumentNullException("Feedback is empty"); } break; default: throw new ArgumentOutOfRangeException("methodType", methodType, null); } request.MethodName = methodType.ToString(); return(request); }
private void LogMethodCall(MethodType methodType, Uri requestUri, LogContext logContext, string requestData = null) { string httpMethod = methodType.ToString().ToUpperInvariant(); logger?.LogInformation( logContext.EventId, "{CorrelationId} {HttpMethod} Request {RequestUri}", logContext.CorrelationId, httpMethod, requestUri); if (!string.IsNullOrWhiteSpace(requestData)) { logger?.LogDebug( logContext.EventId, "{CorrelationId} {HttpMethod} Request Body\n{RequestBody}", logContext.CorrelationId, httpMethod, requestData); } }
private static void Execute(CommandLineApplication parent, MethodType methodType, string description, PveClient client, ClassApi classApiRoot) { parent.Command(methodType.ToString().ToLower(), cmd => { cmd.Description = description; cmd.AddFullNameLogo(); var optVerbose = cmd.VerboseOption(); var argResource = CreateResourceArgument(cmd); var argParameters = cmd.Argument("parameters", "Parameter for resource format key:value (Multiple)." + " If value have space or special charapter using quote 'key:value'", true); var optOutput = cmd.OptionEnum <ApiExplorer.OutputType>("--output|-o", "Type output (default: unicode)"); var optWait = cmd.WaitOption(); cmd.OnExecute(() => { client = client ?? parent.ClientTryLogin(); classApiRoot = classApiRoot ?? GetClassApiRoot(client); var ret = ApiExplorer.Execute(client, classApiRoot, argResource.Value, methodType, ApiExplorer.CreateParameterResource(argParameters.Values), optWait.HasValue(), optOutput.GetEnumValue <ApiExplorer.OutputType>(), optVerbose.HasValue()); parent.Out.Write(ret.ResultText); return(ret.ResultCode); }); }); }
public static FilterBase Restore(string[] tokens) { if (tokens.Length != 4) { return(null); } int factor; if (!Int32.TryParse(tokens[1], out factor) || factor <= 1 || !IsPowerOfTwo(factor)) { return(null); } int windowLength; if (!Int32.TryParse(tokens[2], out windowLength) || windowLength < 4 || !IsPowerOfTwo(windowLength + 1)) { return(null); } MethodType method = MethodType.NUM; for (int i = 0; i < (int)MethodType.NUM; ++i) { MethodType t = (MethodType)i; if (0 == string.Compare(tokens[3], t.ToString())) { method = t; } } if (method == MethodType.NUM) { return(null); } return(new WindowedSincUpsampler(factor, windowLength, method)); }
public string ComposeStringToSign(MethodType? method, string uriPattern, ISigner signer, Dictionary<string, string> queries, Dictionary<string, string> headers, Dictionary<string, string> paths) { var sortedDictionary = SortDictionary(queries); StringBuilder canonicalizedQueryString = new StringBuilder(); foreach (var p in sortedDictionary) { canonicalizedQueryString.Append("&") .Append(AcsURLEncoder.PercentEncode(p.Key)).Append("=") .Append(AcsURLEncoder.PercentEncode(p.Value)); } StringBuilder stringToSign = new StringBuilder(); stringToSign.Append(method.ToString()); stringToSign.Append(SEPARATOR); stringToSign.Append(AcsURLEncoder.PercentEncode("/")); stringToSign.Append(SEPARATOR); stringToSign.Append(AcsURLEncoder.PercentEncode( canonicalizedQueryString.ToString().Substring(1))); return stringToSign.ToString(); }
internal bool SendOutTo(Stream stream) { bool result = false; try { BinaryWriter binaryWriter = new BinaryWriter(stream); binaryWriter.Write($"{MethodType.ToString().ToUpper()} {CurrentUri.PathAndQuery} HTTP/1.1".GetASCIIBytes()); binaryWriter.Write(EOL); SendHeaders(binaryWriter); binaryWriter.Write(EOL); byte[] array = (RawData != null) ? RawData : (((object)FieldsImpl == null) ? null : FieldsImpl.get_data()); if (array != null && array.Length > 0) { binaryWriter.Write(array, 0, array.Length); } result = true; return result; } catch { return result; } }
private void UpdateTexts() { _laneLabel.text = "Lane " + (_laneIndex + 1); _interpolationPanel.gameObject.SetActive(_methodType == MethodType.FixedUpdate && _physicsSyncType == PhysicsSyncType.Default); _bodyPanel.gameObject.SetActive(_movementType != MovementType.CharacterController_Move); if (_physicsSyncType == PhysicsSyncType.Default) { _methodText.text = _methodType.ToString(); _methodButton.interactable = true; } else { _methodText.text = MethodType.Update.ToString(); _methodButton.interactable = false; } _bodyText.text = _bodyType.ToString(); _movementText.text = _movementType.ToString().Replace("_", "."); _interpolationText.text = _interpolationType.ToString().Replace("_", " "); }
/// <summary> /// Processing request data before action /// </summary> /// <param name="request"></param> /// <param name="methodType"></param> /// <returns></returns> private static CleantalkRequest Preprocessing(CleantalkRequest request, MethodType methodType) { if (string.IsNullOrWhiteSpace(request.AuthKey)) { throw new ArgumentNullException("AuthKey is empty"); } switch (methodType) { case MethodType.check_message: //nothing to do break; case MethodType.check_newuser: if (string.IsNullOrWhiteSpace(request.SenderNickname)) { throw new ArgumentNullException("SenderNickname is empty"); } if (string.IsNullOrWhiteSpace(request.SenderEmail)) { throw new ArgumentNullException("SenderEmail is empty"); } break; case MethodType.send_feedback: if (string.IsNullOrWhiteSpace(request.Feedback)) { throw new ArgumentNullException("Feedback is empty"); } break; default: throw new ArgumentOutOfRangeException("methodType", methodType, null); } request.MethodName = methodType.ToString(); return request; }
public string CallRestService(string methodUrl, string requestBody, MethodType methodType, string contentType = "application/json; charset=utf-8") { StringBuilder returnValue = null; HttpWebRequest request = null; HttpWebResponse response = null; Stream resStream = null; try { request = (HttpWebRequest)WebRequest.Create(BaseUrl + methodUrl); request.Method = methodType.ToString(); if (CustomHeaders != null) request.Headers.Add(CustomHeaders); if (methodType == MethodType.POST) { request.ContentType = contentType; byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody); request.ContentLength = byteData.Length; using (Stream sw = request.GetRequestStream()) { if (byteData.Length > 0) sw.Write(byteData, 0, byteData.Length); } } request.Timeout = _timeout; response = (HttpWebResponse)request.GetResponse(); resStream = response.GetResponseStream(); returnValue = new StringBuilder(); if (resStream != null && resStream.CanRead) { using (var sr = new StreamReader(resStream)) { const int bufferSize = 4096; var buffer = new char[bufferSize]; int byteCount = sr.Read(buffer, 0, buffer.Length); while (byteCount > 0) { returnValue.Append(new string(buffer, 0, byteCount)); byteCount = sr.Read(buffer, 0, buffer.Length); } } } } catch (Exception) { throw; } finally { if (response != null) { response.Close(); } if (resStream != null) { resStream.Close(); resStream.Dispose(); } } return returnValue.ToString(); }
private void RunMethod(Process p, Activity a, MethodType type) { //Do a quick check switch (type) { case MethodType.PreMethod: if (!a.PreMethodCall.NeedToInvoke) return; break; case MethodType.PostMethod: if (!a.PostMethodCall.NeedToInvoke) return; break; } string sAssembly = (type == MethodType.PreMethod) ? a.PreMethodCall.Assembly : a.PostMethodCall.Assembly; string sClass = (type == MethodType.PreMethod) ? a.PreMethodCall.Class : a.PostMethodCall.Class; string sMethod = (type == MethodType.PreMethod) ? a.PreMethodCall.Method : a.PostMethodCall.Method; List<string> sParameters = (type == MethodType.PreMethod) ? a.PreMethodCall.Parameters : a.PostMethodCall.Parameters; //Run method. try { InvokeMethod(p, a, sAssembly, sClass, sMethod, sParameters); SendResult(new TestResultArgs(p, a, (type == MethodType.PreMethod) ? TestResultStage.ActivityPreMethodExecuted : TestResultStage.ActivityPostMethodExecuted)); } catch (Exception ex) { if (ex.IsFatal()) { throw; } //TODO: refactor to use FailTest p.ActivityExecutionError = a.ActivityExecutionError = ex.Message.ToString(); SendResult(new TestResultArgs(p, a, TestResultStage.ActivityExecutionError, type.ToString() + " execution error : " + p.ActivityExecutionError)); p.ProcessHasUnexpectedErrors = true; } }
/// <summary> /// Generates the signature. /// </summary> /// <param name="t">The tokens.</param> /// <param name="httpMethod">The HTTP method.</param> /// <param name="url">The URL.</param> /// <param name="prm">The parameters.</param> /// <returns>The signature.</returns> internal static string GenerateSignature(Tokens t, MethodType httpMethod, Uri url, IEnumerable<KeyValuePair<string, string>> prm) { var key = Encoding.UTF8.GetBytes( string.Format("{0}&{1}", UrlEncode(t.ConsumerSecret), UrlEncode(t.AccessTokenSecret))); var prmstr = prm.Select(x => new KeyValuePair<string, string>(UrlEncode(x.Key), UrlEncode(x.Value))) .Concat( url.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => { var s = x.Split('='); return new KeyValuePair<string, string>(s[0], s[1]); }) ) .OrderBy(x => x.Key).ThenBy(x => x.Value) .Select(x => x.Key + "=" + x.Value) .JoinToString("&"); var msg = Encoding.UTF8.GetBytes( string.Format("{0}&{1}&{2}", httpMethod.ToString().ToUpperInvariant(), UrlEncode(url.GetComponents(UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped)), UrlEncode(prmstr) )); return Convert.ToBase64String(SecurityUtils.HmacSha1(key, msg)); }