public static void SQLWhere_SubStr(ref ArrayList ParameterList, DbType type, string FieldName, Object FieldValue, string Operator, string AndOr, int StartPos, int EndPos) { if (FieldValue.ToString().Trim() == "" || FieldValue.ToString().Trim() == "%%") return; ParameterItem pi = new ParameterItem(); pi.ParaName = CheckParaName(ParameterList, FieldName); switch (type) { case DbType.String: pi.WhereString = string.Format(" {0} Substr({1},{4},{5}) {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StartPos.ToString(), EndPos.ToString()); break; case DbType.Decimal: pi.WhereString = string.Format(" {0} Substr({1},{4},{5}) {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StartPos.ToString(), EndPos.ToString()); break; case DbType.VarNumeric: pi.WhereString = string.Format(" {0} Substr({1},{4},{5}) {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StartPos.ToString(), EndPos.ToString()); break; case DbType.DateTime: pi.WhereString = string.Format(" {0} Substr({1},{4},{5}) {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StartPos.ToString(), EndPos.ToString()); FieldValue = string.Format("#{0}#", FieldValue.ToString()); break; } pi.FieldName = FieldName; pi.FieldType = type; pi.FieldValue = FieldValue; ParameterList.Add(pi); }
public async Task <IEnumerable <ProjectItem> > GetProjects(string url = null) { try { if (url == null) { url = this.MarketUrl; } string username = null; string project = null; string target = null; if (!this.GetRepoInfo(url, out username, out project, out target)) { XLogSys.Print.Error(GlobalHelper.Get("market_url_check")); return(null); } IReadOnlyList <RepositoryContent> result = null; result = await client.Repository.Content.GetAllContents(username, project, target); var items = result?.Where(d => d.Type == ContentType.File && (d.Name.EndsWith(".xml", true, null) || d.Name.EndsWith(".hproj", true, null))).Select( d => { var projectItem = new ProjectItem() { IsRemote = true, SavePath = d.DownloadUrl }; var suffix = d.Name.Split('.').Last(); var name = d.Name.Replace("." + suffix, ""); projectItem.Name = name; var meta = name + ".meta"; var metafile = result.FirstOrDefault(d2 => d2.Name == meta); if (metafile != null) { Task.Factory.StartNew(() => { var response = WebRequest.Create(metafile.DownloadUrl).GetResponse().GetResponseStream(); using (StreamReader reader = new StreamReader(response, Encoding.UTF8)) { var item = reader.ReadToEnd(); var metainfo = ParameterItem.GetParameters(item); ControlExtended.UIInvoke(() => { projectItem.DictDeserialize(metainfo.ToDictionary(d2 => d2.Key, d2 => (object)d2.Value)); }); } }); } return(projectItem); }); return(items); } catch (Exception ex) { XLogSys.Print.Error(ex.Message); return(new List <ProjectItem>()); } }
private void ReadValueDataDele() { var path = $"{Environment.CurrentDirectory}\\ValueData.txt"; var content = FileHelper.ReadFile(path); var list = content.Split(Environment.NewLine.ToCharArray()); var result = ""; var list1 = new List<ParameterItem>(); foreach (string item in list) { if (item == "") continue; var kv = new ParameterItem(); kv.Id = Guid.NewGuid().ToString(); kv.Group = "Value"; kv.Name = ""; kv.Value = item; list1.Add(kv); } ValueList = list1; this.BeginInvoke(new DeleParaObject(ReadValueDataAction), list1); base.EndExecute(null); }
public void SaveFile() { ParameterManager.Instance.DeviceName = "BQ20Z45-R"; ParameterManager.Instance.SMBusAddressSize = 1; ParameterManager.Instance.SMBusSpeed = 10000; ParameterManager.Instance.SMBusAdapter = "SIL CP2112"; ParameterItem pi1 = new ParameterItem { Commmand = 0, Name = "ManufacturerAccess", Mode = "R/W", Format = "X4", Size = 2, DefaultValue = "-", Unit = "-", }; ParameterItem pi2 = new ParameterItem { Commmand = 0, Name = "RemainingCapacityAlarm", Mode = "R/W", Format = "D5", Size = 2, DefaultValue = "300", Unit = "mAh", } ; ParameterManager.Instance.Parameters.Add(pi1); ParameterManager.Instance.Parameters.Add(pi2); ParameterManager.SaveFile(ParamFilePath); }
public static void SQLWhere_DateFormat(ref ArrayList ParameterList, DbType type, string FieldName, Object FieldValue, string Operator, string AndOr, string StringProvider) { if (FieldValue.ToString().Trim() == "" || FieldValue.ToString().Trim() == "%%" || type != DbType.DateTime) return; ParameterItem pi = new ParameterItem(); pi.ParaName = ((FieldName.ToUpper() == "ROWNUM") ? "ROWNUM_1" : CheckParaName(ParameterList, FieldName)); switch (type) { case DbType.String: pi.WhereString = string.Format(" {0} TO_CHAR({1},'{4}') {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StringProvider); break; case DbType.Decimal: pi.WhereString = string.Format(" {0} TO_CHAR({1},'{4}') {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StringProvider); break; case DbType.VarNumeric: pi.WhereString = string.Format(" {0} TO_CHAR({1},'{4}') {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StringProvider); break; case DbType.DateTime: pi.WhereString = string.Format(" {0} TO_CHAR({1},'{4}') {2} :{3}", AndOr, FieldName, Operator, pi.ParaName, StringProvider); break; } pi.FieldName = FieldName; pi.FieldType = DbType.String; pi.FieldValue = FieldValue; ParameterList.Add(pi); }
/// <summary> /// Checks specified parameter. /// </summary> private static void AssertParameter( string expectedName, int expectedLineNumber, ParameterItem parameter) { Assert.AreEqual(expectedName, parameter.Name); Assert.IsTrue(parameter.LineNumber.HasValue); Assert.AreEqual(expectedLineNumber, parameter.LineNumber); }
private void UpdateUserNameCandidates(ParameterItem currentItem) { _userNameBox.Items.Clear(); _userNameBox.Items.AddRange( _historyItems.Where(item => item.TCPParameter.Destination == currentItem.TCPParameter.Destination) .Select(item => item.SSHParameter.Account) .Distinct() .OrderBy(s => s) .ToArray() ); }
NetParam MapParameterItem(BaseDeclaration context, ParameterItem parameter, int index, bool isPinvoke, bool structsAndEnumsAreAlwaysRefs) { var theType = parameter.TypeSpec; //parameter.IsInOut && !parameter.TypeSpec.IsInOut ? parameter.TypeSpec.WithInOutSet () : parameter.TypeSpec; var t = MapType(context, theType, isPinvoke); if (isPinvoke) { t = RecastToReference(context, t, theType, structsAndEnumsAreAlwaysRefs); } return(ToNamedParam(parameter, t, index)); }
void _BtnRemove_Click(object sender, System.EventArgs e) { if (_LbItems.SelectedItem != null) { ParameterItem pi = (ParameterItem)_LbItems.SelectedItem; _Data.Remove(pi.Data); _LbItems.Items.Remove(pi); _LbItems.SelectedItem = null; this._OwnerListItem.UpdateContent(); } }
public static void SQLWhere(ref ArrayList ParameterList, string FieldName, string ParaName, Object FieldValue, string Operator, string AndOr) { if (FieldValue.ToString().Trim() == "" || FieldValue.ToString().Trim() == "%%") return; ParameterItem pi = new ParameterItem(); pi.ParaName = ParaName; pi.WhereString = string.Format(" {0} {1} {2} :{3}", AndOr, FieldName, Operator, pi.ParaName); pi.FieldName = FieldName; pi.FieldType = DbType.String; pi.FieldValue = FieldValue; ParameterList.Add(pi); }
public List <ParameterItem> RebuildParameterListWithGenericTypes(List <ParameterItem> pl) { var result = new List <ParameterItem> (pl.Count); foreach (var item in pl) { var newItem = new ParameterItem(item); newItem.TypeSpec = RebuildTypeWithGenericType(item.TypeSpec); result.Add(newItem); } return(result); }
public static void SQLWhere(ref ArrayList ParameterList, DbType type, string FieldName, Object FieldValue) { ParameterItem pi = new ParameterItem(); pi.ParaName = CheckParaName(ParameterList, FieldName); pi.FieldName = FieldName; pi.FieldType = type; if (type != DbType.String) { pi.FieldValue = ((FieldValue == null || FieldValue.ToString() == "") ? null : FieldValue); } else pi.FieldValue = FieldValue; ParameterList.Add(pi); }
/// <summary> /// Apply specified parameters to the input controls. /// </summary> /// <param name="item">parameters to apply</param> private void ApplyParameters(ParameterItem item) { _portBox.Text = item.TCPParameter.Port.ToString(); _encodingBox.SelectedItem = item.TerminalSettings.Encoding; _localEchoBox.SelectedItem = item.TerminalSettings.LocalEcho; _newLineBox.SelectedItem = item.TerminalSettings.TransmitNL; _telnetNewLine.Checked = (item.TerminalSettings.TransmitNL == NewLine.CRLF) ? item.TelnetParameter.TelnetNewLine : false; _terminalTypeBox.SelectedItem = item.TerminalSettings.TerminalType; UpdateControlStatus(); }
static bool TypeMatches(FunctionDeclaration decl, ParameterItem pi, SwiftType st, bool ignoreName, TypeMapper typeMap) { // some SwiftType parameters have no names, such as operators if (!ignoreName && pi.PublicName != "self" && st.Name != null && pi.PublicName != st.Name.Name) { return(false); } if (pi.IsVariadic != st.IsVariadic) { return(false); } return(TypeMatches(decl, pi.TypeSpec, st, typeMap)); }
public static void SetInOutParam(DairyDateItem param) { InParam = new ParameterItem() { ParameterName = @"Date", ParameterValue = param.Date }; OutParam = new ParameterItem() { ParameterName = @"result", ParameterValue = 0 }; }
/// <summary> /// Apply specified parameters to the input controls. /// </summary> /// <param name="item">parameters to apply</param> private void ApplyParameters(ParameterItem item) { UpdateUserNameCandidates(item); if (item.SSHParameter.Method == Granados.SSHProtocol.SSH1) { this._ssh1RadioButton.Checked = true; } else { this._ssh2RadioButton.Checked = true; } _portBox.Text = item.TCPParameter.Port.ToString(); _userNameBox.Text = item.SSHParameter.Account; _authOptions.SelectedItem = item.SSHParameter.AuthenticationType.ToAuthType(); _passphraseBox.Text = item.SSHParameter.PasswordOrPassphrase; _privateKeyFile.Text = item.SSHParameter.IdentityFileName; _encodingBox.SelectedItem = item.TerminalSettings.Encoding; _localEchoBox.SelectedItem = item.TerminalSettings.LocalEcho; _newLineBox.SelectedItem = item.TerminalSettings.TransmitNL; _terminalTypeBox.SelectedItem = item.TerminalSettings.TerminalType; _useX11ForwardingCheckBox.Checked = item.SSHParameter.EnableX11Forwarding; if (item.SSHParameter.X11Forwarding != null) { _x11DisplayText.Text = item.SSHParameter.X11Forwarding.Display.ToString(); _x11ScreenText.Text = item.SSHParameter.X11Forwarding.Screen.ToString(); _x11NeedAuthCheckBox.Checked = item.SSHParameter.X11Forwarding.NeedAuth; _x11XauthorityText.Text = item.SSHParameter.X11Forwarding.XauthorityFile; _x11UseCygwinDomainSocketCheckBox.Checked = item.SSHParameter.X11Forwarding.UseCygwinUnixDomainSocket; _x11CygwinX11UnixFolderText.Text = item.SSHParameter.X11Forwarding.X11UnixFolder; } else { _x11DisplayText.Text = "0"; _x11ScreenText.Text = "0"; _x11NeedAuthCheckBox.Checked = false; _x11XauthorityText.Text = ""; _x11UseCygwinDomainSocketCheckBox.Checked = false; _x11CygwinX11UnixFolderText.Text = ""; } _useAgentForwardingCheckBox.Checked = item.SSHParameter.EnableAgentForwarding; UpdateControlStatus(); }
void _BtnAdd_Click(object sender, System.EventArgs e) { ParameterData data = new ParameterData() { Name = "NewInt", Type = ParameterType.Int, Value = "0" }; _Data.Add(data); ParameterItem pi = new ParameterItem(_OwnerListItem, data); _LbItems.Items.Add(pi); _LbItems.SelectedItem = pi; this._OwnerListItem.UpdateContent(); }
private void AppendSubProperties(ref ParameterItem parameterItem, PropertyInfo propertyInfo) { var properties = propertyInfo.PropertyType.GetProperties(); foreach (var property in properties) { ParameterItem subParameterItem = new ParameterItem(property); var serializableAttribute = property.PropertyType.GetCustomAttribute(typeof(SerializableAttribute)); if (serializableAttribute == null && property.PropertyType != property.DeclaringType) { AppendSubProperties(ref subParameterItem, property); } parameterItem.Properties.Add(subParameterItem); } }
public void Initialize() { string xmlFileContent = File.ReadAllText(options.XmlFilePath); Doc docsAssembly = Helpers.ParseXml(xmlFileContent); var controllers = Helpers.GetClasses(options.ProjectAssembly); List <ControllerItem> controllerItems = new List <ControllerItem>(); foreach (var controller in controllers) { ControllerItem controllerItem = new ControllerItem(controller); controllerItem.Description = docsAssembly.Members.Member.FirstOrDefault(x => x.Name == $"T:{controller.Namespace}.{controller.Name}").Summary; controllerItem.Description = controllerItem.Description.Trim().Replace("\n", ""); var actions = Helpers.GetMethods(controller); foreach (var action in actions) { ActionItem actionItem = new ActionItem(controllerItem, action); string actionXmlName = $"M:{controller.Namespace}.{controller.Name}.{action.Name}"; actionItem.Description = docsAssembly.Members.Member.FirstOrDefault(x => x.Name == actionXmlName)?.Summary; actionXmlName += "("; var parameters = Helpers.GetParameters(action); foreach (var parameter in parameters) { if (String.IsNullOrEmpty(actionItem.Description)) { actionXmlName += parameter.ParameterType + ","; } bool isVariable = parameter.ParameterType.BaseType == typeof(ValueType); ParameterItem parameterItem = new ParameterItem(parameter); if (!isVariable) { AppendSubProperties(ref parameterItem, parameter); } actionItem.Parameters.Add(parameterItem); } if (String.IsNullOrEmpty(actionItem.Description)) { actionXmlName = actionXmlName.TrimEnd(',') + ")"; actionItem.Description = docsAssembly.Members.Member.FirstOrDefault(x => x.Name == actionXmlName)?.Summary; } actionItem.Description = actionItem.Description?.Trim().Replace("\n", ""); controllerItem.Actions.Add(actionItem); } controllerItems.Add(controllerItem); } options.DocumentWriter.WriteDocument(controllerItems); }
private static void CreateSample() { List <ParameterItem> paramList = new List <ParameterItem>(); ParameterItem param = new ParameterItem { ShortParameter = "i", LongParameter = "input-file", VariableName = "inputFile", Description = "filename that contains the JSON values to drive the script. command line overrides file", RequiresInputString = true, Default = "", // this needs to be empty because if it is set, the script will try to find the file... RequiredParameter = false, ValueIfSet = "$2" }; paramList.Add(param); param = new ParameterItem { LongParameter = "log-directory", ShortParameter = "l", Description = "directory for the log file. the log file name will be based on the script name", VariableName = "logDirectory", Default = "\"./\"", RequiresInputString = true, RequiredParameter = false, ValueIfSet = "$2" }; paramList.Add(param); param = new ParameterItem { ShortParameter = "d", Description = "delete the resource group if it already exists", LongParameter = "delete", VariableName = "delete", Default = "false", RequiresInputString = false, RequiredParameter = false, ValueIfSet = "true" }; paramList.Add(param); ConfigModel model = new ConfigModel("test.sh", paramList, true, true, true, true); Console.WriteLine(model.Serialize()); }
protected override void CreateCustomFileds() { base.CreateCustomFileds(); _Item = (ParameterItem)Object; if (_Item.Data.Type == AnimationTreeParameterType.Float) { _FloatField = new UI.FloatField(); _FloatField.Label.text = "Default Value"; _FloatField.ValueChanged += _FloatField_ValueChanged; Controls.Add(_FloatField); } else { _IntField = new UI.IntField(); _IntField.Label.text = "Default Value"; _IntField.ValueChanged += _IntField_ValueChanged; Controls.Add(_IntField); } }
/// <summary> /// 获取接口数据 /// </summary> /// <returns></returns> public Dictionary <string, DoTaskParameterItem> GetInterfaces() { if (TaskParameterItems.Count() != 0) { return(TaskParameterItems); } else { RouteAttribute classRoute = this.GetAttributeByClass <RouteAttribute>(); string rootPath = classRoute.Url; var methods = this.GetType().GetMethods(); methods.Foreach(m => { var attributes = m.GetCustomAttributes().Where(a => a is RouteAttribute); if (attributes.Count() > 0) { RouteAttribute route = attributes.First() as RouteAttribute; List <ParameterItem> paramters = new List <ParameterItem>(); m.GetParameters().Foreach(p => { var it = new ParameterItem() { ParameterName = p.Name, }; if (p.HasDefaultValue) { it.Value = p.DefaultValue.ToString(); } paramters.Add(it); }); this.TaskParameterItems.Add(rootPath + route.Url + string.Format("{0}", route.Explanation), new DoTaskParameterItem() { Paramters = paramters, Url = rootPath + route.Url, Method = m }); } }); return(TaskParameterItems); } }
static void Main() { var cb = new ClassBuilder("EntryPoint", TypeAttributes.Public, false); var pi = new ParameterItem(); pi.Name = "s"; pi.Type = typeof(string); IStatementLine[] Statements = new IStatementLine[] { new ExpressionStatementLine(), new ReturnStatementLine() }; var methodInvoke = new MethodInvokeExpressionLine(); methodInvoke.MethodName = "WriteLine"; var test = new TypeReferenceExpressionLine(); test.Type = "System.Console"; methodInvoke.TargetObject = test; var methodInvokeParam = new VariableReferenceExpressionLine(); methodInvokeParam.VariableName = "s"; methodInvoke.Parameters = new IExpressionLine[] { methodInvokeParam }; Statements[1].Expressions.Add(0, new VariableReferenceExpressionLine() { VariableName = "s" }); Statements[0].Expressions.Add(0, methodInvoke); cb.AddMethod <string>("Print", new ParameterItem[] { pi }, MemberAttributes.Public | MemberAttributes.Static, Statements); var cub = new CompileUnitBuilder("Bla"); var typeDecl = cb.GetDeclaration(); cub.AddClass(typeDecl); cub.PublishCode("c:\\Users\\Sytse\\Documents\\GitHubVisualStudio\\Minor_CodeGen\\CodeGen\\test.cs"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new CodeGenStudio()); }
private void ReadDataDele(object obj) { var path = obj.ToString(); var instanceSheetName = "Default"; var commonSheetName = "Common"; var temp = ExcelHelper.GetContentVertical(path, instanceSheetName); var temp1 = ExcelHelper.GetContent(path, commonSheetName); var list1 = new List<ParameterItem>(); foreach (var item in temp1) { var kv = new ParameterItem(); kv.Id = Guid.NewGuid().ToString(); kv.Group = "Variable"; kv.Name = item[0].Value; kv.Value = item[1].Value; list1.Add(kv); } foreach (var item in temp) { var kv = new ParameterItem(); kv.Id = Guid.NewGuid().ToString(); kv.Group = "Variable"; kv.Name = item[0].Value; kv.Value = item[1].Value; list1.Add(kv); } this.ParameterList = list1; ExcelHelper.KillProcess(); this.BeginInvoke(new DeleParaObject(ReadDataAction), list1); base.EndExecute(null); }
private void WriteText(DocWriter writer, AItem item) { string summary = string.Empty; void WriteNodes(IEnumerable <XNode> nodes) { foreach (XNode node in nodes) { switch (node) { case XText text: summary += string.Join(" \n", text.Value.Split('\n')); break; case XElement element: switch (element.Name.LocalName) { case "see": case "seealso": string referenceName = element.GetReferenceName(); summary += _items.TryGetValue(referenceName, out AMemberItem reference) ? (reference is NamespaceItem ? reference.AsLinkWithTarget(_mainName) : reference.AsLink()) : referenceName.Substring(2).AsDotNetApiLink(); break; case "typeparamref": AMemberItem parent = item as AMemberItem ?? item.Parent; GenericItem generic = null; while (parent != null && generic == null) { if (parent is AGenericDocItem genericItem) { generic = Array.Find(genericItem.Generics, i => i.Name == element.GetName()); } parent = parent.Parent; } if (generic == null) { summary += element.GetName(); } else { summary += writer.IsForThis(generic.Parent) ? generic.AsPageLink() : generic.AsLinkWithTarget(); } break; case "paramref": IParameterDocItem parameterItem = (item as IParameterDocItem) ?? (item.Parent as IParameterDocItem); ParameterItem parameter = parameterItem.Parameters.First(i => i.Name == element.GetName()); summary += parameter.AsPageLink(); break; case "c": summary += $"`{element.Value}`"; break; case "code": summary += $"```{element.Value}```\n"; break; case "para": summary += "\n\n"; WriteNodes(element.Nodes()); summary += "\n\n"; break; default: summary += element.ToString(); break; } break; default: throw new Exception($"unhandled node type in summary {node.NodeType}"); } } } WriteNodes(item.Summary.Nodes()); string[] lines = summary.Split('\n'); int startIndex = 0; int firstLine = 0; foreach (string line in lines) { if (!string.IsNullOrWhiteSpace(line)) { startIndex = line.Length - line.TrimStart().Length; break; } ++firstLine; } summary = string.Join(Environment.NewLine, lines.Skip(firstLine).Select(l => l.StartsWith(" ") ? l.Substring(startIndex) : l)); while (summary.EndsWith(Environment.NewLine)) { summary = summary.Substring(0, summary.Length - Environment.NewLine.Length); } writer.WriteLine($"{summary.TrimEnd()}"); }
public ParameterItemProperties(ParameterItem item) : base(item) { _Item = item; }
private void Add(AnimationTreeParameter data) { ParameterItem item = new ParameterItem(this, data); _ParameterList.Items.Add(item); }
private Parameter CreateParameter(ParameterItem p) { return new Parameter(this, p.Name, p.Documentation, new Span(p.Span.Start, p.Span.Length)); }
/// <summary> /// AddFilter /// </summary> /// <typeparam name="TFilter"></typeparam> public void AddFilter <TFilter>() where TFilter : TFilterBase { MethodInfo[] methods = typeof(TFilter) .GetMethods() .Where(x => x.IsPublic) .Where(x => x.GetCustomAttribute <FilterAttribute>() != null) .ToArray(); foreach (MethodInfo method in methods) { ParameterInfo[] parameters = method.GetParameters(); Type[] integerTypes = new Type[] { typeof(byte), typeof(short), typeof(int), typeof(long) }; Type[] floatingNumberTypes = new Type[] { typeof(float), typeof(double), typeof(decimal) }; ParameterItem CreateParameter(ParameterInfo pi, string pattern) { return(new ParameterItem() { Name = pi.Name, Pattern = $@"(?<{pi.Name}>{pattern})" }); } List <ParameterItem> pp = new List <ParameterItem>(); for (int i = 0; i < parameters.Length; i++) { ParameterInfo currentParameter = parameters[i]; if (integerTypes.Any(x => x == currentParameter.ParameterType)) { pp.Add(CreateParameter(currentParameter, @"-?\d+")); } else if (floatingNumberTypes.Any(x => x == currentParameter.ParameterType)) { pp.Add(CreateParameter(currentParameter, @"-?\d+\.\d+")); } else if (currentParameter.ParameterType == typeof(bool)) { pp.Add(CreateParameter(parameters[i], "True|False")); } else if (currentParameter.ParameterType == typeof(string)) { ParameterItem p = CreateParameter(parameters[i], "[^']*"); p.Pattern = $"'{p.Pattern}'"; pp.Add(p); } else if (currentParameter.ParameterType.IsEnum) { //@"[a-z]{1}[a-z0-9]*" string[] enumValues = Enum.GetNames(parameters[i].ParameterType) .Select(x => x.ToLower()) .ToArray(); pp.Add(CreateParameter(parameters[i], string.Join("|", enumValues))); } else { throw new Exception("parameter type is not supported: " + parameters[i].ParameterType.Name); } } StringBuilder builder = new StringBuilder("^"); //function begin builder.Append($@"{method.Name.ToLowerInvariant()}\("); bool optionalParmeterCall = parameters.All(x => (x.DefaultValue is DBNull) == false); if (optionalParmeterCall) { //add optional parameters builder.Append($"(,|{string.Join("|", pp.Select(x => $"({x.Name}={x.Pattern})").ToArray())})*"); } else { //add all parameters builder.Append(string.Join(",", pp.Select(x => x.Pattern).ToArray())); } //function end builder.Append(@"\)$"); IFilterAction filterAction = CreateFilterAction <TFilter>(new Regex(builder.ToString(), RegexOptions.Compiled), method); FilterActions.Add(filterAction); } }
private static void RunScript(string script, string[] args) { lock (psLocker) { powershellHost = new Host(); powershellEngine = System.Management.Automation.PowerShell.Create(); } try { InitialSessionState initalState = InitialSessionState.CreateDefault(); List <ParameterItem> validCmds = new List <ParameterItem>(); //AddValidCommands Commandline cmdLine = new Commandline(args); if (cmdLine["help"] == "true" || cmdLine["?"] == "true") { AssemblyData assInfo = new AssemblyData(System.Reflection.Assembly.GetExecutingAssembly()); StringBuilder outputBuilder = new StringBuilder(); outputBuilder.AppendLine(); outputBuilder.AppendLine(string.Format("{0} v{1} by {2}", assInfo.Product, assInfo.Version, assInfo.Company)); outputBuilder.AppendLine(assInfo.Copyright); outputBuilder.AppendLine(); outputBuilder.AppendLine(" [-Help]"); outputBuilder.AppendLine(" Show help"); foreach (ParameterItem cmdName in validCmds) { if (cmdName.Mandatory) { outputBuilder.AppendLine(string.Format(" -{0} <{1}>", cmdName.Name, cmdName.Type)); } else { outputBuilder.AppendLine(string.Format(" [-{0} <{1}>]", cmdName.Name, cmdName.Type)); } if (!string.IsNullOrWhiteSpace(cmdName.HelpText)) { outputBuilder.AppendLine(string.Format(" {0}", cmdName.HelpText)); } } if (hideCon) { MessageBox.Show(outputBuilder.ToString(), "Help", MessageBoxButtons.OK, MessageBoxIcon.Question); } else { ConsoleHandler.WriteLine(outputBuilder.ToString()); } return; } Dictionary <string, object> cmdLineArgs = new Dictionary <string, object>(); foreach (string arg in cmdLine.GetKeys()) { ParameterItem paramItem = validCmds.FirstOrDefault(x => String.Equals(x.Name, arg, StringComparison.CurrentCultureIgnoreCase)); if (paramItem != null) { try { object realItem; switch (paramItem.Type) { case "sbyte": realItem = sbyte.Parse(cmdLine[arg]); break; case "byte": realItem = byte.Parse(cmdLine[arg]); break; case "short": realItem = short.Parse(cmdLine[arg]); break; case "ushort": realItem = ushort.Parse(cmdLine[arg]); break; case "int": realItem = int.Parse(cmdLine[arg]); break; case "uint": realItem = uint.Parse(cmdLine[arg]); break; case "ulong": realItem = ulong.Parse(cmdLine[arg]); break; case "long": realItem = long.Parse(cmdLine[arg]); break; case "float": realItem = float.Parse(cmdLine[arg]); break; case "double": realItem = double.Parse(cmdLine[arg]); break; case "decimal": realItem = decimal.Parse(cmdLine[arg]); break; case "char": realItem = char.Parse(cmdLine[arg]); break; case "switch": case "bool": realItem = bool.Parse(cmdLine[arg]); break; case "boolean": realItem = Boolean.Parse(cmdLine[arg]); break; default: realItem = cmdLine[arg]; break; } cmdLineArgs.Add(arg, realItem); } catch (Exception) { string errorString = string.Format("Parameter '-{0}' was not in correct format: '{1}'", arg, paramItem.Type); if (hideCon) { MessageBox.Show(errorString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ConsoleHandler.WriteLine(errorString); } return; } } else { StringBuilder outputBuilder = new StringBuilder(); outputBuilder.AppendLine(string.Format("Parameter '-{0}' is not valid. Use '-help' to show valid parameters.", arg)); if (hideCon) { MessageBox.Show(outputBuilder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ConsoleHandler.WriteLine(outputBuilder.ToString()); } return; } } foreach (ParameterItem paramItem in validCmds.Where(x => x.Mandatory == true)) { if (!cmdLineArgs.ContainsKey(paramItem.Name.ToLower())) { StringBuilder outputBuilder = new StringBuilder(); outputBuilder.AppendLine(string.Format("Parameter '-{0}' of type '{1}' is mandatory.", paramItem.Name, paramItem.Type)); if (hideCon) { MessageBox.Show(outputBuilder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ConsoleHandler.WriteLine(outputBuilder.ToString()); } return; } } List <string> modulesToLoad = Common.ProcessManifest(initalState); powershellEngine.Runspace = RunspaceFactory.CreateRunspace(powershellHost, initalState); powershellEngine.Runspace.ApartmentState = System.Threading.ApartmentState.MTA; powershellEngine.Runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(powershellEngine.Runspace); try { runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); } catch { } foreach (string module in modulesToLoad) { try { runSpaceInvoker.Invoke(string.Format("Import-Module {0} -Scope Global", module)); } catch (Exception e) { ConsoleHandler.WriteLine(string.Format("Could import module {0}: {0}", e.Message, module)); } } Pipeline pipeline = powershellEngine.Runspace.CreatePipeline(); Command command = new Command(script, true, true); foreach (KeyValuePair <string, object> cmdLineData in cmdLineArgs) { command.Parameters.Add(cmdLineData.Key, cmdLineData.Value); } pipeline.Commands.Add(command); Collection <PSObject> resultObjects = pipeline.Invoke(); foreach (PSObject resultObject in resultObjects) { ConsoleHandler.WriteLine(resultObject.ToString()); } } catch (Exception e) { ConsoleHandler.WriteLine(string.Format("Internal error: {0}", e.Message)); } finally { lock (psLocker) { powershellEngine.Dispose(); powershellEngine = null; } } }
public ParameterDifinitionEditor(ListItem owner, ParameterDataCollection data) { this._OwnerListItem = owner; this._Data = data; this.RowDefinitions.Add(24, GridUnitType.Pixel); // title this.RowDefinitions.Add(18, GridUnitType.Pixel); // header this.RowDefinitions.Add(1, GridUnitType.Star); // items this.RowDefinitions.Add(20, GridUnitType.Pixel); // buttons Skill.Editor.UI.DropShadowLabel title = new UI.DropShadowLabel() { Text = "Parameter Difinition", Height = 20, Margin = new Thickness(0, 0, 0, 4) }; this.Controls.Add(title); _HeaderBg = new Box() { Row = 1, Style = (GUIStyle)"RL Header" }; this.Controls.Add(_HeaderBg); _Header = new Grid() { Row = 1 }; _Header.ColumnDefinitions.Add(1, GridUnitType.Star); _Header.ColumnDefinitions.Add(2, GridUnitType.Star); _Header.ColumnDefinitions.Add(2, GridUnitType.Star); _Header.Controls.Add(new Label() { Column = 0, Text = "Type" }); _Header.Controls.Add(new Label() { Column = 1, Text = "Name" }); _Header.Controls.Add(new Label() { Column = 2, Text = "Default Value" }); this.Controls.Add(_Header); _LbItems = new Framework.UI.ListBox() { Row = 2 }; _LbItems.DisableFocusable(); _LbItems.BackgroundVisible = true; _LbItems.Background.Style = (GUIStyle)"RL Background"; this.Controls.Add(_LbItems); _PnlButtons = new Grid() { Row = 3 }; _PnlButtons.ColumnDefinitions.Add(1, GridUnitType.Star); _PnlButtons.ColumnDefinitions.Add(20, GridUnitType.Pixel); // btn add _PnlButtons.ColumnDefinitions.Add(20, GridUnitType.Pixel); // btn remove this.Controls.Add(_PnlButtons); _BtnAdd = new Button { Column = 1 }; _PnlButtons.Controls.Add(_BtnAdd); _BtnRemove = new Button() { Column = 2, IsEnabled = false }; _PnlButtons.Controls.Add(_BtnRemove); _LbItems.SelectionChanged += _LbItems_SelectionChanged; _BtnAdd.Click += _BtnAdd_Click; _BtnRemove.Click += _BtnRemove_Click; for (int i = 0; i < _Data.Count; i++) { ParameterItem item = new ParameterItem(_OwnerListItem, _Data[i]); _LbItems.Items.Add(item); } }
static NetParam ToNamedParam(ParameterItem st, NetTypeBundle bundle, int index) { string targetName = ComeUpWithAName(st.NameIsRequired ? st.PublicName : st.PrivateName, bundle.Type, index); return(new NetParam(targetName, bundle)); }
public SLParameter ToParameter(TypeMapper typeMapper, FunctionDeclaration func, SLImportModules modules, ParameterItem p, int index, bool dontChangeInOut, SLGenericTypeDeclarationCollection genericDecl = null, bool remapSelf = false, string remappedSelfName = "") { var pIsGeneric = func.IsTypeSpecGeneric(p) && p.TypeSpec is NamedTypeSpec; var parmTypeEntity = !pIsGeneric?typeMapper.GetEntityForTypeSpec(p.TypeSpec) : null; if (parmTypeEntity == null && !pIsGeneric && p.IsInOut) { throw ErrorHelper.CreateError(ReflectorError.kTypeMapBase + 45, $"In function {func.ToFullyQualifiedName ()}, unknown type parameter type {p.PublicName}:{p.TypeName}."); } var parmKind = p.IsInOut && (pIsGeneric || !parmTypeEntity.IsStructOrEnum) ? SLParameterKind.InOut : SLParameterKind.None; SLType parmType = null; var pTypeSpec = remapSelf ? p.TypeSpec.ReplaceName("Self", remappedSelfName) : p.TypeSpec; if (genericDecl != null) { GatherGenerics(typeMapper, func, modules, pTypeSpec, genericDecl); } if (pIsGeneric) { if (pTypeSpec.ContainsGenericParameters) { var ns = pTypeSpec as NamedTypeSpec; var boundGen = new SLBoundGenericType(ns.Name, pTypeSpec.GenericParameters.Select(genParm => { return(MapType(func, modules, genParm, true)); })); if (parent.MustForcePassByReference(func, ns)) { boundGen = new SLBoundGenericType("UnsafeMutablePointer", boundGen); } parmType = boundGen; } else { var namedType = pTypeSpec as NamedTypeSpec; if (namedType == null) { throw new NotImplementedException("Can only have a named type spec here."); } var depthIndex = func.GetGenericDepthAndIndex(namedType.Name); var gd = func.GetGeneric(depthIndex.Item1, depthIndex.Item2); var genRef = new SLGenericReferenceType(depthIndex.Item1, depthIndex.Item2); parmType = genRef; } } else { parmType = MapType(func, modules, pTypeSpec, false); if (pIsGeneric) { Tuple <int, int> depthIndex = func.GetGenericDepthAndIndex(pTypeSpec); parmType = new SLGenericReferenceType(depthIndex.Item1, depthIndex.Item2); } else if (parent.MustForcePassByReference(func, pTypeSpec) && !dontChangeInOut) { parmType = new SLBoundGenericType(p.IsInOut ? "UnsafeMutablePointer" : "UnsafePointer", parmType); } } if (isForOverride && p.IsVariadic) { // if we get here, then parmType is an SLSimpleType of SwiftArray<someType> // we're going to turn it into "someType ..." var oldParmType = parmType as SLBoundGenericType; parmType = new SLVariadicType(oldParmType.BoundTypes [0]); } var publicName = !p.NameIsRequired ? null : ConjureIdentifier(p.PublicName, index); var privateName = !String.IsNullOrEmpty(p.PrivateName) ? p.PrivateName : null; return(new SLParameter(publicName, ConjureIdentifier(privateName, index), parmType, parmKind)); }
SLParameter ToParameterToCSharpTypes(SLImportModules modules, ParameterItem p, int index) { return(new SLParameter(p.PublicName, p.PrivateName, MapTypeSimplified(modules, p.TypeSpec), p.IsInOut && TypeSpec.IsBuiltInValueType(p.TypeSpec) ? SLParameterKind.InOut : SLParameterKind.None)); }
private static void CreateSample() { List <ParameterItem> paramList = new List <ParameterItem>(); ParameterItem param = new ParameterItem { ShortParameter = "i", LongParameter = "input-file", VariableName = "inputFile", Description = "filename that contains the JSON values to drive the script. command line overrides file", RequiresInputString = true, Default = "", // this needs to be empty because if it is set, the script will try to find the file... RequiredParameter = false, ValueIfSet = "$2" }; paramList.Add(param); param = new ParameterItem { LongParameter = "log-directory", ShortParameter = "l", Description = "directory for the log file. the log file name will be based on the script name", VariableName = "logDirectory", Default = "\"./\"", RequiresInputString = true, RequiredParameter = false, ValueIfSet = "$2" }; paramList.Add(param); param = new ParameterItem() { LongParameter = "create", ShortParameter = "c", VariableName = "create", Description = "creates the resource", RequiresInputString = false, Default = "false", RequiredParameter = false, ValueIfSet = "true" }; param = new ParameterItem() { LongParameter = "verify", ShortParameter = "v", VariableName = "verify", Description = "verifies the script ran correctly", RequiresInputString = false, Default = "false", RequiredParameter = false, ValueIfSet = "true" }; paramList.Add(param); param = new ParameterItem() { LongParameter = "delete", ShortParameter = "d", VariableName = "delete", Description = "deletes whatever the script created", RequiresInputString = false, Default = "false", RequiredParameter = false, ValueIfSet = "true" }; paramList.Add(param); ScriptData model = new ScriptData("test.sh", paramList, true, true, true, "Sample test script", ""); Console.WriteLine(model.ToJson()); }