public void GetTxCounts(int begin, int end) { List <object> blockInfos = new List <object>(); string url = "http://192.168.199.221:8000/chain"; var ch = new CliHelper(url); var ci = new CommandInfo("get_block_info"); for (int i = begin; i <= end; i++) { dynamic blockInfo = new System.Dynamic.ExpandoObject(); int height = i; ci.Parameter = height.ToString(); ch.ExecuteCommand(ci); Assert.IsTrue(ci.Result); ci.GetJsonInfo(); var result = ci.JsonInfo; string count = result["result"]["result"]["Body"]["TransactionsCount"].ToString(); string txpoolSize = result["result"]["result"]["CurrentTransactionPoolSize"].ToString(); blockInfo.Height = height; blockInfo.TxCount = count; blockInfo.PoolSize = txpoolSize; blockInfos.Add(blockInfo); } foreach (dynamic item in blockInfos) { string message = $"Height: {item.Height}, TxCount: {item.TxCount}, CurrentTransactionPoolSize: {item.PoolSize}"; Console.WriteLine(message); System.Diagnostics.Debug.WriteLine(message); } Console.ReadLine(); }
private static Dictionary <Option, string?> ParseOptions(string text) { var dictionary = DefaultOptions(); var combinedOptions = CliHelper.CombineOption(text.Split(' ', StringSplitOptions.RemoveEmptyEntries), ' '); var queue = new Queue <string?>(combinedOptions); while (queue.Count > 0) { var entry = queue.Dequeue(); if (entry == "-t" || entry == "--type") { dictionary[Option.Type] = queue.Dequeue(); } else if (entry == "-a" || entry == "--alias") { dictionary[Option.Alias] = queue.Dequeue(); } else if (entry == "-m" || entry == "--method") { dictionary[Option.Method] = queue.Dequeue(); } else if (entry == "-c" || entry == "--content") { dictionary[Option.Content] = queue.Dequeue(); } else if (entry == "-p" || entry == "--path") { dictionary[Option.Path] = queue.Dequeue(); } } return(dictionary); }
internal static string ScriptSignature(object [] values) { System.Text.StringBuilder sig = new System.Text.StringBuilder(); for (int i = 0; i != values.Length; ++i) { object value = values [i]; string s; if (value == null) { s = "null"; } else if (value is System.Boolean) { s = "boolean"; } else if (value is string) { s = "string"; } else if (CliHelper.IsNumber(value)) { s = "number"; } else if (value is IScriptable) { if (value is Undefined) { s = "undefined"; } else if (value is Wrapper) { object wrapped = ((Wrapper)value).Unwrap(); //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1043_3"' s = wrapped.GetType().FullName; } else if (value is IFunction) { s = "function"; } else { s = "object"; } } else { s = CliHelper.ToSignature(value.GetType()); } if (i != 0) { sig.Append(','); } sig.Append(s); } return(sig.ToString()); }
private static int GetJSTypeCode(System.Object value) { if (value == null) { return(JSTYPE_NULL); } else if (value == Undefined.Value) { return(JSTYPE_UNDEFINED); } else if (value is string) { return(JSTYPE_STRING); } else if (CliHelper.IsNumber(value)) { return(JSTYPE_NUMBER); } else if (value is bool) { return(JSTYPE_BOOLEAN); } else if (value is IScriptable) { if (value is CliType) { return(JSTYPE_CLI_CLASS); } else if (value is CliArray) { return(JSTYPE_CLI_ARRAY); } else if (value is Wrapper) { return(JSTYPE_CLI_OBJECT); } else { return(JSTYPE_OBJECT); } } else if (value is Type) { return(JSTYPE_CLI_CLASS); } else { if (value.GetType().IsArray) { return(JSTYPE_CLI_ARRAY); } else { return(JSTYPE_CLI_OBJECT); } } }
private CliType(Type type) { m_Type = type; // Check for class attribute m_ClassAttribute = (EcmaScriptClassAttribute) CliHelper.GetCustomAttribute(m_Type, typeof(EcmaScriptClassAttribute)); }
public void PrepareEnv() { Logger.WriteInfo("Preare new and unlock accounts."); CH = new CliHelper(RpcUrl); //New NewAccounts(1000); //Unlock Account UnlockAllAccounts(ThreadCount); }
public void GetTxResult(string rpcUrl, string txId) { var CH = new CliHelper(rpcUrl); string method = "get_tx_result"; var ci = new CommandInfo(method); ci.Parameter = txId; CH.ExecuteCommand(ci); ci.GetJsonInfo(); }
public void PrepareEnv() { Logger.WriteInfo("Rpc Url: {0}", RpcUrl); Logger.WriteInfo("Key Store Path: {0}", Path.Combine(KeyStorePath, "keys")); Logger.WriteInfo("Preare new and unlock accounts."); CH = new CliHelper(RpcUrl, KeyStorePath); //New NewAccounts(200); //Unlock Account UnlockAllAccounts(ThreadCount); }
public void PrepareEnv() { CH = new CliHelper(RpcUrl); //Delete DeleteAccounts(); //New NewAccounts(1000); //Unlock Account UnlockAllAccounts(ThreadCount); }
/// <summary> /// Returns a value indicating whether <paramref name="buildParametersJson"/> matches the expected results. /// </summary> /// <param name="buildParametersJson">The raw JSON parameters value that was provided to a <see cref="Build"/>.</param> /// <param name="pathVariable">Name of the path variable that the arguments are assigned to.</param> /// <param name="expectedPaths">The set of expected path arguments that should have been passed to the build.</param> private static bool FilterBuildToParameters(string buildParametersJson, string pathVariable, IList <string> expectedPaths) { JObject buildParameters = JsonConvert.DeserializeObject <JObject>(buildParametersJson); string pathString = buildParameters[pathVariable].ToString(); IList <string> paths = pathString .Split(" ", StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Trim().Trim('\'')) .Except(new string[] { CliHelper.FormatAlias(ManifestFilterOptionsBuilder.PathOptionName) }) .ToList(); return(CompareLists(expectedPaths, paths)); }
public SideChain(string rpcUrl, string chainName) { RpcUrl = rpcUrl.Contains("chain")? rpcUrl : $"{rpcUrl}/chain"; KeyStorePath = GetDefaultDataDir(); ChainName = chainName; CH = new CliHelper(RpcUrl, KeyStorePath); VerifyResultList = new ConcurrentQueue <VerifyResult>(); CancellationList = new List <CancellationTokenSource>(); InitVerifyAccount(); GetSideChainTxId(); }
public override string ToString() { string ret = "function " + m_Name + "() \n"; ret += "{/*\n"; foreach (MethodInfo mi in m_MethodInfos) { ret += CliHelper.ToSignature(mi) + "\n"; } ret += "*/}"; return(ret); }
public void IsUserSure() { ConsoleProvider.Current = new TestConsoleProvider("y{enter}n{enter}notagoodanswer{enter}y"); var cli = new CliHelper(); var firstAnswer = cli.IsUserSure("Dude this is dangerous"); var secondAnswer = cli.IsUserSure("Dude this is dangerous"); var thirdAnswer = cli.IsUserSure("Dude this is dangerous"); Assert.IsTrue(firstAnswer); Assert.IsFalse(secondAnswer); Assert.IsTrue(thirdAnswer); }
public static bool IsLatestVersion() { var currentVersion = CliHelper.GetCurrentVersion(); if (currentVersion == new Version(1, 0, 0, 0)) { return(true); } var latestVersion = GetLatestVersion(); return(latestVersion is null || !latestVersion.GreaterThan(currentVersion)); }
static void Main(string[] args) { try { CliHelper.Run(args); } catch (Exception ex) { ConsoleHelper.WriteError(ex); } #if DEBUG Console.ReadKey(); #endif }
private async Task <IAction?> ProcessDynamicCommand(EventData data, CustomCommand command) { if (!DynamicCommand.TryParse(command.Parameter !, out var dynaCmd)) { return(NewMessageAction("Corrupted dynamic command")); } var param = HttpUtility.HtmlDecode(data.CommandParameters ?? ""); var args = param?.Split(' ', StringSplitOptions.RemoveEmptyEntries); args = CliHelper.CombineOption(args, ' ').ToArray(); var expectedLength = command.ExpectedDynamicCommandArgs; if (args.Length != expectedLength) { return(NewMessageAction($"Expected {expectedLength} args, found {args.Length} for command '{command.Name}'")); } var timeout = TimeSpan.FromSeconds(10); try { var api = Uri.UnescapeDataString(dynaCmd !.ApiAddress.AbsoluteUri); args = args.Select(HttpUtility.UrlEncode).ToArray(); api = HttpUtility.HtmlDecode(string.Format(api, args)); if (dynaCmd.Method == Method.Get && dynaCmd.ResponseType == ResponseType.Image) { var alias = dynaCmd.Alias?.Trim(); // TODO Discord doesn't have a hyperlink markdown yet unfortunately. // but we can use this: https://leovoel.github.io/embed-visualizer/ api = string.IsNullOrEmpty(alias) ? api : $"[{alias}]({api})"; return(NewMessageAction(api)); } var cts = new CancellationTokenSource(timeout); var apiResponse = await Fetch(api, dynaCmd.Method, dynaCmd.ContentType, cts.Token); var stringContent = apiResponse.ToString() ?? "{}"; if (string.IsNullOrEmpty(dynaCmd.JsonPath)) { return(NewMessageAction(stringContent !)); } var obj = JObject.Parse(stringContent); var response = obj.SelectToken(dynaCmd.JsonPath)?.ToString() ?? stringContent; return(NewMessageAction(response)); } catch (OperationCanceledException) { return(NewMessageAction($"I can't wait for longer than {timeout:s} and the API is slow.")); } }
public void TestBasicAssistMiddleOfLineReplacingCurrentToken() { ConsoleProvider.Current = new TestConsoleProvider("choice: abc after{left}{left}{left}{left}{left}{left}{control} {w}{down}{down}{enter}"); CliHelper cli = new CliHelper(); var picker = new ContextAssistPicker(); picker.Options.Add(ContextAssistSearchResult.FromString("Option 1")); picker.Options.Add(ContextAssistSearchResult.FromString("Option 2")); picker.Options.Add(ContextAssistSearchResult.FromString("Option 3")); cli.Reader.ContextAssistProvider = picker; var line = cli.Reader.ReadLine(); Assert.AreEqual("choice: Option 3 after", line.ToString()); }
public void TestBasicAssistEndOfLineAfterASpace() { ConsoleProvider.Current = new TestConsoleProvider("choice: {control} {w}{down}{down}{enter}"); CliHelper cli = new CliHelper(); var picker = new ContextAssistPicker(); picker.Options.Add(ContextAssistSearchResult.FromString("Option 1")); picker.Options.Add(ContextAssistSearchResult.FromString("Option 2")); picker.Options.Add(ContextAssistSearchResult.FromString("Option 3")); cli.Reader.ContextAssistProvider = picker; var line = cli.Reader.ReadLine(); Assert.AreEqual("choice: Option 3", line.ToString()); }
public void TestCyclingUpThroughOptions() { ConsoleProvider.Current = new TestConsoleProvider("{control} {w}{up}{enter}"); CliHelper cli = new CliHelper(); var picker = new ContextAssistPicker(); picker.Options.Add(ContextAssistSearchResult.FromString("Option 1")); picker.Options.Add(ContextAssistSearchResult.FromString("Option 2")); picker.Options.Add(ContextAssistSearchResult.FromString("Option 3")); cli.Reader.ContextAssistProvider = picker; var line = cli.Reader.ReadLine(); Assert.AreEqual("Option 3", line.ToString()); }
static Type GetOrCreateType(Type eventHandlerType) { if (m_EventHandlerTypes.Contains(eventHandlerType)) { return((Type)m_EventHandlerTypes [eventHandlerType]); } MethodInfo mi = eventHandlerType.GetMethod("Invoke"); Type [] parameterTypes = CliHelper.GetParameterTypes(mi.GetParameters()); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName("Dyn_" + eventHandlerType.FullName.Replace(".", "_")), AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule("DynModule"); TypeBuilder tp = mb.DefineType("DynType", TypeAttributes.Public, typeof(ScriptableCallback)); MethodBuilder db = tp.DefineMethod("DynMethod", MethodAttributes.Public, CallingConventions.Standard, mi.ReturnType, parameterTypes); ILGenerator ilg = db.GetILGenerator(); ilg.DeclareLocal(typeof(object [])); int len = mi.GetParameters().Length; // 1. Array create ilg.Emit(OpCodes.Ldarg_0); ilg.Emit(OpCodes.Ldc_I4, len); ilg.Emit(OpCodes.Newarr, typeof(object)); ilg.Emit(OpCodes.Stloc_0); // 2. Parameter pushen for (int i = 0; i < len; i++) { ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldc_I4, i); ilg.Emit(OpCodes.Ldarg, i + 1); ilg.Emit(OpCodes.Stelem_Ref); } ilg.Emit(OpCodes.Ldloc_0); ilg.EmitCall(OpCodes.Call, typeof(ScriptableCallback).GetMethod("ScriptInvoke"), null); ilg.Emit(OpCodes.Pop); ilg.Emit(OpCodes.Ret); Type type = tp.CreateType(); m_EventHandlerTypes [eventHandlerType] = type; return(type); }
void Init(string name, MemberInfo [] methodInfos, object target) { m_Name = name; m_MethodInfos = new MethodInfo [methodInfos.Length]; Array.Copy( methodInfos, 0, m_MethodInfos, 0, m_MethodInfos.Length); m_Target = target; // Cache paramsParameters attribute paramsParameters = new bool [methodInfos.Length]; for (int i = 0; i < methodInfos.Length; i++) { paramsParameters [i] = CliHelper.HasParamsParameter( m_MethodInfos [i]); } }
private static void HandleVersionOption() { System.Console.WriteLine(CliHelper.GetCurrentVersion().ToString()); if (CodingRulesUpdaterVersionHelper.IsLatestVersion()) { return; } var latestVersion = CodingRulesUpdaterVersionHelper.GetLatestVersion() !; System.Console.WriteLine(string.Empty); System.Console.WriteLine($"Version {latestVersion} of ATC-Coding-Rules-Updater is available!"); System.Console.WriteLine(string.Empty); System.Console.WriteLine("To update run the following command:"); System.Console.WriteLine(" dotnet tool update --global atc-coding-rules-updater"); }
private static void HandleVersionOption() { System.Console.WriteLine(CliHelper.GetCurrentVersion().ToString()); if (CliVersionHelper.IsLatestVersion()) { return; } var latestVersion = CliVersionHelper.GetLatestVersion() !; System.Console.WriteLine(string.Empty); System.Console.WriteLine($"Version {latestVersion} of ATC-Rest-Api-Generator is available!"); System.Console.WriteLine(string.Empty); System.Console.WriteLine("To update run the following command:"); System.Console.WriteLine(" dotnet tool update --global atc-rest-api-generator"); }
public override object GetDefaultValue(Type hint) { if (hint == null || hint == typeof(string)) { return(array.ToString()); } if (hint == typeof(bool)) { return(true); } if (CliHelper.IsNumberType(hint)) { return(BuiltinNumber.NaN); } return(this); }
public override string ToString() { string ret = "function " + ClassName + "() \n"; ret += "{/*\n"; foreach (ConstructorInfo ci in m_Type.GetConstructors()) { ret += CliHelper.ToSignature(ci) + "\n"; } foreach (MemberInfo mi in m_Type.GetMembers(BindingFlags.Static | BindingFlags.Public)) { ret += CliHelper.ToSignature(mi) + "\n"; } ret += "*/}"; return(ret); }
public override object ExecIdCall(IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args) { int id = f.MethodId; switch (id) { case Id_print: for (int i = 0; i < args.Length; i++) { if (i > 0) { Console.Out.Write(" "); } Console.Out.Write(ScriptConvert.ToString(args [i])); } Console.Out.WriteLine(); return(Undefined.Value); case Id_version: if (args.Length > 0) { if (CliHelper.IsNumber(args [0])) { int newVer = (int)ScriptConvert.ToNumber(args [0]); if (Context.IsValidLanguageVersion(newVer)) { cx.Version = Context.ToValidLanguageVersion(newVer); } } } return((int)cx.Version); case Id_options: StringBuilder sb = new StringBuilder(); if (cx.HasFeature(Context.Features.Strict)) { sb.Append("strict"); } return(sb.ToString()); case Id_gc: GC.Collect(); return(Undefined.Value); } throw f.Unknown(); }
public static void PrintUpdateInfoIfNeeded( ILogger logger) { if (IsLatestVersion()) { return; } var currentVersion = CliHelper.GetCurrentVersion(); var latestVersion = GetLatestVersion() !; logger.LogWarning($"Version {latestVersion} of ATC-Coding-Rules-Updater is available!"); logger.LogWarning($"You are running version {currentVersion}"); logger.LogWarning(string.Empty); logger.LogWarning("To update run the following command:"); logger.LogWarning(" dotnet tool update --global atc-coding-rules-updater"); logger.LogWarning(string.Empty); }
public override object GetDefaultValue(Type hint) { object value; if (hint == null || hint == typeof(String)) { value = m_Object.ToString(); } else { string converterName; if (hint == typeof(bool)) { converterName = "booleanValue"; } else if (CliHelper.IsNumberType(hint)) { converterName = "doubleValue"; } else { throw Context.ReportRuntimeErrorById("msg.default.value"); } object converterObject = Get(converterName, this); if (converterObject is IFunction) { IFunction f = (IFunction)converterObject; value = f.Call(Context.CurrentContext, f.ParentScope, this, ScriptRuntime.EmptyArgs); } else { if (CliHelper.IsNumberType(hint) && m_Object is bool) { bool b = (bool)m_Object; value = b ? 1.0 : 0.0; } else { value = m_Object.ToString(); } } } return(value); }
public override object Get(int index, IScriptable start) { foreach (MethodInfo mi in m_Type.IndexGetter) { ParameterInfo [] pis = mi.GetParameters(); if (pis.Length == 1 && CliHelper.IsNumberType(pis [0].ParameterType)) { return(mi.Invoke(m_Object, new object [] { index })); } } object result = base.Get(index, start); if (result != UniqueTag.NotFound) { return(result); } return(UniqueTag.NotFound); }
//creates a reservation based on the user's chosen dates and siteId private void CreateReservation(DateTime arriveDate, DateTime departDate) { Console.ForegroundColor = (ConsoleColor.Magenta); int siteIdSelection = CliHelper.GetInteger("Which site should be reserved (enter 0 to cancel)?: "); //if user chooses 0 then return to original menu if (siteIdSelection == 0) { Console.Clear(); return; } //else statement proceeds with good reservation else { Console.ForegroundColor = (ConsoleColor.Magenta); string reservedName = CliHelper.GetString("What name should the reservation be made under?: "); Reservation reservation = new Reservation { siteID = siteIdSelection, name = reservedName, fromDate = arriveDate, toDate = departDate }; int reservationId = reservationDAO.CreateReservation(reservation); if (reservationId > 0) { Console.ForegroundColor = (ConsoleColor.Magenta); Console.WriteLine("Your reservation has been added"); Console.WriteLine(); } else { Console.ForegroundColor = (ConsoleColor.Red); Console.WriteLine("Error, try again"); Console.WriteLine(); } } }