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); } }
public static string getOperationMethodName(this DbSetInfo dbSetInfo, MethodType methodType) { switch (methodType) { case MethodType.Refresh: if (string.IsNullOrWhiteSpace(dbSetInfo.refreshDataMethod)) return null; return GenerateMethodName(dbSetInfo.refreshDataMethod, dbSetInfo.dbSetName); case MethodType.Insert: if (string.IsNullOrWhiteSpace(dbSetInfo.insertDataMethod)) return null; return GenerateMethodName(dbSetInfo.insertDataMethod, dbSetInfo.dbSetName); case MethodType.Update: if (string.IsNullOrWhiteSpace(dbSetInfo.updateDataMethod)) return null; return GenerateMethodName(dbSetInfo.updateDataMethod, dbSetInfo.dbSetName); case MethodType.Delete: if (string.IsNullOrWhiteSpace(dbSetInfo.deleteDataMethod)) return null; return GenerateMethodName(dbSetInfo.deleteDataMethod, dbSetInfo.dbSetName); case MethodType.Validate: if (string.IsNullOrWhiteSpace(dbSetInfo.validateDataMethod)) return null; return GenerateMethodName(dbSetInfo.validateDataMethod, dbSetInfo.dbSetName); default: throw new DomainServiceException(string.Format("Invalid Method Type {0}", methodType)); } }
/// <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)); }
/// <summary> /// Generates MondInstanceFunction bindings for the given methods. /// </summary> internal static IEnumerable<Tuple<string, MondInstanceFunction>> BindInstance( string className, ICollection<MethodInfo> methods, Type type = null, MethodType methodType = MethodType.Normal, string nameOverride = null) { if (className == null) throw new ArgumentNullException("className"); if (type == null && methods.Any(m => !m.IsStatic)) throw new MondBindingException("BindInstance requires a type for non-static methods"); var methodTables = BuildMethodTables((IEnumerable<MethodBase>)methods, methodType, nameOverride); foreach (var table in methodTables) { #if !NO_EXPRESSIONS BindCallFactory callFactory = (m, p, a, r) => BindFunctionCall(m, type, true, p, a, r); yield return Tuple.Create(table.Name, BindImpl<MondInstanceFunction, MondValue>(className, table, true, callFactory)); #else yield return Tuple.Create(table.Name, BindInstanceImpl(className, table, nameOverride, type == null)); #endif } }
public ProxyMethodInfo(string methodName, string typeName, Type fakeType, MethodInfo fakeMethod, MethodType fakeMethodType) : this(methodName, typeName) { FakeMethodType = fakeMethodType; FakeMethod = fakeMethod; FakeType = fakeType; }
public RemoveMethodsArgs(MethodType forClass, string prefix, Type returnType, bool canBeVoid, int paramCount) { this.forClass = forClass; this.prefix = prefix; this.returnType = returnType; this.canBeVoid = canBeVoid; this.paramCount = paramCount; }
public Name(string methodName, string className, MethodType type, bool interesting) { MethodName = methodName; ClassName = className; Type = type; Interesting = interesting; }
private static Database CreateDatabase(MethodType type) { switch (type) { case MethodType.One: { // Should only exist one DatabaseProviderFactory object in your application, // since all the Database objects are cached in the factory var factory = new DatabaseProviderFactory(); return factory.CreateDefault(); } case MethodType.Two: { var factory = new DatabaseProviderFactory(); DatabaseFactory.SetDatabaseProviderFactory(factory); return DatabaseFactory.CreateDatabase(); } case MethodType.Three: { var factory = new DatabaseProviderFactory(); DatabaseFactory.SetDatabaseProviderFactory(factory); return DatabaseFactory.CreateDatabase("LocalDb"); } case MethodType.Four: { return new SqlDatabase(ConfigurationManager.ConnectionStrings["LocalDb"].ConnectionString); } default: throw new NotSupportedException(); } }
public CommonParameters(MethodType method, bool verifyOriginator = false) { Id = RandomNumberGenerator.Instance.Next(); MethodType = method; VerifyOriginator = verifyOriginator; }
/// <summary> /// Initializes a new <see cref="Method"/> instance with the given parameters. /// </summary> /// <param name="moduleId">The ID of the module the symbol resides in.</param> /// <param name="type">The type of the method.</param> /// <param name="address">The start address of the method.</param> /// <param name="length">The length of the method, in bytes.</param> public Method( uint moduleId, MethodType type, uint address, uint length ) : base(moduleId, address, length) { this.Type = type; //Debug.Assert( address % 4 == 0 ); Debug.Assert( length % 4 == 0 ); }
public static List<string> CreateMethodParamList(MethodType Methodtype, string Tablename, List<string> Colnames, string Namespace) { List<string> lines = new List<string>(); List<string> propertyInfos = new List<string>(); var typeMap = Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.Namespace == Namespace) .ToDictionary(t => t.Name, t => t, StringComparer.OrdinalIgnoreCase); Type type; if (typeMap.TryGetValue(Tablename.Trim(), out type)) { try { var cls = Activator.CreateInstance(type); foreach (var prop in cls.GetType().GetProperties()) { propertyInfos.Add(prop.Name); } } catch(Exception ex) { Console.WriteLine(string.Format("Error:{0}", ex)); } } else { Console.WriteLine("Type not found"); } var i = 0; foreach (var s in Colnames) { switch (Methodtype) { case MethodType.Insert: lines.Add(string.Format("fbCom.Parameters.AddWithValue(\"@{0}\", {1}.{2});", s, Tablename, propertyInfos[i])); break; case MethodType.Select: lines.Add(string.Format("fbCom.Parameters.AddWithValue(\"@{0}\", {1});", s, propertyInfos[i].ToUpper())); return lines; //case MethodType.Update: // lines.Add(string.Format("fbCom.Parameters.AddWithValue(\"{0}\", {1}.{2});", s, Tablename, propertyInfos[i])); // break; case MethodType.Delete: lines.Add(string.Format("fbCom.Parameters.AddWithValue(\"@{0}\", {1});", s, propertyInfos[i].ToUpper())); return lines; case MethodType.None: break; default: break; } i++; } return lines; }
public PipelineException(PipelineErrorType errorType, string serviceName, string route, Uri requestUri, MethodType methodType, Exception innerException) : base(PipelineException.DefaultMessage, innerException) { this.errorType = errorType; this.serviceName = serviceName; this.route = route; this.requestUri = requestUri; this.methodType = methodType; }
/// <summary> /// Creates a service object method with the given name, description and Methodtype /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="methodType"></param> /// <returns></returns> public static Method CreateMethod(string name, string description, MethodType methodType) { Method m = new Method(); m.Name = name; m.Type = methodType; m.MetaData.DisplayName = AddSpaceBeforeCaptialLetter(name); m.MetaData.Description = description; return m; }
private NativeInvokerBytecodeGenerator(LambdaForm lambdaForm, MethodType invokerType) { if (invokerType != invokerType.basicType()) { throw new BailoutException(Bailout.NotBasicType, invokerType); } this.lambdaForm = lambdaForm; this.invokerType = invokerType; this.delegateType = MethodHandleUtil.GetMemberWrapperDelegateType(invokerType); MethodInfo mi = MethodHandleUtil.GetDelegateInvokeMethod(delegateType); Type[] paramTypes = MethodHandleUtil.GetParameterTypes(typeof(object[]), mi); // HACK the code we generate is not verifiable (known issue: locals aren't typed correctly), so we stick the DynamicMethod into mscorlib (a security critical assembly) this.dm = new DynamicMethod(lambdaForm.debugName, mi.ReturnType, paramTypes, typeof(object).Module, true); this.ilgen = CodeEmitter.Create(this.dm); if (invokerType.parameterCount() > MethodHandleUtil.MaxArity) { this.packedArgType = paramTypes[paramTypes.Length - 1]; this.packedArgPos = paramTypes.Length - 1; } else { this.packedArgPos = Int32.MaxValue; } locals = new CodeEmitterLocal[lambdaForm.names.Length]; for (int i = lambdaForm._arity(); i < lambdaForm.names.Length; i++) { Name name = lambdaForm.names[i]; if (name.index() != i) { throw new BailoutException(Bailout.PreconditionViolated, "name.index() != i"); } switch (name.typeChar()) { case 'L': locals[i] = ilgen.DeclareLocal(Types.Object); break; case 'I': locals[i] = ilgen.DeclareLocal(Types.Int32); break; case 'J': locals[i] = ilgen.DeclareLocal(Types.Int64); break; case 'F': locals[i] = ilgen.DeclareLocal(Types.Single); break; case 'D': locals[i] = ilgen.DeclareLocal(Types.Double); break; case 'V': break; default: throw new BailoutException(Bailout.PreconditionViolated, "Unsupported typeChar(): " + name.typeChar()); } } }
public Method(MethodType methodType, Endpoint endpoint, Action action) { if (action == null) { throw new ArgumentNullException("action", "action cannot be null."); } this.Initialize(methodType, endpoint); this.action = action; }
/// <summary> /// Creates a service object method with the given name, description and Methodtype /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="methodType"></param> /// <returns></returns> public static Method CreateMethod(string name, string description, MethodType methodType) { Method m = new Method { Name = name, Type = methodType, MetaData = new MetaData(AddSpaceBeforeCaptialLetter(name), description) }; return m; }
public Method(MethodType methodType, Endpoint endpoint, Action<IRequestMessage, IResponseMessage> action) { if (action == null) { throw new ArgumentNullException("action", "action cannot be null."); } this.Initialize(methodType, endpoint); this.requestResponseAction = action; }
/// <summary> /// Returns specific public methods that: have the specified prefix; have the specified return Type, or /// void, and has the specified number of parameters. If the returnType is specified as null then the return /// Type is ignored. /// </summary> /// <param name="type"></param> /// <param name="methodType"></param> /// <param name="name"></param> /// <param name="returnType"></param> protected MethodInfo[] FindMethods(Type type, MethodType methodType, string name, Type returnType) { return type.GetMethods(GetBindingFlagsForMethodType(methodType)). Where(m => m.Name == name). Where(m => (m.IsStatic && methodType == MethodType.Class) || (!m.IsStatic && methodType == MethodType.Object)). Where(m => AttributeUtils.GetCustomAttribute<NakedObjectsIgnoreAttribute>(m) == null). Where(m => returnType == null || returnType.IsAssignableFrom(m.ReturnType)).ToArray(); }
public FeedbackType(string name, int id, MethodInfo callback, MethodType methodType, List<FeedbackField> fields) { this.name = name; this.id = id; this.method = callback; this.fields = fields; methodHasTimestamp = (methodType & MethodType.Timestamp) != MethodType.None; methodHasMsgType = (methodType & MethodType.MessageType) != MethodType.None; methodIsObjectArray = (methodType & MethodType.ObjectArray) != MethodType.None; }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="MethodCommand" /> Klasse. /// </summary> /// <param name="method"> /// The method. /// </param> /// <param name="context"> /// The context. /// </param> public MethodCommand([NotNull] MethodInfo method, [NotNull] WeakReference context) { Contract.Requires<ArgumentNullException>(method != null, "method"); _method = method; _context = context; _methodType = (MethodType) method.GetParameters().Length; if (_methodType != MethodType.One) return; if (_method.GetParameters()[0].ParameterType != typeof (EventData)) _methodType = MethodType.EventArgs; }
public RequestMessage(MethodType intMethod, string strURL) { // Asigna las propiedades Method = intMethod; URL = strURL; // Asigna los valores básicos ContentType = "text/xml"; // Define los objetos UrlParameters = new ParameterDataCollection(); QueryParameters = new ParameterDataCollection(); Attachments = new AttachmentsCollection(); }
public void AddMethod(string name, string displayName, string description, MethodType k2Type, List<string> inputProps, List<string> requiredProps, List<string> returnProps) { SchemaMethod meth = new SchemaMethod(); meth.Name = name; meth.DisplayName = displayName; meth.K2Type = k2Type; meth.Description = description; meth.InputProperties = inputProps; meth.RequiredProperties = requiredProps; meth.ReturnProperties = returnProps; SchemaMethods.Add(meth); }
public WindowedSincUpsampler(int factor, int windowLength, MethodType method) : base(FilterType.WindowedSincUpsampler) { if (factor <= 1 || !IsPowerOfTwo(factor)) { throw new ArgumentException("factor must be power of two integer and larger than 1"); } Factor = factor; WindowLength = windowLength; Method = method; mFirst = true; }
public void AddMethod(int id, SimpleMethodInfo method, MethodType type) { IMonitorServiceCallback channel = GetCallbackChannel(); if (!_clientIDs.ContainsKey(channel)) { AddStatusText(string.Format("New Client (#{0})", _nextClientID)); _clientIDs.Add(channel, _nextClientID++); } AddStatusText(string.Format("New Method (#{0}, {1})", _clientIDs[channel], id)); _methods.Add(new ClientMethodInfo() { Callback = channel, ID = id, MethodInfo = method, ClientID = _clientIDs[channel], Type = type }); }
public static Method FindByMethodType(Entity entity, MethodType methodType) { if (entity == null) throw new ArgumentNullException("entity"); foreach (var method in entity.AllMethods) { if (method.GetAttributeValue("methodType", Constants.NamespaceUri, MethodType.None) == methodType) { return method; } } return null; }
/// <summary> /// Sends a new message to the event bus. /// </summary> /// <param name="values">The values that will be sent.</param> /// <param name="method">The method type of this message.</param> /// <param name="target">The target of this message.</param> /// <returns></returns> public async Task<Message> SendAsync(IEnumerable<dynamic> values, MethodType method, string target = null) { var message = new Message { Method = method, Sender = Sender, Target = target, Time = DateTime.Now, Values = values }; Console.WriteLine("Sending " + JsonConvert.SerializeObject(message, Formatting.Indented)); return await eventHubProxy.Invoke<Message>("Send", message); }
static void Main(string[] args) { tables = GetTableNames(); trueclassnames = GetTrueClassNames(); foreach (var table in tables) { tablename = table; tablerealname = GetTrueClassName(); columnnames = GetDBTableColumnNames(); CreateMethodsTemplate t = new CreateMethodsTemplate(); t.Session = new Dictionary<string, object>(); t.Session.Add("Tablename", tablename); t.Session.Add("Database", @"C:\Chronicle\Data\Test.fdb"); t.Session.Add("User", "SYSDBA"); t.Session.Add("Password", "dm"); t.Session.Add("Dialect", 1); methodtype = MethodType.Insert; t.Session.Add("MethodHeadCreate", GetMethodHead()); t.Session.Add("ParameterListCreate", MethodParamList()); t.Session.Add("ColumnListCreate", GetColumnList()); t.Session.Add("ColumnValueListCreate", GetColumnValueList()); methodtype = MethodType.Select; t.Session.Add("MethodHeadRead", GetMethodHead()); t.Session.Add("ParameterListRead", MethodParamList()); t.Session.Add("ColumnListRead", GetColumnList()); t.Session.Add("ColumnValueListRead", GetColumnValueList()); //methodtype = MethodType.Update; //t.Session.Add("MethodHeadUpdate", GetMethodHead()); //t.Session.Add("ParameterListUpdate", MethodParamList()); //t.Session.Add("ColumnListUpdate", GetColumnList()); //t.Session.Add("ColumnValueListUpdate", GetColumnValueList()); methodtype = MethodType.Delete; t.Session.Add("MethodHeadDelete", GetMethodHead()); t.Session.Add("ParameterListDelete", MethodParamList()); t.Session.Add("ColumnListDelete", GetColumnList()); t.Session.Add("ColumnValueListDelete", GetColumnValueList()); t.Initialize(); string output = t.TransformText(); string projectDir = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())); string GeneratedClassPath = Path.Combine(projectDir, string.Format("GeneratedClasses\\{0}Methods.cs", tablename)); File.WriteAllText(GeneratedClassPath, output); Console.WriteLine(output); } Console.ReadLine(); }
/// <summary> /// Returns specific public methods that: have the specified prefix; have the specified return Type, or /// void, and has the specified number of parameters. If the returnType is specified as null then the return /// Type is ignored. /// </summary> /// <param name="reflector"></param> /// <param name="type"></param> /// <param name="methodType"></param> /// <param name="name"></param> /// <param name="returnType"></param> /// <param name="paramTypes">the set of parameters the method should have, if null then is ignored</param> /// <param name="paramNames">the names of the parameters the method should have, if null then is ignored</param> protected MethodInfo FindMethod(IReflector reflector, Type type, MethodType methodType, string name, Type returnType, Type[] paramTypes, string[] paramNames = null) { try { MethodInfo method = paramTypes == null ? type.GetMethod(name, GetBindingFlagsForMethodType(methodType, reflector)) : type.GetMethod(name, GetBindingFlagsForMethodType(methodType, reflector), null, paramTypes, null); if (method == null) { return null; } // check for static modifier if (method.IsStatic && methodType == MethodType.Object) { return null; } if (!method.IsStatic && methodType == MethodType.Class) { return null; } if (method.GetCustomAttribute<NakedObjectsIgnoreAttribute>() != null) { return null; } // check for return Type if (returnType != null && !returnType.IsAssignableFrom(method.ReturnType)) { return null; } if (paramNames != null) { string[] methodParamNames = method.GetParameters().Select(p => p.Name).ToArray(); if (!paramNames.SequenceEqual(methodParamNames)) { return null; } } return method; } catch (AmbiguousMatchException e) { throw new ModelException(Log.LogAndReturn(string.Format(Resources.NakedObjects.AmbiguousMethodError, name, type.FullName)), e); } }
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<Parameter> 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.ToUpperString() + "&" + uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped).UrlEncode() + "&" + stringParameter.UrlEncode(); var hash = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase)); return Convert.ToBase64String(hash).UrlEncode(); } }
internal DynamicMethodBuilder(string name, MethodType type, Type valueType) : this(name, type, typeof(Container <,>).MakeGenericType(typeof(object), valueType), null, null, null) { }
private string ProcessResponse(HttpResponseMessage response, LogContext logContext, MethodType methodType) { if (!response.IsSuccessStatusCode) { HandleFailure(response, logContext, methodType); } string responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); LogPostMethodCall(MethodType.Post, logContext, response, responseContent); return(responseContent); }
/// <summary> /// Attempts to create a <see cref="HarmonyPatchInfo"/> from a patch class annotated with <see cref="HarmonyPatch"/>. /// Returns null after logging errors if it fails. /// </summary> /// <param name="patchClass"></param> /// <returns></returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="patchClass"/> is null.</exception> public static HarmonyPatchInfo?GetPatch(Type patchClass) { if (patchClass == null) { throw new ArgumentNullException(nameof(patchClass), "patchClass cannot be null."); } try { Plugin.Log?.Debug($"Getting patch info for {patchClass.Name}"); HarmonyPatch[] patches = patchClass.GetCustomAttributes <HarmonyPatch>().ToArray() ?? Array.Empty <HarmonyPatch>(); if (patches.Length == 0) { throw new ArgumentException($"Type '{patchClass.Name}' has no 'HarmonyPatch' annotations."); } Plugin.Log?.Debug($" Found {patches.Length} HarmonyPatch annotations."); Type? originalType = null; string? originalMemberName = null; MethodType methodType = MethodType.Normal; Type[] parameters = Array.Empty <Type>(); for (int i = 0; i < patches.Length; i++) { HarmonyMethod info = patches[i].info; if (info.declaringType != null) { originalType = info.declaringType; } if (!string.IsNullOrEmpty(info.methodName)) { originalMemberName = info.methodName; } if (info.methodType.HasValue) { methodType = info.methodType.Value; } if ((info.argumentTypes?.Length ?? 0) > 0) { parameters = info.argumentTypes !; } } if (originalType == null) { throw new ArgumentException($"Original type could not be determined."); } if (methodType == MethodType.Normal && (originalMemberName == null || originalMemberName.Length == 0)) { methodType = MethodType.Constructor; } Plugin.Log?.Debug($" Attempting to create patch for {GetPatchedMethodString(originalType.Name, originalMemberName, methodType, parameters)}"); MethodBase originalMethod = methodType switch { MethodType.Normal => GetMethod(originalType, originalMemberName !, parameters), MethodType.Getter => originalType.GetProperty(originalMemberName, allBindingFlags).GetMethod, MethodType.Setter => originalType.GetProperty(originalMemberName, allBindingFlags).SetMethod, MethodType.Constructor => originalType.GetConstructor(allInstanceBindingFlags, null, parameters, Array.Empty <ParameterModifier>()), MethodType.StaticConstructor => throw new NotImplementedException("Static constructor patches are not supported."), //originalType.GetConstructor(allStaticBindingFlags, null, parameters, Array.Empty<ParameterModifier>()), _ => throw new NotImplementedException($"MethodType '{methodType}' is unrecognized.") }; if (originalMethod == null) { throw new ArgumentException($"Could not find original method '{originalType.Name}.{originalMemberName}'."); } MethodInfo prefix = patchClass.GetMethod("Prefix", allBindingFlags); MethodInfo postfix = patchClass.GetMethod("Postfix", allBindingFlags); MethodInfo transpiler = patchClass.GetMethod("Transpiler", allBindingFlags); return(new HarmonyPatchInfo(Harmony, originalMethod, prefix, postfix, transpiler)); } catch (Exception ex) { Plugin.Log.Error($"Error getting Harmony patch '{patchClass.Name}'"); Plugin.Log.Debug(ex); return(null); } }
public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, MethodType oldType, int[] permutationOrNull) { #if FIRST_PASS return(null); #else // LAME why does OpenJDK name the parameter permutationOrNull while it is not allowed to be null? if (permutationOrNull.Length != oldType.parameterCount()) { throw new java.lang.IllegalArgumentException("wrong number of arguments in permutation"); } MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("MethodHandleImpl.permuteArguments", newType, target); for (int i = 0, argCount = newType.parameterCount(); i < permutationOrNull.Length; i++) { // make sure to only read each array element once, to avoid having to make a defensive copy of the array int perm = permutationOrNull[i]; if (perm < 0 || perm >= argCount) { throw new java.lang.IllegalArgumentException("permutation argument out of range"); } dm.Ldarg(perm); dm.Convert(oldType.parameterType(i), newType.parameterType(perm), 0); } dm.CallTarget(); dm.Convert(oldType.returnType(), newType.returnType(), 0); dm.Ret(); return(dm.CreateAdapter()); #endif }
/// <summary> /// コンストラクター。 /// </summary> /// <param name="scriptName">スクリプト名</param> /// <param name="method">HTTPメソッド</param> public NCMBScript(string scriptName, MethodType method) : this(scriptName, method, DEFAULT_SCRIPT_ENDPOINT) { }
private static string GetPatchedMethodString(string originalTypeName, string?originalMemberName, MethodType methodType, Type[] parameters) { return(methodType switch { MethodType.Normal => $"Method: '{originalTypeName}.{originalMemberName}({string.Join(", ", parameters.Select(p => p.Name))})'", MethodType.Getter => $"Property Getter: '{originalTypeName}.{originalMemberName}'", MethodType.Setter => $"Property Setter: '{originalTypeName}.{originalMemberName}'", MethodType.Constructor => $"Constructor: '{originalTypeName}({string.Join(", ", parameters.Select(p => p.Name))})'", MethodType.StaticConstructor => $"Static Constructor: '{originalTypeName}({string.Join(", ", parameters.Select(p => p.Name))})'", _ => $"Unknown MethodType: '{methodType}'", });
internal DynamicMethodBuilder(string name, MethodType type, MethodHandle target) : this(name, type, null, target.vmtarget, null, null) { ilgen.Emit(OpCodes.Ldarg_0); }
public HttpRequestor(API root, MethodType method) { _root = root; _method = method; }
// TODO what is lookupClass for? public static object createDelegate(MethodType type, MemberName m, bool doDispatch, jlClass lookupClass) { #if FIRST_PASS return(null); #else int index = m.getVMIndex(); if (index == Int32.MaxValue) { bool invokeExact = m.getName() == "invokeExact"; Type targetDelegateType = MethodHandleUtil.CreateDelegateType(invokeExact ? type.dropParameterTypes(0, 1) : type); MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("DirectMethodHandle." + m.getName(), type, typeof(IKVM.Runtime.InvokeCache <>).MakeGenericType(targetDelegateType)); dm.Ldarg(0); if (invokeExact) { dm.Call(ByteCodeHelperMethods.GetDelegateForInvokeExact.MakeGenericMethod(targetDelegateType)); } else { dm.LoadValueAddress(); dm.Call(ByteCodeHelperMethods.GetDelegateForInvoke.MakeGenericMethod(targetDelegateType)); dm.Ldarg(0); } for (int i = 1, count = type.parameterCount(); i < count; i++) { dm.Ldarg(i); } dm.CallDelegate(targetDelegateType); dm.Ret(); return(dm.CreateDelegate()); } else { TypeWrapper tw = (TypeWrapper)typeof(MemberName).GetField("vmtarget", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(m); tw.Finish(); MethodWrapper mw = tw.GetMethods()[index]; mw.ResolveMethod(); MethodInfo mi = mw.GetMethod() as MethodInfo; if (mi != null && !tw.IsRemapped && !tw.IsGhost && !tw.IsNonPrimitiveValueType && type.parameterCount() <= MethodHandleUtil.MaxArity // FXBUG we should be able to use a normal (unbound) delegate for virtual methods // (when doDispatch is set), but the x64 CLR crashes when doing a virtual method dispatch on // a null reference && (!mi.IsVirtual || (doDispatch && IntPtr.Size == 4)) && (doDispatch || !mi.IsVirtual)) { return(Delegate.CreateDelegate(MethodHandleUtil.CreateDelegateType(tw, mw), mi)); } else { // slow path where we emit a DynamicMethod MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder(mw.DeclaringType.TypeAsBaseType, "DirectMethodHandle:" + mw.Name, type); for (int i = 0, count = type.parameterCount(); i < count; i++) { if (i == 0 && !mw.IsStatic && (tw.IsGhost || tw.IsNonPrimitiveValueType)) { dm.LoadFirstArgAddress(); } else { dm.Ldarg(i); } } if (doDispatch && !mw.IsStatic) { dm.Callvirt(mw); } else { dm.Call(mw); } dm.Ret(); return(dm.CreateDelegate()); } } #endif }
public static PromotionOperation Create(TypeExpression type, Enum op, MethodType methodAnalyzed, Location location, bool notifyError = true) { return(new VerbosePromotionOperation(type, op, methodAnalyzed, location, notifyError)); }
public MethodData(MethodBase methodBase, MethodType methodType, ProxyOperationRuntime operation) { _methodBase = methodBase; _methodType = methodType; _operation = operation; }
public MethodData(MethodBase methodBase, MethodType methodType) : this(methodBase, methodType, null) { }
internal DynamicMethodBuilder(string name, MethodType type, MethodHandle target, object value) : this(name, type, typeof(Container <,>).MakeGenericType(target.vmtarget.GetType(), value.GetType()), target.vmtarget, value, null) { ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldfld, container.GetField("target")); }
public static void AddedServiceMethod(ILogger logger, string methodName, string serviceName, MethodType methodType, IReadOnlyList <string> httpMethods, string routePattern) { if (logger.IsEnabled(LogLevel.Trace)) { // There should be one HTTP method here, but concat in case someone has overriden metadata. var allHttpMethods = string.Join(',', httpMethods); _addedServiceMethod(logger, methodName, serviceName, methodType, allHttpMethods, routePattern, null); } }
internal Task <DictionaryResponse <TKey, TValue> > AccessApiDictionaryAsync <TKey, TValue>(MethodType type, string url, IDictionary <string, object> parameters, CancellationToken cancellationToken, string jsonPath = "") { return(this.AccessApiDictionaryAsyncImpl <TKey, TValue>(type, url, parameters, cancellationToken, jsonPath)); }
protected void FindAndRemoveHideMethod(IReflector reflector, IList <IFacet> facets, IMethodRemover methodRemover, Type type, MethodType methodType, string capitalizedName, Type collectionType, ISpecification specification) { FindAndRemoveHideMethod(reflector, facets, methodRemover, type, methodType, capitalizedName, ParamTypesOrNull(collectionType), specification); }
internal DynamicMethodBuilder(Type owner, string name, MethodType type) : this(name, type, null, null, null, owner) { }
public void ChangeSearchMethod(MethodType newMathMethod) { _currentMathMethod = newMathMethod; }
/// <summary> /// コンストラクター。<br/> /// スクリプトのエンドポイントを指定する場合は、こちらのコンストラクターを使用します。 /// </summary> /// <param name="scriptName">スクリプト名</param> /// <param name="method">HTTPメソッド</param> /// <param name="baseUrl">エンドポイント</param> public NCMBScript(string scriptName, MethodType method, string baseUrl) { _scriptName = scriptName; _method = method; _baseUrl = baseUrl; }
/// <summary> /// Private constructor of the BinaryArithmeticalOperation. /// Implements Factory method. /// Role: Product. /// Implements a double dispatcher method in its methods AcceptOperation. /// </summary> /// <param name="secondOperand">The second operand in a binary arihtmetical operation. /// First operand would be came inside the proper message to AcceptOperation methods /// </param> /// <param name="binaryOperator">operand to apply to the operands.</param> /// <param name="methodAnalyzed">the actual method being analised.</param> /// <param name="showErrorMessage">Indicates if an error message should be shown (used for dynamic types)</param> /// <param name="location">The location (file, line, column) of text being analyses</param> public BinaryArithmeticalOperation(TypeExpression secondOperand, Enum binaryOperator, MethodType methodAnalyzed, bool showErrorMessage, Location location) { this.secondOperand = secondOperand; this.binaryOperator = binaryOperator; this.methodAnalyzed = methodAnalyzed; this.showErrorMessage = showErrorMessage; this.location = location; }
protected void FindAndRemoveHideMethod(IReflector reflector, IList <IFacet> facets, IMethodRemover methodRemover, Type type, MethodType methodType, string capitalizedName, Type[] paramTypes, ISpecification specification) { MethodInfo method = FindMethodWithOrWithoutParameters(reflector, type, methodType, PrefixesAndRecognisedMethods.HidePrefix + capitalizedName, typeof(bool), paramTypes); if (method != null) { methodRemover.RemoveMethod(method); facets.Add(new HideForContextFacet(method, specification)); AddOrAddToExecutedWhereFacet(method, specification); } }
//--- Constructors --- public DbMethod(MethodInfo methodInfo, VersionInfo targetVersion) { _methodInfo = methodInfo; _targetVersion = targetVersion; _methodType = MethodType.Update; }
protected MethodInfo FindMethodWithOrWithoutParameters(IReflector reflector, Type type, MethodType methodType, string name, Type returnType, Type[] parms) { return(FindMethod(reflector, type, methodType, name, returnType, parms) ?? FindMethod(reflector, type, methodType, name, returnType, Type.EmptyTypes)); }
public void Error(Exception exception, TEntity result, MethodType type, string text = "") { throw new NotImplementedException(); }
private BindingFlags GetBindingFlagsForMethodType(MethodType methodType, IReflector reflector) { return(BindingFlags.Public | (methodType == MethodType.Object ? BindingFlags.Instance : BindingFlags.Static) | (reflector.IgnoreCase ? BindingFlags.IgnoreCase : BindingFlags.Default)); }
public Control() { this.methodField = MethodType.MD5; }
protected void FindAndRemoveDisableMethod(IReflector reflector, IList <IFacet> facets, IMethodRemover methodRemover, Type type, MethodType methodType, string capitalizedName, ISpecification specification) { FindAndRemoveDisableMethod(reflector, facets, methodRemover, type, methodType, capitalizedName, (Type)null, specification); }
protected void FindDefaultDisableMethod(IReflector reflector, IList <IFacet> facets, IMethodRemover methodRemover, Type type, MethodType methodType, string capitalizedName, Type[] paramTypes, ISpecification specification) { MethodInfo method = FindMethodWithOrWithoutParameters(reflector, type, methodType, PrefixesAndRecognisedMethods.DisablePrefix + capitalizedName, typeof(string), paramTypes); if (method != null) { facets.Add(new DisableForContextFacet(method, specification)); } }
public DbMethod(MethodInfo methodInfo, VersionInfo targetVersion, MethodType methodType) { _methodInfo = methodInfo; _targetVersion = targetVersion; _methodType = methodType; }
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)); }