public static MethodParameters[] GetMethodParmaters(MethodInfo methodInfo, object[] args) { var paramsOfMethod = methodInfo.GetParameters(); var methodParameters = new MethodParameters[paramsOfMethod.Length]; var i = -1; foreach (var paramInfo in paramsOfMethod) { i++; var genericType = typeof(MethodParameter <>).MakeGenericType(args[i].GetType()); var methodParamter = Activator.CreateInstance(genericType); var props = genericType.GetProperties(); foreach (var prop in props) { if (prop.Name == "Type") { prop.SetValue(methodParamter, args[i].GetType()); continue; } if (prop.Name == "Name") { prop.SetValue(methodParamter, paramsOfMethod[i].Name); continue; } if (prop.Name == "Value") { prop.SetValue(methodParamter, args[i]); } } methodParameters[i] = methodParamter as MethodParameters; } return(methodParameters); }
public void GetParameters_ReturnsParameterArray_WhenNoErrors() { var expectedObject1 = "I'm an object"; var expectedObject2 = "You're an object"; var expectedObject3 = "We're all objects"; var args = new List <CommandLineArgument>(); var expected = new object[] { expectedObject1, expectedObject2, expectedObject3 }; var expectedReturn = new MethodParameters { Parameters = new List <object> { expectedObject1, expectedObject2, expectedObject3 }, Errors = new List <string>() }; _mockMethodService.Setup(s => s.GetParameters(It.IsAny <MethodInfo>(), It.IsAny <List <CommandLineArgument> >())) .Returns(expectedReturn); var actual = _service.GetParameters(_command.Info, args); CollectionAssert.AreEqual(expected, actual); }
static void Main(string[] args) { MethodParameters methodParameters = new MethodParameters(); #region Method Parameters #region ref Console.WriteLine("----------ref start----------"); int number = 1; MethodParameters.RefMethod(ref number); Console.WriteLine(number); // result:2 // result: // Original values in Main. Name:laptops,ID:10001 // Back in Main.Name:laptops,ID: 10002 MethodParameters.ModifyProductByReference(); // output: // 三体,by 刘慈欣 // 三体II: 黑暗森林,by 刘慈欣 // 三体III: 死神永生,by 刘慈欣 methodParameters.ListBooks(); ref var book = ref methodParameters.GetBookByTitle("三体");
/// <summary> /// Invokes the action with the parsed parameters. /// </summary> /// <returns>0 for success.</returns> public int Invoke() { var args = MethodParameters .OrderBy(map => map.Position) .Select(row => row.Value) .ToArray() ; this.CommonParameters.ToList().ForEach(cp => cp.WriteToCommand()); this.Command.OnBeforeExecute(this); var result = MethodInfo.Invoke(Command, args); int exitCode = 0; if (result is int) { exitCode = (int)result; } if (result is bool) { exitCode = (bool)result ? 0 : -1; } return(this.Command.OnAfterExecute(this, exitCode)); }
private bool processDocument(string token, MethodParameters par, string sourceLanguage, string targetLanguage) { Dictionary <string, string> translations = new Dictionary <string, string>(); int n = 0; foreach (HtmlNode node in coll) { n++; if (par.Cancel) { return(false); } if (node.InnerText == node.InnerHtml) { //this dictionary is to translate every sentence only once. if (!translations.ContainsKey(node.InnerText)) { translations[node.InnerText] = translate(node.InnerText, token, sourceLanguage, targetLanguage); //translations[node.InnerText] = node.InnerText; } node.InnerHtml = translations[node.InnerText]; } par.SetProgress(n); } return(true); }
internal static MethodParameters ToBindingMethodParameters(this BindingSettings bindingSettings) { Func <Type[], Type> argumentResolver = null; var methodParameters = new MethodParameters(); var arguments = bindingSettings.BindingType.GetGenericArguments(); methodParameters.Parameters = new Type[2]; methodParameters.Parameters[0] = arguments[0].MakeByRefType(); arguments = arguments.Skip(1).ToArray(); if (bindingSettings.IsFunction) { methodParameters.ReturnType = arguments.Last(); argumentResolver = AspectArgsContractResolver.ToFunctionAspectArgumentContract; } else { methodParameters.ReturnType = typeof(void); argumentResolver = AspectArgsContractResolver.ToActionAspectArgumentContract; } methodParameters.Parameters[1] = argumentResolver(arguments); return(methodParameters); }
public IReturnType ToDefaultDelegate() { IReturnType type = new GetClassReturnType(cu.ProjectContent, "System.Func", 0); List <IReturnType> parameters = new List <IReturnType>(); if (this.HasParameterList) { parameters = MethodParameters.Select(p => p.ReturnType ?? new GetClassReturnType(cu.ProjectContent, "System.Object", 0)).ToList(); } if (this.MethodReturnType != null && this.MethodReturnType.FullyQualifiedName == "System.Void") { type = new GetClassReturnType(cu.ProjectContent, "System.Action", 0); } else { var rt = this.MethodReturnType; if (rt == null) { rt = new GetClassReturnType(cu.ProjectContent, "System.Object", 0); } parameters.Add(rt); } return(new ConstructedReturnType(type, parameters)); }
public void GetParameters_CallsWriteLine_ForEachReturnedError() { var expectedError1 = "I'm an error"; var expectedError2 = "You're an error"; var expectedError3 = "We're all errors"; var args = new List <CommandLineArgument>(); var expectedReturn = new MethodParameters { Errors = new List <string> { expectedError1, expectedError2, expectedError3 } }; _mockMethodService.Setup(s => s.GetParameters(It.IsAny <MethodInfo>(), It.IsAny <List <CommandLineArgument> >())) .Returns(expectedReturn); var actual = _service.GetParameters(_command.Info, args); _mockConsoleService.Verify(s => s.WriteLine(expectedError1), Times.Once()); _mockConsoleService.Verify(s => s.WriteLine(expectedError2), Times.Once()); _mockConsoleService.Verify(s => s.WriteLine(expectedError3), Times.Once()); }
private void ProcessRouteParameter(string param) { param = param.Trim('{', '}'); PropertyInfo property = null; try { property = RouteType.GetProperty(param); } catch (Exception) { } if (property == null) { MethodParameters.Add("\n /* CANNOT FIND " + param + " */\n "); } else { param = param.ToCamelCase(); ProcessClrProperty(property, true); // Uri Encode string parameters. if (property.GetGetMethod().ReturnType == typeof(string)) { UrlPath.Add("encodeURIComponent(" + param + ")"); } else { UrlPath.Add(param); } } }
public Method(MethodParameters parameters) { Name = parameters.Name; RawReturnType = parameters.RawReturnType; ReturnType = parameters.ReturnType; AccessModifier = parameters.AccessModifier; Parameters = parameters.Parameters; }
private void StartProcessInstance(bool startGeneric) { string processName = ServiceBroker.Service.ServiceObjects[0].Methods[0].Name; if (!startGeneric) { processName = GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessName, true); } int processVersion = GetIntProperty(Constants.SOProperties.ProcessInstanceClient.ProcessVersion); ServiceObject serviceObject = ServiceBroker.Service.ServiceObjects[0]; serviceObject.Properties.InitResultTable(); DataTable results = ServiceBroker.ServicePackage.ResultTable; using (CLIENT.Connection k2Con = new CLIENT.Connection()) { k2Con.Open(K2ClientConnectionSetup); CLIENT.ProcessInstance pi; if (processVersion > 0) { pi = k2Con.CreateProcessInstance(processName, processVersion); } else { pi = k2Con.CreateProcessInstance(processName); } string folio = GetStringProperty(Constants.SOProperties.ProcessInstanceClient.ProcessFolio); if (!string.IsNullOrEmpty(folio)) { pi.Folio = folio; } if (startGeneric) { MethodParameters mParams = ServiceBroker.Service.ServiceObjects[0].Methods[0].MethodParameters; foreach (CLIENT.DataField df in pi.DataFields) { df.Value = GetDataFieldValue(mParams[df.Name].Value, df.ValueType); } } k2Con.StartProcessInstance(pi, GetBoolProperty(Constants.SOProperties.ProcessInstanceClient.StartSync)); DataRow dr = results.NewRow(); dr[Constants.SOProperties.ProcessInstanceClient.ProcessInstanceId] = pi.ID; dr[Constants.SOProperties.ProcessInstanceClient.ProcessFolio] = pi.Folio; results.Rows.Add(dr); k2Con.Close(); } }
/// <summary> /// Generate session id if needed and /// sends it back to the client. /// </summary> private string ProcessSessionId(MethodParameters methodParameters) { string sessionId = methodParameters.SessionId ?? ServerSessionIdRepository.GenerateSessionId(); sessionIdRepository.SessionId = sessionId; specialValues.Add("sessionId", sessionId); return(sessionId); }
private static void CreateThread(int threadId) { Console.WriteLine("Creating Thread {0}", threadId); MethodParameters newParameter = new MethodParameters(); newParameter.ThreadId = threadId; newParameter.ThreadCreated = DateTime.Now; Interlocked.Increment(ref _threadCounter); ThreadPool.QueueUserWorkItem(new WaitCallback(LongRunningProcess), (object)newParameter); }
private MethodParameter FindByIndex(int i) { if (i >= MethodParameters.Count) { return(null); } return(MethodParameters .OrderBy(p => p.Position) .ToArray()[i] ); }
private void GetMethods(Dictionary <string, MethodInfoWithParam> methods, Func <string, MethodInfo> getMethod) { foreach (string methodName in methods.Keys.ToArray()) { //MethodInfo method = getMethod(methodsName); //methods[methodsName] = method; MethodInfoWithParam mwp = methods[methodName]; mwp.MethodInfo = getMethod(methodName); mwp.Parameters = MethodParameters.GetParameters(mwp.MethodInfo, mwp.NamedParameters, ErrorOptions.TraceWarning); } }
private static void LongRunningProcess(object input) { MethodParameters inputParams = (MethodParameters)input; Random random = new Random(((MethodParameters)input).ThreadId); Thread.Sleep(random.Next(500, 5000)); Console.WriteLine("Thread {0} complete in {1} seconds", inputParams.ThreadId, (DateTime.Now - inputParams.ThreadCreated).TotalSeconds); Interlocked.Decrement(ref _threadCounter); }
private Parameter FindByToken(string token) { Parameter result = MethodParameters .FirstOrDefault(p => p.IsIdentifiedBy(token)) ; if (result == null) { result = CommonParameters.FirstOrDefault(p => p.IsIdentifiedBy(token)); } return(result); }
internal virtual MethodParameters GetMethodParameters(string method) { MethodParameters parameters = new MethodParameters(); switch (method) { case "GetWorklistItems": { break; } } return(parameters); }
public static MethodParameters GetMethodParamaters(List <string> inputIds, MethodParameterType type) { MethodParameters paramCollection = new MethodParameters(); if (inputIds.Count == 0) { return(paramCollection); } foreach (var param in inputIds) { paramCollection.Create(CreateParameter(param, SoType.Text, false, type)); } return(paramCollection); }
public void GetParameters_DoesNotCallsWriteLine_WhenNoErrors() { var args = new List <CommandLineArgument>(); var expectedReturn = new MethodParameters { Errors = new List <string>() }; _mockMethodService.Setup(s => s.GetParameters(It.IsAny <MethodInfo>(), It.IsAny <List <CommandLineArgument> >())) .Returns(expectedReturn); var actual = _service.GetParameters(_command.Info, args); _mockConsoleService.Verify(s => s.WriteLine(It.IsAny <string>()), Times.Never()); }
private static void RunTest(MethodParameters mp) { var action = mp.Action; var token = mp.Token; var stdOut = mp.StdOut; var runningTests = mp.RunningTests; var startOrderInt = mp.StartOrderInt; var totalRuntime = mp.TotalRuntime; var testResults = mp.TestResults; //stdOut.Write(string.Format("\r> Starting: {0} \n", action.Name)); token.ThrowIfCancellationRequested(); runningTests.IncrementIndex(action.Index); var startOrder = Interlocked.Increment(ref startOrderInt); var startTime = totalRuntime.Elapsed; var sw = new Stopwatch(); sw.Start(); var exitCode = action.RunTests(); sw.Stop(); testResults.Add(new RunStats { Name = action.Name, StartTime = startTime, RunTime = sw.Elapsed, EndTime = totalRuntime.Elapsed, StartOrder = startOrder, FinishOrder = testResults.Count, ExitCode = exitCode }); // stdOut.WriteLine("Just finished " + action.Name); runningTests.IncrementIndex(action.Index); if (exitCode != 0) { //Go to TestFailure runningTests.IncrementIndex(action.Index); if (!Console.IsOutputRedirected) stdOut.Write("\r! Test failure: {0} ({1}) \n", action.Name, exitCode); } if (exitCode < 0) { //Go to RunFailure runningTests.IncrementIndex(action.Index); } Interlocked.Decrement(ref _threadCounter); }
public override void VisitMethodParameters(MethodParameters mp) { Code.Append("("); var last = mp.Parameters.LastOrDefault(); foreach (var pd in mp.Parameters) { pd.Accept(this); if (pd != last) { Code.Append(", "); } } Code.Append(")"); }
public string GetMethodBasedUniqueName() { var tempParams = MethodParameters.Any() ? MethodParameters.Aggregate(aggregate) : ""; string temp = $"{NameSpaceAndClass}={MethodToRun}={tempParams}.json"; char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); foreach (char item in invalidFileNameChars) { temp = temp.Replace(item.ToString(), ""); } if (temp.Length > maxFileLength) { return(temp.Substring(temp.Length - maxFileLength).Trim()); } return(temp); }
/// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) { return(false); } MethodParameters methodParameters = (MethodParameters)obj; if (this.Parameters == null && methodParameters.Parameters == null) { return(true); } if ((this.Parameters != null && methodParameters.Parameters == null) || (this.Parameters == null && methodParameters.Parameters != null)) { return(false); } if (this.Parameters.Length != methodParameters.Parameters.Length) { return(false); } foreach (MethodParameter methodParmeter in this.Parameters) { bool cycleResult = false; foreach (MethodParameter innerMethodParameter in methodParameters.Parameters) { if (methodParmeter.Equals(innerMethodParameter)) { cycleResult = true; } } if (cycleResult == false) { return(false); } } return(true); }
private static void CreateThread(TestRunAction action, CancellationToken token, TextWriterWrapper stdOut, ProgressStats runningTests, int startOrderInt, Stopwatch totalRuntime, ConcurrentBag <RunStats> testResults) { var parameters = new MethodParameters { Action = action, RunningTests = runningTests, StartOrderInt = startOrderInt, StdOut = stdOut, TestResults = testResults, Token = token, TotalRuntime = totalRuntime }; Interlocked.Increment(ref _threadCounter); ThreadPool.QueueUserWorkItem(RunTest, parameters); }
public string Translate(string targetLanguage, MethodParameters param) { ensureAuthenticated(); if (!processDocument(token, param, sourceLanguage, targetLanguage)) { return(null); } MemoryStream t = new MemoryStream(); html.Save(t); t.Seek(0, SeekOrigin.Begin); var reader1 = new StreamReader(t); string translatedHtml = reader1.ReadToEnd(); return(translatedHtml); }
/// <summary> /// Handle the facet call request /// </summary> public JsonValue Handle(MethodParameters methodParameters) { string sessionId = ProcessSessionId(methodParameters); FacetRequest request = FacetRequest.CreateFrom( methodParameters.FacetName, methodParameters.MethodName, methodParameters.Arguments, app.GameAssemblyTypes ); MiddlewareAttribute[] globalMiddleware = { new MiddlewareAttribute( 1, typeof(StartSession), sessionId ) }; var response = FacetMiddleware.ExecuteMiddlewareStack( app, globalMiddleware, request, rq => { object returnedValue = null; UnwrapTargetInvocationException(() => { returnedValue = rq.Method.Invoke( rq.Facet, rq.Arguments ); }); return(FacetResponse.CreateFrom( returnedValue, request.Method )); } ); return(response.ReturnedJson); }
private static void CreateThread(TestRunAction action, CancellationToken token, TextWriterWrapper stdOut, ProgressStats runningTests, Stopwatch totalRuntime, ConcurrentBag<RunStats> testResults) { var startOrder = Interlocked.Increment(ref _startOrderInt); var parameters = new MethodParameters { Action = action, RunningTests = runningTests, StartOrderInt = startOrder, StdOut = stdOut, TestResults = testResults, Token = token, TotalRuntime = totalRuntime }; Interlocked.Increment(ref _threadCounter); //Shouldn't really use built-in thread pool for long-running processes... ThreadPool.QueueUserWorkItem(RunTest, parameters); }
protected virtual Method ParseMethod(MethodInfo methodInfo) { Parameter[] parameters = methodInfo .GetParameters() .Select(ParseParameter) .ToArray(); var constructorParameters = new MethodParameters { Name = methodInfo.Name, RawReturnType = methodInfo.ReturnType, ReturnType = ReflectionUtility.GetGeneralizedTypeName(methodInfo.ReturnType), AccessModifier = ReflectionUtility.GetAccessModifier(methodInfo), Parameters = parameters, }; var method = new Method(constructorParameters); return(method); }
internal static MethodParameters ToMethodParameters(this BindingSettings bindingSettings) { var methodParameters = new MethodParameters(); var arguments = bindingSettings.BindingType.GetGenericArguments(); if (bindingSettings.IsFunction()) { var length = arguments.Length - 2; methodParameters.ReturnType = arguments.Last(); methodParameters.Parameters = new Type[length]; Array.Copy(arguments, 1, methodParameters.Parameters, 0, length); } else { methodParameters.Parameters = arguments.Skip(1).ToArray(); } return(methodParameters); }
private static InvocationArgument GetParametersArgument(MethodDef method, out Local parametersVariable) { var methodParameters = new MethodParameters(method); var hasParameters = methodParameters.Count > 0; var localParametersVariable = parametersVariable = hasParameters ? new Local(new SZArraySig(method.Module.CorLibTypes.Object)) { Name = "parameters" } : null; return(new InvocationArgument("Parameters", hasParameters, delegate(Instructions instructions) { method.Body.Variables.Add(localParametersVariable); instructions.EmitLdc(methodParameters.Count); instructions.Emit(OpCodes.Newarr, method.Module.CorLibTypes.Object); instructions.EmitStloc(localParametersVariable); // setups parameters array for (int parameterIndex = 0; parameterIndex < methodParameters.Count; parameterIndex++) { var parameter = methodParameters[parameterIndex]; // we don't care about output parameters if (!parameter.ParamDef.IsOut) { instructions.EmitLdloc(localParametersVariable); // array instructions.EmitLdc(parameterIndex); // array index instructions.EmitLdarg(parameter); // loads given parameter... var parameterType = parameter.Type; if (parameterType is ByRefSig) // ...if ref, loads it as referenced value { parameterType = parameter.Type.Next; instructions.EmitLdind(parameterType); } instructions.EmitBoxIfNecessary(parameterType); // ... and boxes it instructions.Emit(OpCodes.Stelem_Ref); } } instructions.EmitLdloc(localParametersVariable); }, instructions => instructions.Emit(OpCodes.Ldnull))); }
private MethodParameters GetMethodParameters(string method) { MethodParameters parameters = new MethodParameters(); switch (method) { case "RedirectWorklistItem": { parameters.Add(new MethodParameter("UserName", "System.String", SoType.Text, new MetaData("User Name", ""))); break; } case "RedirectManagedUserWorklistItem": { parameters.Add(new MethodParameter("ManagedUserName", "System.String", SoType.Text, new MetaData("Managed User Name", ""))); parameters.Add(new MethodParameter("UserName", "System.String", SoType.Text, new MetaData("User Name", ""))); break; } } return(parameters); }
private MethodParameters GetMethodParameters(string method) { MethodParameters parameters = new MethodParameters(); switch (method) { case "RedirectWorklistItem": { parameters.Add(new MethodParameter("UserName", "System.String", SoType.Text, new MetaData("User Name", ""))); break; } case "RedirectManagedUserWorklistItem": { parameters.Add(new MethodParameter("ManagedUserName", "System.String", SoType.Text, new MetaData("Managed User Name", ""))); parameters.Add(new MethodParameter("UserName", "System.String", SoType.Text, new MetaData("User Name", ""))); break; } } return parameters; }
private MethodParameters GetMethodParameters(string method) { MethodParameters parameters = new MethodParameters(); switch (method) { case "GetWorklistItems": { break; } } return parameters; }