private static RestRequest CreateRequest(string resource, Method method) { return new RestRequest(resource, method) { JsonSerializer = _newtonsoftJsonSerializer }; }
public RealFourierTransform(int length) { _numberOfData = length; if(length<1) throw new ArgumentException("length smaller than 1 is not appropriate here."); else if(length<3) { _method = Method.Trivial; } else if(Calc.BinaryMath.IsPowerOfTwo(length)) { // use Hartley transform _method = Method.Hartley; } else if(Pfa235FFT.CanFactorized(length)) { // use Pfa235 transform _method = Method.Pfa235; _pfa235 = new Pfa235FFT(_numberOfData); } else { // use chirp transform _method = Method.Chirp; } }
public static bool IsMain(Method m) { // In order to be a legal Main() method, the following must be true: // The method takes no parameters // The method is not a ghost method // The method has no requires clause // The method has no modifies clause // If the method is an instance (that is, non-static) method in a class, then the enclosing class must not declare any constructor // Or if a method is annotated with {:main} and the above restrictions apply, except it is allowed to take ghost arguments, // and it is allowed to have preconditions and modifies. This lets the programmer add some explicit assumptions about the outside world, // modeled, for example, via ghost parameters. if (!m.IsGhost && m.Name == "Main" && m.TypeArgs.Count == 0 && m.Ins.Count == 0 && m.Outs.Count == 0 && m.Req.Count == 0 && m.Mod.Expressions.Count == 0 && (m.IsStatic || (((ClassDecl)m.EnclosingClass) == null) || !((ClassDecl)m.EnclosingClass).HasConstructor)) { return true; } else if (Attributes.Contains(m.Attributes, "main") && !m.IsGhost && m.TypeArgs.Count == 0 && m.Outs.Count == 0 && (m.IsStatic || (((ClassDecl)m.EnclosingClass) == null) || !((ClassDecl)m.EnclosingClass).HasConstructor)) { if (m.Ins.Count == 0) { return true; } else { bool isGhost = true; foreach (var arg in m.Ins) { if (!arg.IsGhost) { isGhost = false; } } return isGhost; } } else { return false; } }
public static void Link(Core.Action action, Method method) { action.Method = method; action.MethodID = method.MethodID; method.Actions.Add(action); }
private static RestRequest GetRequest(Method method, string resource) { var request = new RestRequest(method); request.Resource = resource; request.JsonSerializer = new RestSharpJsonNetSerializer(); return request; }
public ActionResult Execute(Type modelType, string methodName, int index, string key = null) { var typeMapping = ModelMappingManager.MappingFor(modelType); var methods = key != null ? typeMapping.InstanceMethods : typeMapping.StaticMethods; var mapping = methods.FirstOrDefault(m => m.MethodName.Equals(methodName, StringComparison.InvariantCultureIgnoreCase) && m.Index == index); if (mapping == null) throw new RunningObjectsException(string.Format("No method found with name {2} at index {0} for type {1}", index, modelType.PartialName(), methodName)); var method = new Method(new MethodDescriptor(mapping, ControllerContext.GetActionDescriptor(RunningObjectsAction.Execute))); if (!method.Parameters.Any()) { return ExecuteMethodOf ( modelType, method, () => OnSuccess(modelType)(null), OnSuccessWithReturn(method), OnException(method), HttpNotFound, key ); } if (!method.Descriptor.Mapping.Method.IsStatic) { method.Instance = GetInstanceOf(modelType, key, new ModelDescriptor(typeMapping)); RunningObjectsSetup.Configuration.Query.RemoveKeywordEvaluator("{instance}"); RunningObjectsSetup.Configuration.Query.KeywordEvaluators.Add("{instance}", q => method.Instance); } return !ControllerContext.IsChildAction ? (ActionResult)View(method) : PartialView(method); }
public CardsRequest(ICardId card, string resource = "", Method method = Method.GET) : base("cards/{cardId}/" + resource, method) { Guard.NotNull(card, "card"); AddParameter("cardId", card.GetCardId(), ParameterType.UrlSegment); this.AddCommonCardParameters(); }
/// <summary> /// To download content /// </summary> /// <param name="url"></param> /// <param name="method"></param> /// <returns></returns> public static string DownloadContent(string url, Method method = Method.GET) { // Using RestSharp RestClient client = new RestClient(url); RestRequest request = new RestRequest(method); var response = client.Execute(request); // Checking for Exception if (response.ErrorException != null) { throw new WebException(response.ErrorMessage, response.ErrorException); } string content = response.Content; if (content == null) { return null; } var byteOrderMark = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); // Removing Byte Order Mark from Content if (content.StartsWith(byteOrderMark)) { content = content.Replace(byteOrderMark, string.Empty); } return content; }
internal PreVerbExecutionContext( Method method, object target, ParameterAndValue[] parameters) : base(method, target, parameters, new Dictionary<object, object>()) { }
protected override RestRequest PrepareRequest(string path, 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 = base.PrepareRequest(path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); var workContext = _workContextFactory(); var currentUser = workContext.CurrentCustomer; //Add special header with user name to each API request for future audit and logging if (currentUser != null && currentUser.IsRegisteredUser) { var userName = currentUser.OperatorUserName; if (string.IsNullOrEmpty(userName)) { userName = currentUser.UserName; } if (!string.IsNullOrEmpty(userName)) { request.AddHeader("VirtoCommerce-User-Name", userName); } } return request; }
private RestRequest BuildRequest(string endpoint, Method method, Dictionary<string, string> urlParams = null, Dictionary<string, string> inputParams = null, Dictionary<string, string> headerParams = null) { var request = new RestRequest(endpoint, method); if (urlParams == null) { urlParams = new Dictionary<string, string>(); } urlParams.Add("locale", _configService.Locale()); foreach (var entry in urlParams) { request.AddUrlSegment(entry.Key, entry.Value); } if (inputParams != null) { foreach (var entry in inputParams) { request.AddParameter(entry.Key, entry.Value); } } if (headerParams != null) { foreach (var entry in headerParams) { request.AddHeader(entry.Key, entry.Value); } } return request; }
public static string GetResponseString(this HttpWebRequest request, Method rt, string requestParams = null, Encoding encoding = null) { string responseData = string.Empty; request.Method = rt.ToString().Trim(); HttpWebResponse RawResponse = null; if (rt == Method.POST && requestParams != null) { encoding = encoding ?? Encoding.Default; byte[] bytes = encoding.GetBytes(requestParams.Trim()); request.ContentLength = bytes.Length; using (Stream outputStream = request.GetRequestStream()) outputStream.Write(bytes, 0, bytes.Length); } RawResponse = (HttpWebResponse)request.GetResponse(); encoding = Encoding.UTF8;// encoding ?? (String.IsNullOrWhiteSpace(RawResponse.CharacterSet) ? Encoding.Default : Encoding.GetEncoding(RawResponse.CharacterSet)); if (RawResponse.ContentEncoding == @"gzip") using (GZipStream _stream = new GZipStream(RawResponse.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReader _sr = new StreamReader(_stream, encoding)) responseData = _sr.ReadToEnd(); } else using (StreamReader _sr = new StreamReader(RawResponse.GetResponseStream())) { responseData = _sr.ReadToEnd(); } return responseData; }
public static IRestRequest CreateRequest(this IRequestFactory factory, Endpoint endpoint, Method method) { var request = factory.CreateRequest(); request.Resource = endpoint.Resource; request.Method = method; return request; }
public object Call(Method m) { if(m.ID != -1) { ProgramCounter = MethodTable[m.ID]; return null; } List<string> path = m.Name.Split(':').First().Split('.').ToList(); string lib = path.Last(); path.Remove(path.Last()); string BasePath = path.First(); path.Remove(path.First()); Package package; if (path.Count > 0) package = Package.getBasePackage(BasePath).getPackageAt(path); else package = Package.getBasePackage(BasePath); List<object> args = new List<object>(); for (int i = 0; i < m.Perms.Count; i++) { args.Add(ResolveRawValue(m.Perms[i])); } var s2 = m.Name.Split(':').Last(); Library Lib = package.getLibrary(lib); var d = Lib.Functions.Get(s2); return d.DynamicInvoke(args.ToArray()); }
/// <summary> /// Visits the call. /// </summary> /// <param name="destination">The destination.</param> /// <param name="receiver">The receiver.</param> /// <param name="callee">The callee.</param> /// <param name="arguments">The arguments.</param> /// <param name="isVirtualCall">if set to <c>true</c> [is virtual call].</param> /// <param name="programContext">The program context.</param> /// <param name="stateBeforeInstruction">The state before instruction.</param> /// <param name="stateAfterInstruction">The state after instruction.</param> public override void VisitCall( Variable destination, Variable receiver, Method callee, ExpressionList arguments, bool isVirtualCall, Microsoft.Fugue.IProgramContext programContext, Microsoft.Fugue.IExecutionState stateBeforeInstruction, Microsoft.Fugue.IExecutionState stateAfterInstruction) { if ((callee.DeclaringType.GetRuntimeType() == typeof(X509ServiceCertificateAuthentication) || callee.DeclaringType.GetRuntimeType() == typeof(X509ClientCertificateAuthentication)) && (callee.Name.Name.Equals("set_CertificateValidationMode", StringComparison.InvariantCultureIgnoreCase))) { IAbstractValue value = stateBeforeInstruction.Lookup((Variable)arguments[0]); IIntValue intValue = value.IntValue(stateBeforeInstruction); if (intValue != null) { X509CertificateValidationMode mode = (X509CertificateValidationMode)intValue.Value; if (mode != X509CertificateValidationMode.ChainTrust) { Resolution resolution = base.GetResolution(mode.ToString(), X509CertificateValidationMode.ChainTrust.ToString()); Problem problem = new Problem(resolution, programContext); base.Problems.Add(problem); } } } base.VisitCall(destination, receiver, callee, arguments, isVirtualCall, programContext, stateBeforeInstruction, stateAfterInstruction); }
public void open(VariabelDatabase database, EnegyData data, Posision pos) { Class config = new Class("Config"); Method get = new Method("get"); get.GetAgumentStack().push("string", "name"); get.SetBody(Get_caller); get.SetStatic(); config.SetMethod(get, data, database, pos); Method isScriptLock = new Method("isScriptLock"); isScriptLock.SetBody(IsScriptLock_caller); isScriptLock.SetStatic(); config.SetMethod(isScriptLock, data, database, pos); Method set = new Method("set"); set.GetAgumentStack().push("string", "name"); set.GetAgumentStack().push("string", "value"); set.SetBody(Set_caller); set.SetStatic(); config.SetMethod(set, data, database, pos); Method isLocked = new Method("isLocked"); isLocked.SetStatic(); isLocked.GetAgumentStack().push("string", "name"); isLocked.SetBody(IsLocked_caller); config.SetMethod(isLocked, data, database, pos); database.pushClass(config, data); }
public WebServiceRequest (string resource, Method method) : base (resource, method) { AddHeader("Authorization", "Bearer jh8nCJo5vGRYRji7eT2DzGSn4wkljIJjey8OI9F5iMos0tFezFvwdrcJZtBc3B4EZOPCz" + "7kcWzWUhqEvYSzY7br7hvXHFxVUnUE6OwdHPUjZojy5MLtWu9UDn1G9QrS6vuIRWtOH3J8mLAtswesmhWD8tHMiVoER9gd8UByg" + "1wojqpzi3YNa53uPzkwDZkLxjTjgkfKJBAXYtQxNvg7NbLiMf1lCe7LWlQjCNk7VnBYgt4kYlrCLsgVMsRswJP6R"); }
private void AnalyzeMethod(Method method) { var stCount = method.NumberOfLines(); var types = method.ReferencedTypes(); var cc = method.CyclomaticComplexity(); methodInfos.Add(method.FullName, Tuple.Create(stCount, cc, types.Select(t => t.FullName).ToList())); }
public override void Parse(Method method) { ArgumentUtility.CheckNotNull ("method", method); foreach (var interfaceDeclaration in IntrospectionUtility.InterfaceDeclarations(method)) MatchFragments(interfaceDeclaration, method); }
public IRestResponse Call(string resource, Method method) { var client = GetClient(); var request = GetRequest(method, resource); return client.Execute(request); }
public Interface(Namespace parentNamespace, XmlBindings.Interface xmlData, Overrides.XmlBindings.Interface overrides, Dictionary<string, QualifiableType> typeDictionary) { Debug.Assert(xmlData.Name.StartsWith("I")); string unprefixed = xmlData.Name.Substring(1); m_stylizedName = Formatter.Prefix + unprefixed; m_innerName = "I" + parentNamespace.ApiName + unprefixed; m_nativeNameOfInheritanceParent = xmlData.Extends; if (overrides != null && overrides.IsProjectedAsAbstract) { m_stylizedName = "I" + Formatter.Prefix + unprefixed; } m_methods = new List<Method>(); foreach (XmlBindings.Method xmlMethod in xmlData.Methods) { Method m = new Method(xmlMethod); m_methods.Add(m); } typeDictionary[parentNamespace.RawName + "::" + xmlData.Name] = this; }
public IRestRequest CreateRequest(string resource, Method method = Method.GET, params Parameter[] parameters) { return CreateRequest( () => { IRestRequest request = new RestRequest { Resource = resource, Method = method }; if (parameters.Length == 0) return request; foreach (var parameter in parameters) { request.AddParameter(parameter); } if (_headerProvider != null) _headerProvider.PopulateHeaders(ref request); return request; } ); }
public RestRequest(string resource, Method method) { ContentCollectionMode = ContentCollectionMode.MultiPartForFileParameters; Method = method; Resource = resource; Serializer = new Serializers.JsonSerializer(); }
protected RestRequest NewRequest(string path, Method method) { var request = new RestRequest(path, method); request.AddParameter("no-cache", DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture), ParameterType.GetOrPost); return request; }
internal void ExecuteGraphApiAsync(Method httpMethod, string graphPath, IDictionary<string, string> parameters, bool addAccessToken, Action<FacebookAsyncResult> callback) { var request = new RestRequest(graphPath, httpMethod); if (parameters != null) { foreach (var keyValuePair in parameters) request.AddParameter(keyValuePair.Key, keyValuePair.Value); } ExecuteGraphApiAsync( request, addAccessToken, Settings.UserAgent, response => { Exception exception; if (response.ResponseStatus == ResponseStatus.Completed) exception = (FacebookException)response.Content; else exception = new FacebookRequestException(response); if (callback != null) callback(new FacebookAsyncResult(response.Content, exception)); }); }
public CallInfo(Module vmModule, Method method, int instructionPointer) { Module = vmModule; Class = null; Method = method; InstructionPointer = instructionPointer; }
private bool IsMixingMessageContractParams(Method method) { bool hasMessageContract = false; bool hasOtherType = false; foreach (Parameter parameter in method.Parameters) { if (HasMessageContractAttribute(parameter.Type.Attributes)) { hasMessageContract = true; } else { hasOtherType = true; } if (hasMessageContract && hasOtherType) { return true; } } // check for return type if (HasMessageContractAttribute(method.ReturnType.Attributes)) { hasMessageContract = true; } else { hasOtherType = true; } return hasOtherType && hasMessageContract; }
/// <summary> /// This is used to acquire a <c>MethodPart</c> for the method /// provided. This will synthesize an XML annotation to be used for /// the method. If the method provided is not a setter or a getter /// then this will return null, otherwise it will return a part with /// a synthetic XML annotation. In order to be considered a valid /// method the Java Bean conventions must be followed by the method. /// </summary> /// <param name="method"> /// this is the method to acquire the part for /// </param> /// <returns> /// this is the method part object for the method /// </returns> public MethodPart GetInstance(Method method) { Annotation label = GetAnnotation(method); if(label != null) { return GetInstance(method, label); } return null; }
public override string Path(Method method = Method.GET) { string path = (_parent != null) ? _parent.Path(method) + "/" : "/"; if (_id != null) path += _id; return path; }
public IRestRequest CreateRequest(string resource, Method method = Method.GET, params KeyValuePair<string, string>[] parameters) { return CreateRequest( () => { IRestRequest request = new RestRequest { Resource = resource, Method = method }; if (parameters.Length == 0) return request; foreach (var kvp in parameters) { request.AddUrlSegment(kvp.Key, kvp.Value); } if (_headerProvider != null) _headerProvider.PopulateHeaders(ref request); return request; } ); }
/// <summary> /// Initializes a new instance of the <see cref="RestRequest"/> class. /// </summary> /// <param name="method">Method to use for this request.</param> public RestRequest(Method method) : base(method) { IntializeJsonSerializer(); }
public PrintStatement(Method method) { this.method = method; }
/// <summary> /// Executes an async request and serializes the response to an object. /// </summary> public async Task <T> ExecuteRequestAsync <T>(Method method, string resource, object requestBody = null, CancellationToken token = default(CancellationToken)) { var result = await ExecuteRequestAsync(method, resource, requestBody, token).ConfigureAwait(false); return(JsonConvert.DeserializeObject <T>(result.ToString(), Settings.JsonSerializerSettings)); }
public object Invoke(params object[] parameters) { return(Method.Invoke(Target, parameters)); }
public IOControlCode(uint deviceType, uint function, Method method, Access access) { code = (deviceType << 16) | ((uint)access << 14) | (function << 2) | (uint)method; }
private ClientResponse SendRequest(Method method, string fullFileName = "") { //ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_uri); httpWebRequest.Timeout = 1000000; // log messages //log.DebugFormat("Request Type: {0}", method.ToString()); //log.DebugFormat("Request Headers: {0}, Accept: {1}", _headers, _accept); //log.DebugFormat(" Request Url : {0}", _uri); if (method == Method.PUT || method == Method.POST) { //log.DebugFormat("Body: {0} ", _body); //log.DebugFormat("Content Type: {0}", _contentType); } if (_headers != null) { httpWebRequest.Headers = _headers; } if (_accept != null) { httpWebRequest.Accept = _accept; } if (_clientCert != null) { httpWebRequest.ClientCertificates.Add(_clientCert); } httpWebRequest.CookieContainer = _cookies; httpWebRequest.Method = method.ToString(); httpWebRequest.ContentType = _contentType; httpWebRequest.Proxy = _proxy; if (_gzipContentEncoding == true) { httpWebRequest.AutomaticDecompression = System.Net.DecompressionMethods.GZip; } if (!string.IsNullOrEmpty(_body)) { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(_body); // Set the content length of the string being posted. httpWebRequest.ContentLength = byte1.Length; Stream newStream = httpWebRequest.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); // Close the Stream object. newStream.Close(); } else { httpWebRequest.ContentLength = 0; } if (string.IsNullOrEmpty(fullFileName)) { try { return(new ClientResponse((HttpWebResponse)httpWebRequest.GetResponse())); } catch (WebException e) { return(new ClientResponse(e)); } } else { try { try { new Task(() => { DownloadFile(httpWebRequest, fullFileName); }).Start(); } catch //(Exception ex) { //log.Error(ex); } Uri newUri = new Uri(_uri.AbsoluteUri.Substring(0, _uri.AbsoluteUri.LastIndexOf('/'))); HttpWebRequest httpWebRequestForPing = (HttpWebRequest)WebRequest.Create(newUri); HttpWebRequestDefinition(method, ref httpWebRequestForPing); return(new ClientResponse((HttpWebResponse)httpWebRequestForPing.GetResponse())); } catch (WebException e) { return(new ClientResponse(e)); } } }
/// <summary> /// Initializes a new instance of the <see cref="RestRequest"/> class. /// </summary> /// <param name="resource">Resource to use for this request.</param> /// <param name="method">Method to use for this request.</param> public RestRequest(Uri resource, Method method) : base(resource, method) { IntializeJsonSerializer(); }
public Commands(Method method) { this.method = method; }
public void GenerateMethod(Method method) { if (ASTUtils.CheckIgnoreMethod(method, Options)) { return; } PushBlock(CLIBlockKind.Method, method); GenerateDeclarationCommon(method); if ((method.IsVirtual || method.IsOverride) && !method.IsOperator) { Write("virtual "); } var isBuiltinOperator = method.IsOperator && Operators.IsBuiltinOperator(method.OperatorKind); if (method.IsStatic || isBuiltinOperator) { Write("static "); } if (method.OperatorKind == CXXOperatorKind.ExplicitConversion) { Write("explicit "); } if (method.IsConstructor || method.IsDestructor || method.OperatorKind == CXXOperatorKind.Conversion || method.OperatorKind == CXXOperatorKind.ExplicitConversion) { Write("{0}(", GetMethodName(method)); } else { Write("{0} {1}(", method.ReturnType, method.Name); } GenerateMethodParameters(method); Write(")"); if (method.IsOverride) { if (method.Access == AccessSpecifier.Private) { Write(" sealed"); } Write(" override"); } WriteLine(";"); if (method.OperatorKind == CXXOperatorKind.EqualEqual) { GenerateEquals(method, (Class)method.Namespace); } PopBlock(NewLineKind.BeforeNextBlock); }
public override Method VisitMethod(Method method) { // body might not have been materialized, so make sure we do that first! Block body = method.Body; if (method == null) { return(null); } BlockSorter blockSorter = new BlockSorter(); BlockList sortedBlocks = blockSorter.SortedBlocks; this.SucessorBlock = blockSorter.SuccessorBlock; this.StackLocalsAtEntry = new TrivialHashtable(); this.localsStack = new LocalsStack(); ExceptionHandlerList ehandlers = method.ExceptionHandlers; for (int i = 0, n = ehandlers == null ? 0 : ehandlers.Count; i < n; i++) { ExceptionHandler ehandler = ehandlers[i]; if (ehandler == null) { continue; } Block handlerStart = ehandler.HandlerStartBlock; if (handlerStart == null) { continue; } LocalsStack lstack = new LocalsStack(); this.StackLocalsAtEntry[handlerStart.UniqueKey] = lstack; if (ehandler.HandlerType == NodeType.Catch) { lstack.exceptionHandlerType = CoreSystemTypes.Object; if (ehandler.FilterType != null) { lstack.exceptionHandlerType = ehandler.FilterType; } } else if (ehandler.HandlerType == NodeType.Filter) { lstack.exceptionHandlerType = CoreSystemTypes.Object; if (ehandler.FilterExpression != null) { lstack = new LocalsStack(); lstack.exceptionHandlerType = CoreSystemTypes.Object; this.StackLocalsAtEntry[ehandler.FilterExpression.UniqueKey] = lstack; } } } blockSorter.VisitMethodBody(body); for (int i = 0, n = sortedBlocks.Count; i < n; i++) { Block b = sortedBlocks[i]; if (b == null) { Debug.Assert(false); continue; } this.VisitBlock(b); } return(method); }
public API_Response Get(string parameter, Method method) { return(Get(parameter, method, "", "")); }
private void put(Method m) { // FOR-DEBUG calls.putInt(0xBADF00D); calls.put((byte)m); // FOR-DEBUG calls.putInt(0xBADF00D); }
public Result NewObj <ArgList> (APC pc, Method ctor, SymbolicValue dest, ArgList args, Data data) where ArgList : IIndexable <SymbolicValue> { return(this.visitor.NewObj(pc, ctor, dest, Convert(pc, args), data)); }
public API_Response Get(string parameter, Method method, string json, string bearer) { string url = "https://" + IPAddress + ":8443/api" + parameter; API_Response apiResponse = null; int loop = 0; bool complete = false; DateTime datetime = DateTime.MinValue; if (parameter == string.Empty || IPAddress == string.Empty) { throw new Exception("You must provide a paramater and/or IP address"); } while (loop <= Retries && !complete) { apiResponse = new API_Response(); IsError = false; ErrorMessage = string.Empty; Response = string.Empty; datetime = DateTime.Now; HttpWebRequest request = null; HttpWebResponse response = null; try { if (Debug) { Console.WriteLine("Atempt " + (loop + 1).ToString() + " of " + (Retries + 1).ToString()); Console.WriteLine("Sending WebRequest: " + method.ToString() + " " + url); } request = (HttpWebRequest)WebRequest.Create(url); // SSL Certificate is Self-Signed, ignore validatation. ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; // Set SSL Protocol to TLS 1.2 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; request.ContentType = "application/json"; request.Accept = "application/json"; request.Method = method.ToString(); request.Timeout = Timeout; request.ReadWriteTimeout = Timeout; request.KeepAlive = false; request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None; request.Proxy = null; request.ContentLength = json.Length; if (bearer != string.Empty) { request.Headers["Authorization"] = "Bearer " + bearer; } if (json != string.Empty) { if (Debug) { Console.WriteLine("Data TX: " + json + " Length: " + json.Length.ToString()); } byte[] payload = Encoding.ASCII.GetBytes(json); Stream stream = request.GetRequestStream(); stream.Write(payload, 0, payload.Length); stream.Flush(); stream.Close(); } if (Debug) { Console.WriteLine("Waiting for Response"); } using (response = (HttpWebResponse)request.GetResponse()) { Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); apiResponse.Response = reader.ReadToEnd(); apiResponse.StatusCode = (int)((HttpWebResponse)response).StatusCode; reader.Close(); dataStream.Close(); } if (Debug) { Console.WriteLine("Data RX: " + apiResponse.Response); Console.WriteLine("Status Code: " + apiResponse.StatusCode); } complete = true; } catch (SocketException ex) { apiResponse.Error = true; apiResponse.ErrorMessage = ex.Message; apiResponse.StatusCode = (int)response.StatusCode; } catch (IOException ex) { apiResponse.Error = true; apiResponse.ErrorMessage = ex.Message; apiResponse.StatusCode = (int)response.StatusCode; } catch (WebException ex) { apiResponse.Error = true; apiResponse.ErrorMessage = ex.Message; if (ex.Response != null) { apiResponse.StatusCode = (int)((HttpWebResponse)ex.Response).StatusCode; } } catch (Exception ex) { apiResponse.Error = true; apiResponse.ErrorMessage = ex.Message; if (response != null) { apiResponse.StatusCode = (int)response.StatusCode; } } if (Debug) { if (apiResponse.Error) { Console.WriteLine("Error: " + apiResponse.ErrorMessage); Console.WriteLine("Status Code: " + apiResponse.StatusCode); } TimeSpan ts = DateTime.Now.Subtract(datetime); Console.WriteLine("TimeTaken: " + ts.TotalMilliseconds + "ms"); } loop++; } IsError = apiResponse.Error; Response = apiResponse.Response; ErrorMessage = apiResponse.ErrorMessage; StatusCode = apiResponse.StatusCode; return(apiResponse); }
public Result ConstrainedCallvirt <TypeList, ArgList> (APC pc, Method method, TypeNode constraint, TypeList extraVarargs, SymbolicValue dest, ArgList args, Data data) where TypeList : IIndexable <TypeNode> where ArgList : IIndexable <SymbolicValue> { return(this.visitor.ConstrainedCallvirt(pc, method, constraint, extraVarargs, dest, Convert(pc, args), data)); }
public Result Entry(APC pc, Method method, Data data) { return(this.visitor.Entry(pc, method, data)); }
/// <summary> /// Initializes a new instance of the <see cref="Callvirt"/> class. /// </summary> /// <param name="method">The method.</param> /// <param name="result">The result.</param> /// <param name="parameters">The parameters.</param> public Callvirt(Method method, Register result, Operand [] parameters) : base(method, result, parameters) { }
public Result LoadMethodToken(APC pc, Method type, SymbolicValue dest, Data data) { return(this.visitor.LoadMethodToken(pc, type, dest, data)); }
public Task Execute(string endpoint, Method method, TRequest requestParameters) => Task.FromResult(0);
public Result Jmp(APC pc, Method method, Data data) { return(this.visitor.Jmp(pc, method, data)); }
public IRestResponse HandleMyClientRequest(string url, MyClientRequest clRequest, Method method) { var MyRestClient = new RestClient(); MyRestClient.BaseUrl = new Uri(url); var request = new RestRequest(method) { ReadWriteTimeout = 3600 }; //in real scenario we could add more parameters to Header (e.g. token authentication, accept) request.AddHeader("Content-Type", "application/json"); if (method == Method.POST || method == Method.PUT) { request.AddParameter("application/json", clRequest.Body, ParameterType.RequestBody); } return(MyRestClient.Execute(request)); }
private void SetConfig(string uri, Method method, SecurityProtocolType securityProtocol = SecurityProtocolType.Tls12, bool clearRequest = true) => SetConfig(new Uri(uri), method, securityProtocol, clearRequest);
public override ScriptValue Call(ScriptValue thisObject, ScriptValue[] parameters, int length) { return(ScriptValue.CreateValue(Method.Call(false, m_Object, parameters, length))); }
public Task <T> Execute <T>(string endpoint, Method method, TRequest requestParameters) => Task.FromResult(default(T));
private void GenerateMember(Class ce, object node, object signature) { var names = node.GetNames(); var itemType = node.Get <string>("type"); var name = node.Get <string>("name"); var access = node.Get <string>("access"); if (name.IsNullOrEmpty()) { Console.WriteLine("Warning: empty name " + name); return; } var className = node.Get <string>("class"); var type = "object";// node.Get<string>("type"); //var ce = FindClass(className); if (ce == null) { Console.WriteLine("Warning: Can't find class: " + className); return; } Element me2 = null; if (itemType == "attribute" || itemType == "property") { var isReadOnly = node.Get <string>("readonly") != null; if (type.IsNullOrEmpty()) { type = "object"; Console.WriteLine("Warning: type is null: " + className + "." + name + " assuming object"); //return; } var pe = new Property { Name = name, Type = FindClass(type), }; pe.IsReadOnly = isReadOnly; if (Char.IsDigit(pe.Name[0])) { Console.WriteLine("Warning: Invalid name " + pe.Name); return; } if (pe.Type == null) { Console.WriteLine("Warning: type is null"); return; } ce.Members.Add(pe); if (itemType == "attribute") { var ctor = ce.GetEmptyConstructor(); if (ctor == null) { ctor = new Method { IsConstructor = true, Name = ".ctor", }; ce.Members.Add(ctor); } var att = ctor.Attributes.Where(t => t.Name == "JsMethod").FirstOrDefault(); if (att == null) { att = new SharpKit.ExtJs4.Generator.Attribute { Name = "JsMethod", NamedParamters = new Dictionary <string, string> { { "JsonInitializers", "true" } }, }; ctor.Attributes.Add(att); } } me2 = pe; } else if (itemType == "method") { var prms = signature.GetValues("params"); var returnType = "object";// node.GetValues("return"); var me = new Method { Name = name, //Type = FindClass(node.Get<string>("desc")) //Type = FindClass(type), }; if (me.Name == ce.Name) { me.IsConstructor = true; returnType = null; } if (prms != null) { me.Parameters = prms.Select(GenerateParameter).ToList(); } if (me.Parameters.Contains(null)) { Console.WriteLine("Warning: prms contains nulls:" + className + "." + name); return; } if (returnType != null) { //var returnType = returns.LastOrDefault() as string; //returnType = returnType.Split('|').FirstOrDefault().Trim(); me.Type = FindClass(returnType); if (me.Type == null) { Console.WriteLine("Cannot resolve method return type: " + className + "." + name); me.Type = ObjectClass; } } ce.Members.Add(me); me2 = me; } if (me2 != null) { if (access.IsNullOrEmpty()) { } else if (access == "protected") { me2.IsProtected = true; } else if (access == "private") { me2.IsPrivate = true; } else if (access == "public") { } else { } ImportDocumentation(me2, node); } }
public static async Task <string> RequestUrl(string baseUrl, string path, Method method, object postData = null, Dictionary <string, string> headers = null, int timeout = 10_000, ContentType contentType = ContentType.Json /*,
public OldValueSubroutine(SubroutineFacade subroutineFacade, Method method, SimpleSubroutineBuilder <Label> builder, Label startLabel) : base(subroutineFacade, method, builder, startLabel) { }
public override bool TryGetAssemblySetupTeardownMethods(AssemblyEx assembly, out Method setup, out Method teardown) { setup = teardown = null; return(false); }
public override bool DoSignaturesMatch(Method other) { return(((MockMethod)other).id == this.id); }
public void GenerateMethodInvocation(Method method) { var contexts = new List <MarshalContext>(); var @params = new List <string>(); if (!method.IsStatic && !(method.IsConstructor || method.IsDestructor)) { @params.Add("__object"); } int paramIndex = 0; foreach (var param in method.Parameters.Where(m => !m.IsImplicit)) { var ctx = new MarshalContext(Context) { ArgName = param.Name, Parameter = param, ParameterIndex = paramIndex++ }; contexts.Add(ctx); var marshal = new JavaMarshalManagedToNative(ctx); param.Visit(marshal); if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore)) { Write(marshal.Context.SupportBefore); } @params.Add(marshal.Context.Return); } PrimitiveType primitive; method.ReturnType.Type.IsPrimitiveType(out primitive); var hasReturn = primitive != PrimitiveType.Void && !(method.IsConstructor || method.IsDestructor); if (hasReturn) { TypePrinter.PushContext(TypePrinterContextKind.Native); var typeName = method.ReturnType.Visit(TypePrinter); TypePrinter.PopContext(); Write($"{typeName.Type} __ret = "); } if (method.IsConstructor) { Write("__object = "); } var unit = method.TranslationUnit; var package = string.Join(".", GetPackageNames(unit)); Write($"{package}.{JavaNative.GetNativeLibClassName(unit)}.INSTANCE.{JavaNative.GetCMethodIdentifier(method)}("); Write(string.Join(", ", @params)); WriteLine(");"); WriteLine("mono.embeddinator.Runtime.checkExceptions();"); foreach (var marshal in contexts) { if (!string.IsNullOrWhiteSpace(marshal.SupportAfter)) { Write(marshal.SupportAfter); } } if (hasReturn) { var ctx = new MarshalContext(Context) { ReturnType = method.ReturnType, ReturnVarName = "__ret" }; var marshal = new JavaMarshalNativeToManaged(ctx); method.ReturnType.Visit(marshal); if (marshal.Context.Return.ToString().Length == 0) { throw new System.Exception(); } if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore)) { Write(marshal.Context.SupportBefore); } WriteLine($"return {marshal.Context.Return};"); } }