public Parameter internalGet(string code) { var bxls = myapp.files.ResolveAll("data", "*.bxl", true, null); var parser = new BxlParser(); foreach (string bxl in bxls) { if(bxl.Contains(".bak"))continue; var x = parser.Parse(File.ReadAllText(bxl)); var pxs = x.XPathSelectElements("//paramlib/param"); foreach (XElement px in pxs) { var result = new Parameter(); if (bxl.Contains("/sys/")) { result.Level = "sys"; } else if (bxl.Contains("/usr/")) { result.Level = "usr"; } else if (bxl.Contains("/mod/")) { result.Level = "mod"; } px.applyTo(result); if(!_cache.ContainsKey(result.Code)) { _cache[result.Code] = result; } if(result.Code==code) { return result; } } } return new Parameter {Code = code, Name = code,Level = "usr"}; }
public void GetMethodInfo(MethodKey key, out Parameter[] parameters, out Local[] locals, out ILVariable[] decLocals) { parameters = null; locals = null; decLocals = null; foreach (var textView in MainWindow.Instance.AllTextViews) { if (parameters != null && decLocals != null) break; var cm = textView.CodeMappings; if (cm == null) continue; MemberMapping mapping; if (!cm.TryGetValue(key, out mapping)) continue; var method = mapping.MethodDefinition; if (mapping.LocalVariables != null && method.Body != null) { locals = method.Body.Variables.ToArray(); decLocals = new ILVariable[method.Body.Variables.Count]; foreach (var v in mapping.LocalVariables) { if (v.IsGenerated) continue; if (v.OriginalVariable == null) continue; if ((uint)v.OriginalVariable.Index >= decLocals.Length) continue; decLocals[v.OriginalVariable.Index] = v; } } parameters = method.Parameters.ToArray(); } }
public ContainerGetUrlMethod() { Visibility = Visibility.Private; Name = "GetUrl"; Parameters = new Parameter[] { }; ReturnType = new Type(new Identifier("System", "Uri")); }
private Parameter ExtractActualComParameterObject(Parameter parameter) { var type = parameter.GetType(); var method = type.GetMethod("GetParm", BindingFlags.Instance | BindingFlags.NonPublic); var actualParameter = method.Invoke(parameter, null); return (Parameter) actualParameter; }
Unit[] toUnits(Parameter.Stage stage) { var units = new List<Unit>(); foreach (var enemy in stage.Enemies) { var job = enemy.Job; for(var i=0; i<enemy.Count; ++i) { var unit = new Unit(false, job.Hp, job.Attack, job.Defence, job.Move); units.Add(unit); } } var ps = stage.Formation.Positions; int len = stage.Formation.Positions.Length; for(int i=0; i<units.Count; ++i) { var p = ps[i % len]; units[i].Leader = i < len ? ps[i].Leader : false; units[i].X = p.X; units[i].Y = p.Y; } return units.ToArray (); }
public Method(MethodDefinition method) { Name = method.Name; NameWithTypes = BuildNameWithTypes(method); if (method.IsPublic) Access = "public"; else if (method.IsFamily) Access = "protected"; if(method.ReturnType.FullName != "System.Void") ReturnType = method.ReturnType.ToXdgUrl(); XmlNode doc = Xdg.FindXmlDoc(method); if (doc != null) { Summary = doc.GetElementContent("summary"); Remarks = doc.GetElementContent("remarks"); ReturnDocs = doc.GetElementContent("returns"); } Parameters = new List<Parameter>(); foreach (ParameterDefinition p in method.Parameters) { Parameter param = new Parameter(); param.Name = p.Name; param.Type = p.ParameterType.ToXdgUrl(); if(doc != null) param.Doc = doc.GetElementContent("param[@name=\""+p.Name+"\"]"); Parameters.Add(param); } }
public CheckpointPIDController(Drone drone, float mass, float gravity, AbstractDroneCommand droneCommand, Parameter[] parameters, List<Checkpoint> checkpoints) : base(drone, mass, gravity, droneCommand, parameters) { _targetCheckpoints = checkpoints; _isStarted = false; _rotorsEnabled = false; }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var functionName = binder.Name; try { // convert arguments to Parameter var parameters = new Parameter[args.Length]; for (int i = 0; i < args.Length; i++) { parameters[i] = new Parameter(args[i]); } Function.SetEntRef(_entRef); result = Function.Call(functionName, typeof(object), parameters); return true; } catch (Exception ex) { Log.Error(ex); result = null; return false; } }
private static void BindParameter(FrameworkElement target, Parameter parameter, string elementName, string path, BindingMode bindingMode) { var element = elementName == "$this" ? target : ExtensionMethods.GetNamedElementsInScope(target).FindName(elementName); if (element == null) return; if(string.IsNullOrEmpty(path)) path = ConventionManager.GetElementConvention(element.GetType()).ParameterProperty; var binding = new Binding(path) { Source = element, Mode = bindingMode }; #if SILVERLIGHT var expression = (BindingExpression)BindingOperations.SetBinding(parameter, Parameter.ValueProperty, binding); var field = element.GetType().GetField(path + "Property", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (field == null) return; ConventionManager.ApplySilverlightTriggers(element, (DependencyProperty)field.GetValue(null), x => expression); #else binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; BindingOperations.SetBinding(parameter, Parameter.ValueProperty, binding); #endif }
public void Construct5() { var parameter = new Parameter("param1", 5.0); Assert.AreEqual("param1", parameter.Name); Assert.AreEqual(0, parameter.DispId); Assert.AreEqual("5", parameter.Value); }
public void Construct6() { var parameter = new Parameter("param1", true); Assert.AreEqual("param1", parameter.Name); Assert.AreEqual(0, parameter.DispId); Assert.AreEqual("True", parameter.Value); }
public void SetControl(Parameter par) { NameLabel.InnerText = par.Name; DescriptionLabel.InnerText = par.Description; if (par.Type == "System.String") { TextInput.Visible = true; TextInput.Value = par.Value; } if (par.Type == "System.Integer") { NumInput.Visible = true; NumInput.Value = par.Value; } if (par.Type == "System.Boolean") { CheckInput.Visible = true; if (par.Value == "True") { CheckInput.Checked = true; } else { CheckInput.Checked = false; } } }
public static Schema.KRPC.Services GetServices() { var services = new Schema.KRPC.Services (); foreach (var serviceSignature in Services.Instance.Signatures.Values) { var service = new Schema.KRPC.Service (); service.Name = serviceSignature.Name; foreach (var procedureSignature in serviceSignature.Procedures.Values) { var procedure = new Procedure (); procedure.Name = procedureSignature.Name; if (procedureSignature.HasReturnType) { procedure.HasReturnType = true; procedure.ReturnType = TypeUtils.GetTypeName (procedureSignature.ReturnType); } foreach (var parameterSignature in procedureSignature.Parameters) { var parameter = new Parameter (); parameter.Name = parameterSignature.Name; parameter.Type = TypeUtils.GetTypeName (parameterSignature.Type); if (parameterSignature.HasDefaultArgument) { parameter.HasDefaultArgument = true; parameter.DefaultArgument = parameterSignature.DefaultArgument; } procedure.Parameters.Add (parameter); } foreach (var attribute in procedureSignature.Attributes) { procedure.Attributes.Add (attribute); } if (procedureSignature.Documentation != "") procedure.Documentation = procedureSignature.Documentation; service.Procedures.Add (procedure); } foreach (var clsSignature in serviceSignature.Classes.Values) { var cls = new Class (); cls.Name = clsSignature.Name; if (clsSignature.Documentation != "") cls.Documentation = clsSignature.Documentation; service.Classes.Add (cls); } foreach (var enmSignature in serviceSignature.Enumerations.Values) { var enm = new Enumeration (); enm.Name = enmSignature.Name; if (enmSignature.Documentation != "") enm.Documentation = enmSignature.Documentation; foreach (var enmValueSignature in enmSignature.Values) { var enmValue = new EnumerationValue (); enmValue.Name = enmValueSignature.Name; enmValue.Value = enmValueSignature.Value; if (enmValueSignature.Documentation != "") enmValue.Documentation = enmValueSignature.Documentation; enm.Values.Add (enmValue); } service.Enumerations.Add (enm); } if (serviceSignature.Documentation != "") service.Documentation = serviceSignature.Documentation; services.Services_.Add (service); } return services; }
private void EndBlock() { AddParameter(parameter); parameter = new Parameter(); PullParent(); parserState = ParserState.BeginParameterName; }
public MappedInvocation(NRefactory.ConstructorDeclaration ctor, MethodDefinition baseCtor) { var parameterTypes = new List<Type>(); var ctorType = ctor.GetActualType(); _parameters = ctor.Parameters .Select((p, i) => { return new Parameter(p.Name, p.GetActualType(), i); }) .ToArray(); _parameterDeclarations = ctor.Parameters.ToArray(); _visitor.VisitConstructorDeclaration(ctor, null); _outParameters = new List<Parameter>(); parameterTypes = new List<Type>(); _parameters.ForEach((p, i) => { var type = p.Type; if (_visitor.Contains(p.Name)) { if (!type.IsByRef) { type = type.MakeByRefType(); p = new Parameter(p.Name, type, p.Location); } _outParameters.Add(p); } parameterTypes.Add(type); }); VerifyUniqueness(ctorType, parameterTypes); Parameters = parameterTypes.ToArray(); }
public override bool VisitFunctionDecl(Function function) { if (!VisitDeclaration(function)) return false; if (function.IsReturnIndirect) { var indirectParam = new Parameter() { Kind = ParameterKind.IndirectReturnType, QualifiedType = function.ReturnType, Name = "return", }; function.Parameters.Insert(0, indirectParam); function.ReturnType = new QualifiedType(new BuiltinType( PrimitiveType.Void)); } if (function.HasThisReturn) { // This flag should only be true on methods. var method = (Method) function; var classType = new QualifiedType(new TagType(method.Namespace), new TypeQualifiers {IsConst = true}); function.ReturnType = new QualifiedType(new PointerType(classType)); } // TODO: Handle indirect parameters return true; }
public void Add(Parameter parameter) { if (parameter.Type == Parameter.ParamType.File) file_parameter = parameter; else fields.Add(parameter); }
static void Main(string[] args) { SolverContext context = SolverContext.GetContext(); Model model = context.CreateModel(); // ------------ // Parameters Set city = new Set(Domain.IntegerNonnegative, "city"); Parameter dist = new Parameter(Domain.Real, "dist", city, city); var arcs = from p1 in data from p2 in data select new Arc { City1 = p1.Name, City2 = p2.Name, Distance = p1.Distance(p2) }; dist.SetBinding(arcs, "Distance", "City1", "City2"); model.AddParameters(dist); // ------------ // Decisions Decision assign = new Decision(Domain.IntegerRange(0, 1), "assign", city, city); Decision rank = new Decision(Domain.RealNonnegative, "rank", city); model.AddDecisions(assign, rank); // ------------ // Goal: minimize the length of the tour. Goal goal = model.AddGoal("TourLength", GoalKind.Minimize, Model.Sum(Model.ForEach(city, i => Model.ForEachWhere(city, j => dist[i, j] * assign[i, j], j => i != j)))); // ------------ // Enter and leave each city only once. int N = data.Length; model.AddConstraint("assign1", Model.ForEach(city, i => Model.Sum(Model.ForEachWhere(city, j => assign[i, j], j => i != j)) == 1)); model.AddConstraint("assign2", Model.ForEach(city, j => Model.Sum(Model.ForEachWhere(city, i => assign[i, j], i => i != j)) == 1)); // Forbid subtours (Miller, Tucker, Zemlin - 1960...) model.AddConstraint("no_subtours", Model.ForEach(city, i => Model.ForEachWhere(city, j => rank[i] + 1 <= rank[j] + N * (1 - assign[i, j]), j => Model.And(i != j, i >= 1, j >= 1) ) ) ); Solution solution = context.Solve(); // Retrieve solution information. Console.WriteLine("Cost = {0}", goal.ToDouble()); Console.WriteLine("Tour:"); var tour = from p in assign.GetValues() where (double)p[0] > 0.9 select p[2]; foreach (var i in tour.ToArray()) { Console.Write(i + " -> "); } Console.WriteLine(); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); }
public ParameterConditional(Parameter compared, Parameter compareTo, WarningType warningType, string description = null) { this.compared = compared; this.compareTo = compareTo; this.warningType = warningType; this.description = description; }
protected override void OnLoadFromConfig(ConfigNode node) { base.OnLoadFromConfig(node); parameter = ConfigNodeUtil.ParseValue<Parameter>(node, "parameter"); value = ConfigNodeUtil.ParseValue<float>(node, "value"); }
/// <summary> /// Obtains the type and value of a parameter from an XML Error file. /// </summary> /// <param name="reader">XML Error file.</param> /// <param name="parameter">Parameter to obtain.</param> /// <returns>Parameter.</returns> public static Parameter Deserialize(XmlReader reader, Parameter parameter) { if (reader.IsStartElement(DTD.Error.ErrorParams.TagErrorParam)) { if (parameter == null) { parameter = new Parameter(); } // Read Attributes of Node. parameter.Key = reader.GetAttribute(DTD.Error.ErrorParams.TagKey); switch (reader.GetAttribute(DTD.Error.ErrorParams.TagType)) { case ResponseException.ErrorKey: parameter.Type = ErrorParamType.Key; break; case ResponseException.ErrorLiteral: parameter.Type = ErrorParamType.Literal; break; } if (!reader.IsEmptyElement) { parameter.Text = reader.ReadString(); } else { reader.Skip(); } } return parameter; }
public void CreateWithBooleanTypeAndValue() { const bool newParameterValue = true; var parameter = new Parameter<bool> { Value = newParameterValue }; Assert.AreEqual(newParameterValue, parameter.Value); }
public void DefaultValueForIntType() { var defaultParameterValue = new Parameter<int>().DefaultValue; const int expectedValue = 0; Assert.AreEqual(expectedValue, defaultParameterValue); }
public void CreateWithIntTypeAndNoValue() { var parameter = new Parameter<int>(); const int expectedValue = 0; Assert.AreEqual(expectedValue, parameter.Value); }
/// <summary> /// Creates a FunctionScalarProperty element (potentially within multiple ComplexProperty elements) that /// maps the Property at the bottom of the passed in property chain to the passed in Parameter /// within the passed in ModificationFunction. /// </summary> /// <param name="modificationFunction">ultimate parent for ScalarProperty created by this</param> /// <param name="propertyChain">property to be inserted, preceded by its ComplexProperty parents if appropriate</param> /// <param name="navPropPointingToProperty"> /// Optional - if present indicates the Scalar Property at /// the bottom of the propertyChain was reached via a NavProp (propertyChain will have only 1 Property) /// </param> /// <param name="parameter">The sproc parameter to which we will map</param> internal CreateFunctionScalarPropertyTreeCommand( ModificationFunction modificationFunction, List<Property> propertyChain, NavigationProperty navPropPointingToProperty, Parameter parameter, string version) { CommandValidation.ValidateModificationFunction(modificationFunction); CommandValidation.ValidateParameter(parameter); if (null != navPropPointingToProperty) { CommandValidation.ValidateNavigationProperty(navPropPointingToProperty); } Debug.Assert(propertyChain.Count > 0, "Properties list should contain at least one element"); _modificationFunction = modificationFunction; _propertyChain = propertyChain; _navPropPointingToProperty = navPropPointingToProperty; if (_navPropPointingToProperty != null) { Debug.Assert( propertyChain.Count == 1, "When creating a FunctionScalarProperty via a NavigationProperty propertyChain should have only 1 element, but it has " + propertyChain.Count); } _parameter = parameter; Debug.Assert( string.IsNullOrEmpty(version) || ModelConstants.FunctionScalarPropertyVersionOriginal.Equals(version, StringComparison.Ordinal) || ModelConstants.FunctionScalarPropertyVersionCurrent.Equals(version, StringComparison.Ordinal), "version should be empty or " + ModelConstants.FunctionScalarPropertyVersionOriginal + " or " + ModelConstants.FunctionScalarPropertyVersionCurrent + ". Actual value: " + version); _version = version; }
public SMART_TARGET_CLOSEST_CREATURE() : base(19, "Closest creature") { parameters[0] = new CreatureParameter("CreatureEntry(0any)"); parameters[1] = new Parameter("maxDist"); parameters[2] = new Parameter("dead?"); }
private void AddParameter(Parameter<API> parameter) { ListViewItem item = new ListViewItem(parameter.ToString()); item.Tag = parameter; parametersListView.Items.Add(item); }
private static bool CheckForEnumValue(Parameter parameter, Type desugared) { var enumItem = parameter.DefaultArgument.Declaration as Enumeration.Item; if (enumItem != null) { parameter.DefaultArgument.String = string.Format("{0}{1}{2}.{3}", desugared.IsPrimitiveType() ? "(int) " : string.Empty, string.IsNullOrEmpty(enumItem.Namespace.Namespace.Name) ? string.Empty : enumItem.Namespace.Namespace.Name + ".", enumItem.Namespace.Name, enumItem.Name); return true; } var call = parameter.DefaultArgument.Declaration as Function; if (call != null || parameter.DefaultArgument.Class == StatementClass.BinaryOperator) { string @params = regexFunctionParams.Match(parameter.DefaultArgument.String).Groups[1].Value; if (@params.Contains("::")) parameter.DefaultArgument.String = regexDoubleColon.Replace(@params, desugared + "."); else parameter.DefaultArgument.String = regexName.Replace(@params, desugared + ".$1"); return true; } return false; }
public void CreateWithIntTypeAndValue() { const int newParameterValue = 10; var parameter = new Parameter<int> {Value = newParameterValue}; Assert.AreEqual(newParameterValue, parameter.Value); }
public bool VisitParameterDecl(Parameter parameter) { throw new System.NotImplementedException(); }
protected ClockHandElement(Parameter parameter, Element parent, string name = null) : base(parameter, parent, name) { }
private string CreateCSharpDeclarationString(Parameter parameter) { return($"{parameter.ModelType.Name} {parameter.Name}"); }
internal static void TestAddProperty( string initial, string expected, string name = "P", Accessibility defaultAccessibility = Accessibility.Public, Accessibility setterAccessibility = Accessibility.Public, DeclarationModifiers modifiers = default(DeclarationModifiers), string getStatements = null, string setStatements = null, Type type = null, IPropertySymbol explicitInterfaceSymbol = null, IList <Func <SemanticModel, IParameterSymbol> > parameters = null, bool isIndexer = false, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool compareTokens = true) { // This assumes that tests will not use place holders for get/set statements at the same time if (getStatements != null) { expected = expected.Replace("$$", getStatements); } if (setStatements != null) { expected = expected.Replace("$$", setStatements); } using (var context = new TestContext(initial, expected, compareTokens)) { var typeSymbol = GetTypeSymbol(type)(context.SemanticModel); var getParameterSymbols = GetParameterSymbols(parameters, context); var setParameterSymbols = getParameterSymbols == null ? null : new List <IParameterSymbol>(getParameterSymbols) { Parameter(type, "value")(context.SemanticModel) }; IMethodSymbol getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol( null, defaultAccessibility, new DeclarationModifiers(isAbstract: getStatements == null), typeSymbol, null, "get_" + name, null, getParameterSymbols, statements: context.ParseStatements(getStatements)); IMethodSymbol setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol( null, setterAccessibility, new DeclarationModifiers(isAbstract: setStatements == null), GetTypeSymbol(typeof(void))(context.SemanticModel), null, "set_" + name, null, setParameterSymbols, statements: context.ParseStatements(setStatements)); // If get is provided but set isn't, we don't want an accessor for set if (getStatements != null && setStatements == null) { setAccessor = null; } // If set is provided but get isn't, we don't want an accessor for get if (getStatements == null && setStatements != null) { getAccessor = null; } var property = CodeGenerationSymbolFactory.CreatePropertySymbol( null, defaultAccessibility, modifiers, typeSymbol, explicitInterfaceSymbol, name, getParameterSymbols, getAccessor, setAccessor, isIndexer); context.Result = context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions).Result; } }
public Dictionary <List <AppFunc>, List <TableColumn> > ListFuncTableColumn(string ObjectFolder, string strFileName, ref string MsgLinkUrl) { Dictionary <List <AppFunc>, List <TableColumn> > FuncTableColumn = new Dictionary <List <AppFunc>, List <TableColumn> >(); try { List <AppFunc> list = new List <AppFunc>(); string Path = System.Web.Hosting.HostingEnvironment.MapPath("~/BusinessObjects/" + ObjectFolder + "/" + strFileName + ".xml"); XDocument xdoc = XDocument.Load(Path); try { string strXml = xdoc.Document.ToString(); int Start = strXml.IndexOf("<MsgOpen>") + "<MsgOpen>".Length; int End = strXml.IndexOf("</MsgOpen>"); MsgLinkUrl = strXml.Substring(Start, End - Start); } catch { } var xmlTree = from c in xdoc.Descendants("Function") select c; if (xmlTree.Count() > 0) { foreach (var v in xmlTree) { AppFunc sys = new AppFunc(); sys.Language = v.Attribute("Description").Value; sys.FuncName = v.Attribute("FuncName").Value; // sys.Parameter = v.Attribute("Parameter").Value; sys.Address = v.Attribute("Address").Value; sys.Binding = v.Attribute("Binding").Value; sys.SplitChar = v.Attribute("SplitChar").Value; List <Parameter> ListParam = new List <Parameter>(); var param = v.Descendants("ParaStr").Descendants <XElement>("Para"); if (param.Count() > 0) { foreach (var p in param) { Parameter para = new Parameter(); para.Description = p.Attribute("Description").Value.CvtString(); para.Name = p.Attribute("Name").Value.CvtString(); para.Value = p.Attribute("Value").Value.CvtString(); para.TableName = p.Attribute("TableName").Value.CvtString(); ListParam.Add(para); } } sys.Parameter = ListParam; list.Add(sys); } } List <TableColumn> lists = new List <TableColumn>(); var xmlTrees = from c in xdoc.Descendants("Object").Descendants <XElement>("Attribute") select c; if (xmlTrees.Count() > 0) { foreach (var v in xmlTrees) { TableColumn sys = new TableColumn(); sys.Language = v.Attribute("Description").Value; sys.DataType = v.Attribute("DataType").Value; sys.DataValue = v.Attribute("DataValue").Value; sys.Description = v.Attribute("Description").Value; sys.FieldName = v.Attribute("Name").Value; lists.Add(sys); } } xdoc = null; FuncTableColumn.Add(list, lists); return(FuncTableColumn); } catch (Exception ex) { //ErrorLog.WriteErrorMessage(ex.Message + "|" + DateTime.Now.ToString() + "|" + ex.Source + "|" + "UserDefine.svc方法GetSystemFuncList"); } return(null); }
public static double k_function(Node[] x, Node[] y, Parameter param) { switch (param.kernel_type) { case Parameter.LINEAR: return(dot(x, y)); case Parameter.POLY: return(powi(param.gamma * dot(x, y) + param.coef0, param.degree)); case Parameter.RBF: { double sum = 0; int xlen = x.Length; int ylen = y.Length; int i = 0; int j = 0; while (i < xlen && j < ylen) { if (x[i].index == y[j].index) { double d = x[i++].value - y[j++].value; sum += d * d; } else if (x[i].index > y[j].index) { sum += y[j].value * y[j].value; ++j; } else { sum += x[i].value * x[i].value; ++i; } } while (i < xlen) { sum += x[i].value * x[i].value; ++i; } while (j < ylen) { sum += y[j].value * y[j].value; ++j; } return(System.Math.Exp(-param.gamma * sum)); } case Parameter.SIGMOID: return(System.Math.Tanh(param.gamma * dot(x, y) + param.coef0)); case Parameter.PRECOMPUTED: return(x[(int)(y[0].value)].value); default: return(0); // java } }
/// <summary> /// Displays the graph /// </summary> /// <returns></returns> public void Display() { Util.DontNotify(() => { GraphVisualiser.Reset(); String name = null; // Computes the expected end to display double expectedEndX = 0; Dictionary <Function, Graph> graphs = new Dictionary <Function, Graph>(); foreach (Function function in Functions) { InterpretationContext context = new InterpretationContext(function); if (function.FormalParameters.Count == 1) { Parameter parameter = (Parameter)function.FormalParameters[0]; Graph graph = function.CreateGraph(context, parameter, null); if (graph != null) { expectedEndX = Math.Max(expectedEndX, graph.ExpectedEndX()); graphs.Add(function, graph); } } } double expectedEndY = 0; Dictionary <Function, Surface> surfaces = new Dictionary <Function, Surface>(); foreach (Function function in Functions) { InterpretationContext context = new InterpretationContext(function); if (function.FormalParameters.Count == 2) { Surface surface = function.CreateSurface(context, null); if (surface != null) { expectedEndX = Math.Max(expectedEndX, surface.ExpectedEndX()); expectedEndY = Math.Max(expectedEndY, surface.ExpectedEndY()); surfaces.Add(function, surface); } } } try { int maxX = Int32.Parse(Tb_MaxX.Text); expectedEndX = Math.Min(expectedEndX, maxX); } catch (Exception) { } // Creates the graphs foreach (KeyValuePair <Function, Graph> pair in graphs) { Function function = pair.Key; Graph graph = pair.Value; if (function != null && graph != null) { EfsProfileFunction efsProfileFunction = new EfsProfileFunction(graph); if (function.Name.Contains("Gradient")) { GraphVisualiser.AddGraph(new EfsGradientProfileGraph(GraphVisualiser, efsProfileFunction, function.FullName)); } else { GraphVisualiser.AddGraph(new EfsProfileFunctionGraph(GraphVisualiser, efsProfileFunction, function.FullName)); } if (name == null) { name = function.Name; } } } // Creates the surfaces foreach (KeyValuePair <Function, Surface> pair in surfaces) { Function function = pair.Key; Surface surface = pair.Value; if (surface != null) { EfsSurfaceFunction efsSurfaceFunction = new EfsSurfaceFunction(surface); GraphVisualiser.AddGraph(new EfsSurfaceFunctionGraph(GraphVisualiser, efsSurfaceFunction, function.FullName)); if (name == null) { name = function.Name; } } } Train train = new Train(GraphVisualiser); train.InitializeTrain(TrainPosition.GetDistance(), TrainPosition.GetSpeed(), TrainPosition.GetUnderReadingAmount(), TrainPosition.GetOverReadingAmount()); GraphVisualiser.AddGraph(train); GraphVisualiser.Annotations.Add(train.TrainLineAnnotation); GraphVisualiser.Annotations.Add(train.TrainAnnotation); if (name != null) { try { double val = double.Parse(Tb_MinX.Text); GraphVisualiser.SetMinX(val); } catch (Exception) { } try { double val = double.Parse(Tb_MaxX.Text); GraphVisualiser.SetMaxX(val); } catch (Exception) { } if (Cb_AutoYSize.Checked) { GraphVisualiser.SetMaxY(double.NaN); } else { double height; if (double.TryParse(Tb_MaxY.Text, out height)) { GraphVisualiser.SetMaxY(height); } else { GraphVisualiser.SetMaxY(double.NaN); } } GraphVisualiser.SetMinY2(double.NaN); GraphVisualiser.SetMaxY2(double.NaN); double top, bottom; if (double.TryParse(Tb_MinGrad.Text, out bottom)) { GraphVisualiser.SetMinY2(bottom); } if (double.TryParse(Tb_MaxGrad.Text, out top)) { GraphVisualiser.SetMaxY2(top); } GraphVisualiser.DrawGraphs(expectedEndX); } }); }
public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter) { var config = rawConfig as GuidMacroConfig; if (config == null) { throw new InvalidCastException("Couldn't cast the rawConfig as GuidMacroConfig"); } string guidFormats; if (!string.IsNullOrEmpty(config.Format)) { guidFormats = config.Format !; } else { guidFormats = GuidMacroConfig.DefaultFormats; } Guid g = Guid.NewGuid(); for (int i = 0; i < guidFormats.Length; ++i) { bool isUpperCase = char.IsUpper(guidFormats[i]); string value = g.ToString(guidFormats[i].ToString()); value = isUpperCase ? value.ToUpperInvariant() : value.ToLowerInvariant(); Parameter pLegacy = new Parameter { IsVariable = true, Name = config.VariableName + "-" + guidFormats[i], DataType = config.DataType }; // Not breaking any dependencies on exact param names and on the // case insensitive matching of parameters (https://github.com/dotnet/templating/blob/7e14ef44/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectGenerator.cs#L726) // we need to introduce new parameters - with distinc naming for upper- and lower- casing replacements Parameter pNew = new Parameter { IsVariable = true, Name = config.VariableName + (isUpperCase ? GuidMacroConfig.UpperCaseDenominator : GuidMacroConfig.LowerCaseDenominator) + guidFormats[i], DataType = config.DataType }; vars[pLegacy.Name] = value; vars[pNew.Name] = value; setter(pLegacy, value); setter(pNew, value); } Parameter pd; if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam)) { // If there is an existing parameter with this name, it must be reused so it can be referenced by name // for other processing, for example: if the parameter had value forms defined for creating variants. // When the param already exists, use its definition, but set IsVariable = true for consistency. pd = (Parameter)existingParam; pd.IsVariable = true; } else { pd = new Parameter { IsVariable = true, Name = config.VariableName }; } var defaultFormat = string.IsNullOrEmpty(config.DefaultFormat) ? "D" : config.DefaultFormat !; string defaultValue = char.IsUpper(defaultFormat[0]) ? g.ToString(config.DefaultFormat).ToUpperInvariant() : g.ToString(config.DefaultFormat).ToLowerInvariant(); vars[config.VariableName] = defaultValue; setter(pd, defaultValue); }
public SqlString GetSpatialFilterString(string tableAlias, string geometryColumnName, string primaryKeyColumnName, string tableName, Parameter parameter) { //TODO : Check the implementation for parameter return(new SqlStringBuilder(6) .Add(tableAlias) .Add(".") .Add(geometryColumnName) .Add(".Filter(") .AddParameter() .Add(") = 1") .ToSqlString()); }
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { var svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (svc != null) { var frm = new TemplateTextEditorForm(); string template = ""; string valueToEdit = (value == null ? "" : value.ToString()); if (context.Instance is ReportView) { var view = context.Instance as ReportView; if (context.PropertyDescriptor.Name == "CustomTemplate") { if (string.IsNullOrEmpty(valueToEdit)) { valueToEdit = view.ViewTemplateText; } template = view.Template.Text.Trim(); frm.Text = "Edit custom template"; frm.ObjectForCheckSyntax = view.Report; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "CustomConfiguration") { if (string.IsNullOrEmpty(valueToEdit)) { valueToEdit = view.Template.Configuration; } template = view.Template.Configuration.Trim(); frm.Text = "Edit template configuration"; frm.ObjectForCheckSyntax = view.Template; frm.textBox.ConfigurationManager.Language = "cs"; } } else if (context.Instance is ReportViewPartialTemplate) { var pt = context.Instance as ReportViewPartialTemplate; var templateText = pt.View.Template.GetPartialTemplateText(pt.Name); if (string.IsNullOrEmpty(valueToEdit)) { valueToEdit = templateText; } template = templateText; frm.Text = "Edit custom partial template"; frm.ObjectForCheckSyntax = pt.View.Template.ForReportModel ? (object)pt.View.Model : (object)pt.View; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.Instance is ReportTask) { template = razorTaskTemplate; frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit task script"; frm.textBox.ConfigurationManager.Language = "cs"; List <string> samples = new List <string>(); foreach (var sample in tasksSamples) { samples.Add("@using Seal.Model\r\n@using Seal.Helpers\r\n@using System.Data\r\n@{\r\n\t//" + sample.Item1 + "\r\n\t" + sample.Item2 + "}\r\n|" + sample.Item1); } frm.SetSamples(samples); } else if (context.Instance is ReportOutput) { if (context.PropertyDescriptor.Name == "PreScript") { template = razorPreOutputTemplate; } else if (context.PropertyDescriptor.Name == "PostScript") { template = razorPostOutputTemplate; } frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit output script"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.Instance is Parameter || context.Instance is ParametersEditor) { Parameter parameter = context.Instance is Parameter ? context.Instance as Parameter : ((ParametersEditor)context.Instance).GetParameter(context.PropertyDescriptor.Name); if (parameter != null) { template = parameter.ConfigValue; frm.Text = parameter.DisplayName; frm.textBox.ConfigurationManager.Language = (string.IsNullOrEmpty(parameter.EditorLanguage) ? "" : parameter.EditorLanguage); if (parameter.TextSamples != null) { frm.SetSamples(parameter.TextSamples.ToList()); } } } else if (context.Instance.GetType().ToString() == "SealPdfConverter.PdfConverter") { string language = "cs"; SealPdfConverter converter = SealPdfConverter.Create(""); converter.ConfigureTemplateEditor(frm, context.PropertyDescriptor.Name, ref template, ref language); frm.textBox.ConfigurationManager.Language = language; } else if (context.Instance.GetType().ToString() == "SealExcelConverter.ExcelConverter") { string language = "cs"; SealExcelConverter converter = SealExcelConverter.Create(""); converter.ConfigureTemplateEditor(frm, context.PropertyDescriptor.Name, ref template, ref language); frm.textBox.ConfigurationManager.Language = language; } else if (context.Instance is ViewFolder) { if (context.PropertyDescriptor.Name == "DisplayName") { template = displayNameTemplate; frm.ObjectForCheckSyntax = ((ReportComponent)context.Instance).Report; frm.Text = "Edit display name script"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "InitScript") { template = razorInitScriptTemplate; frm.ObjectForCheckSyntax = ((ReportComponent)context.Instance).Report; frm.Text = "Edit the script executed when the report is initialized"; frm.textBox.ConfigurationManager.Language = "cs"; } } else if (context.Instance is ReportElement) { ReportElement element = context.Instance as ReportElement; if (context.PropertyDescriptor.Name == "CellScript") { frm.Text = "Edit custom script for the cell"; template = razorCellScriptTemplate; List <string> samples = new List <string>(); foreach (var sample in razorCellScriptSamples) { samples.Add("@using Seal.Model\r\n@{\r\n\t//" + sample.Item1 + "\r\n\tResultCell cell=Model;\r\n\tReportElement element = cell.Element;\r\n\tReportModel reportModel = element.Model;\r\n\tReport report = reportModel.Report;\r\n\t" + sample.Item2 + "}\r\n|" + sample.Item1); } frm.SetSamples(samples); frm.ObjectForCheckSyntax = new ResultCell(); frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "SQL") { frm.Text = "Edit custom SQL"; frm.textBox.ConfigurationManager.Language = "sql"; template = element.RawSQLColumn; List <string> samples = new List <string>(); samples.Add(element.RawSQLColumn); if (!string.IsNullOrEmpty(element.SQL) && !samples.Contains(element.SQL)) { samples.Add(element.SQL); } frm.SetSamples(samples); frm.textBox.LineWrapping.Mode = ScintillaNET.LineWrappingMode.Word; } else if (context.PropertyDescriptor.Name == "CellCss") { frm.Text = "Edit custom CSS"; frm.textBox.ConfigurationManager.Language = "css"; List <string> samples = new List <string>(); samples.Add("text-align:right;"); samples.Add("text-align:center;"); samples.Add("text-align:left;"); samples.Add("font-style:italic;"); samples.Add("font-weight:bold;color:red;background-color:yellow;"); samples.Add("color:green;text-align:right;|color:black;|font-weight:bold;color:red;text-align:right;"); samples.Add("white-space: nowrap;"); frm.SetSamples(samples); frm.textBox.LineWrapping.Mode = ScintillaNET.LineWrappingMode.Word; } } else if (context.Instance is MetaColumn) { if (context.PropertyDescriptor.Name == "Name") { frm.Text = "Edit column name"; frm.textBox.ConfigurationManager.Language = "sql"; frm.textBox.LineWrapping.Mode = ScintillaNET.LineWrappingMode.Word; } } else if (context.Instance is SealSecurity) { if (context.PropertyDescriptor.Name == "Script" || context.PropertyDescriptor.Name == "ProviderScript") { template = ((SealSecurity)context.Instance).ProviderScript; frm.ObjectForCheckSyntax = new SecurityUser(null); frm.Text = "Edit security script"; frm.textBox.ConfigurationManager.Language = "cs"; } } else if (context.Instance is MetaTable) { if (context.PropertyDescriptor.Name == "DefinitionScript") { template = razorTableDefinitionScriptTemplate; frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit the script to define the table"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "LoadScript") { template = razorTableLoadScriptTemplate; frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit the default script to load the table"; frm.textBox.ConfigurationManager.Language = "cs"; } } else if (context.Instance is ReportModel) { if (context.PropertyDescriptor.Name == "PreLoadScript") { template = razorModelPreLoadScriptTemplateNoSQL; frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit the script executed before table load"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "FinalScript") { template = razorTableFinalScriptTemplate; frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit the final script executed for the model"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "LoadScript") { if (((ReportModel)context.Instance).Source.IsNoSQL) { frm.Text = "Edit the script executed after table load"; template = razorModelLoadScriptTemplateNoSQL; } else { frm.Text = "Edit the script to load the table"; template = razorModelLoadScriptTemplate; } frm.ObjectForCheckSyntax = context.Instance; frm.textBox.ConfigurationManager.Language = "cs"; } } else if (context.Instance is MetaSource && context.PropertyDescriptor.Name == "InitScript") { template = razorSourceInitScriptTemplate; frm.ObjectForCheckSyntax = context.Instance; frm.Text = "Edit the init script of the source"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.Instance is TasksFolder) { if (context.PropertyDescriptor.Name == "TasksScript") { template = razorTasksTemplate; frm.ObjectForCheckSyntax = new ReportTask(); if (CurrentEntity is Report) { frm.ScriptHeader = ((Report)CurrentEntity).Repository.Configuration.CommonScriptsHeader; frm.ScriptHeader += ((Report)CurrentEntity).Repository.Configuration.TasksScript; frm.ScriptHeader += ((Report)CurrentEntity).CommonScriptsHeader; } frm.Text = "Edit the script that will be added to all task scripts"; frm.textBox.ConfigurationManager.Language = "cs"; } } else if (context.Instance is CommonScript) { template = CommonScript.RazorTemplate; frm.Text = "Edit the script that will be added to all scripts executed for the report."; if (CurrentEntity is SealServerConfiguration) { //common script from configuration frm.ScriptHeader = ((SealServerConfiguration)CurrentEntity).GetCommonScriptsHeader((CommonScript)context.Instance); } if (CurrentEntity is Report) { //common script from report frm.ScriptHeader = ((Report)CurrentEntity).Repository.Configuration.CommonScriptsHeader; frm.ScriptHeader += ((Report)CurrentEntity).GetCommonScriptsHeader((CommonScript)context.Instance); } frm.ObjectForCheckSyntax = CurrentEntity; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.Instance is SealServerConfiguration) { //use report tag to store current config var report = new Report(); report.Tag = context.Instance; if (context.PropertyDescriptor.Name == "InitScript") { template = razorConfigurationInitScriptTemplate; frm.ObjectForCheckSyntax = report; frm.Text = "Edit the root init script"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "TasksScript") { template = razorTasksTemplate; frm.ScriptHeader = ((SealServerConfiguration)context.Instance).CommonScriptsHeader; frm.ObjectForCheckSyntax = new ReportTask(); frm.Text = "Edit the script that will be added to all task scripts"; frm.textBox.ConfigurationManager.Language = "cs"; } else if (context.PropertyDescriptor.Name == "ReportCreationScript") { template = razorConfigurationReportCreationScriptTemplate; frm.ObjectForCheckSyntax = report; frm.Text = "Edit the script executed when a new report is created"; frm.textBox.ConfigurationManager.Language = "cs"; } } if (!string.IsNullOrEmpty(template) && string.IsNullOrWhiteSpace(valueToEdit) && !context.PropertyDescriptor.IsReadOnly) { valueToEdit = template; } //Reset button if (!string.IsNullOrEmpty(template) && !context.PropertyDescriptor.IsReadOnly) { frm.SetResetText(template); } frm.textBox.Text = valueToEdit.ToString(); if (context.PropertyDescriptor.IsReadOnly) { frm.textBox.IsReadOnly = true; frm.okToolStripButton.Visible = false; frm.cancelToolStripButton.Text = "Close"; } frm.checkSyntaxToolStripButton.Visible = (frm.ObjectForCheckSyntax != null); if (svc.ShowDialog(frm) == DialogResult.OK) { if (string.IsNullOrEmpty(template)) { template = ""; } if (frm.textBox.Text.Trim() != template.Trim() || string.IsNullOrEmpty(template)) { value = frm.textBox.Text; } else if (frm.textBox.Text.Trim() == template.Trim() && !string.IsNullOrEmpty(template)) { value = ""; } } } return(value); }
public CaloriesElement(Parameter parameter, Element parent, string name = null) : base(parameter, parent, name) { }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; if (doc == null) { return(Result.Failed); } //Fetch a RebarBarType element to be used in Rebar creation. FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(RebarBarType)); if (fec.GetElementCount() <= 0) { return(Result.Failed); } RebarBarType barType = fec.FirstElement() as RebarBarType; Rebar rebar = null; CurveElement curveElem = null; using (Transaction tran = new Transaction(doc, "Create Rebar")) { Element host = null; Selection sel = commandData.Application.ActiveUIDocument.Selection; try { //Select structural Host. Reference hostRef = sel.PickObject(ObjectType.Element, "Select Host"); host = doc.GetElement(hostRef.ElementId); if (host == null) { return(Result.Failed); } } catch (Exception e) { message = e.Message; return(Result.Failed); } try { //Select curve element Reference lineRef = sel.PickObject(ObjectType.Element, "Select Model curve"); curveElem = doc.GetElement(lineRef.ElementId) as CurveElement; } catch (Exception) { curveElem = null; } tran.Start(); //create Rebar Free Form by specifying the GUID defining the custom external server // the Rebar element returned needs to receive constraints, // so that regeneration can call the custom geometry calculations and create the bars rebar = Rebar.CreateFreeForm(doc, RebarUpdateServer.SampleGuid, barType, host); // Get all bar handles to set constraints to them, so that the bar can generate it's geometry RebarConstraintsManager rManager = rebar.GetRebarConstraintsManager(); IList <RebarConstrainedHandle> handles = rManager.GetAllHandles(); // if bar has no handles then the server can't generate rebar geometry if (handles.Count <= 0) { tran.RollBack(); return(Result.Failed); } // iterate through the rebar handles and prompt for face selection for each of them, to get user input foreach (RebarConstrainedHandle handle in handles) { if (handle.GetHandleType() == RebarHandleType.StartOfBar || handle.GetHandleType() == RebarHandleType.EndOfBar) { continue;// Start handle and end handle will receive constraints from the custom external server execution } try { Reference reference = sel.PickObject(ObjectType.Face, "Select face for " + handle.GetHandleName()); if (reference == null) { continue; } // create constraint using the picked faces and set it to the associated handle List <Reference> refs = new List <Reference>(); refs.Add(reference); RebarConstraint constraint = RebarConstraint.Create(handle, refs, true, 0.0); rManager.SetPreferredConstraintForHandle(handle, constraint); } catch (Exception e) { message = e.Message; tran.RollBack(); return(Result.Cancelled); } } try { //here we add a value to the shared parameter and add it to the regeneration dependencies Parameter newSharedParam = rebar.LookupParameter(AddSharedParams.m_paramName); Parameter newSharedParam2 = rebar.LookupParameter(AddSharedParams.m_CurveIdName); newSharedParam.Set(0); newSharedParam2.Set(curveElem == null ? -1 : curveElem.Id.IntegerValue); RebarFreeFormAccessor accesRebar = rebar.GetFreeFormAccessor(); accesRebar.AddUpdatingSharedParameter(newSharedParam.Id); accesRebar.AddUpdatingSharedParameter(newSharedParam2.Id); } catch (Exception ex) { message = ex.Message; tran.RollBack(); return(Result.Cancelled); } tran.Commit(); return(Result.Succeeded); } } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
private bool IsApplicable(Parameter x) { return((x.Count?.IsStatic ?? false) && x.Type.IndirectionLevels == 1 && !x.Type.IsVoidPointer()); }
public override int GetHashCode() { unchecked { return(((Definition != null ? Definition.Id.GetHashCode() : 0) * 397) ^ (Parameter != null ? Parameter.GetHashCode() : 0)); } }
public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup);
/// <summary> /// Special name format as required by COBie v2.4 /// </summary> /// <param name="element">the Element</param> /// <returns>the name</returns> static private string GetCOBieDesiredName(Element element) { if (element == null) { return(""); } Parameter instanceMarkParam = element.get_Parameter(BuiltInParameter.ALL_MODEL_MARK); // if NULL, try DOOR_NUMBER which also has the same parameter name "Mark" if (instanceMarkParam == null) { instanceMarkParam = element.get_Parameter(BuiltInParameter.DOOR_NUMBER); } ElementType elementType = null; if (element is ElementType) { elementType = element as ElementType; } else { elementType = element.Document.GetElement(element.GetTypeId()) as ElementType; } Parameter typeMarkParam = null; if (elementType != null) { typeMarkParam = elementType.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_MARK); // if NULL, try WINDOW_TYPE_ID which also has the same parameter name "Mark" if (typeMarkParam == null) { typeMarkParam = elementType.get_Parameter(BuiltInParameter.WINDOW_TYPE_ID); } } string typeMarkValue = (typeMarkParam != null) ? typeMarkParam.AsString() : null; string instanceMarkValue = (instanceMarkParam != null) ? instanceMarkParam.AsString() : null; string fullName = null; if (string.IsNullOrWhiteSpace(typeMarkValue)) { fullName = string.IsNullOrWhiteSpace(instanceMarkValue) ? "" : instanceMarkValue; } else if (string.IsNullOrWhiteSpace(instanceMarkValue)) { fullName = typeMarkValue; } else { fullName = typeMarkValue + "-" + instanceMarkValue; } Tuple <ElementId, int> tupNameDupl; if (!m_NameIncrNumberDict.TryGetValue(fullName, out tupNameDupl)) { m_NameIncrNumberDict.Add(fullName, new Tuple <ElementId, int>(element.Id, 1)); } else { // Found the same name used before, if not the same ElementId than the previously processed, add an incremental number to name if (!element.Id.Equals(tupNameDupl.Item1)) { Tuple <ElementId, int> tup = new Tuple <ElementId, int>(element.Id, tupNameDupl.Item2 + 1); m_NameIncrNumberDict[fullName] = tup; fullName = fullName + " (" + tup.Item2.ToString() + ")"; } } return(fullName); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; Autodesk.Revit.Creation.Application createApp = app.Application.Create; Autodesk.Revit.Creation.Document createDoc = doc.Create; // Determine the wall endpoints: double length = 5 * MeterToFeet; XYZ [] pts = new XYZ[2]; pts[0] = XYZ.Zero; pts[1] = new XYZ(length, 0, 0); // Determine the levels where // the wall will be located: Level levelBottom = null; Level levelTop = null; if (!GetBottomAndTopLevels(doc, ref levelBottom, ref levelTop)) { message = "Unable to determine " + "wall bottom and top levels"; return(Result.Failed); } using (Transaction t = new Transaction(doc)) { t.Start("Create Wall, Door and Tag"); // Create a wall: BuiltInParameter topLevelParam = BuiltInParameter.WALL_HEIGHT_TYPE; ElementId topLevelId = levelTop.Id; //Line line = createApp.NewLineBound( pts[0], pts[1] ); // 2013 Line line = Line.CreateBound(pts[0], pts[1]); // 2014 //Wall wall = createDoc.NewWall( // 2012 // line, levelBottom, false ); Wall wall = Wall.Create( // 2013 doc, line, levelBottom.Id, false); Parameter param = wall.get_Parameter( topLevelParam); param.Set(topLevelId); // Determine wall thickness for tag // offset and profile growth: //double wallThickness = wall.WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011 double wallThickness = wall.WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012 // Add door to wall; // note that the NewFamilyInstance method // does not automatically add a door tag, // like the UI command does: FamilySymbol doorSymbol = GetFirstFamilySymbol( doc, BuiltInCategory.OST_Doors); if (null == doorSymbol) { message = "No door symbol found."; return(Result.Failed); } XYZ midpoint = Util.Midpoint(pts[0], pts[1]); FamilyInstance door = createDoc .NewFamilyInstance( midpoint, doorSymbol, wall, levelBottom, StructuralType.NonStructural); // Create door tag: View view = doc.ActiveView; double tagOffset = 3 * wallThickness; midpoint += tagOffset * XYZ.BasisY; // 2011: TagOrientation.TAG_HORIZONTAL //IndependentTag tag = createDoc.NewTag( // view, door, false, TagMode.TM_ADDBY_CATEGORY, // TagOrientation.Horizontal, midpoint ); // 2012 IndependentTag tag = IndependentTag.Create( doc, view.Id, new Reference(door), false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midpoint); // 2018 // Create and assign new door tag type: FamilySymbol doorTagType = GetFirstFamilySymbol( doc, BuiltInCategory.OST_DoorTags); doorTagType = doorTagType.Duplicate( "New door tag type") as FamilySymbol; tag.ChangeTypeId(doorTagType.Id); // Demonstrate changing name of // family instance and family symbol: door.Name = door.Name + " modified"; door.Symbol.Name = door.Symbol.Name + " modified"; t.Commit(); } return(Result.Succeeded); }
public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter);
private static StrongGridJsonObject ConvertToJson(Parameter <string> title, Parameter <long?> senderId, Parameter <string> subject, Parameter <string> htmlContent, Parameter <string> textContent, Parameter <IEnumerable <long> > listIds, Parameter <IEnumerable <long> > segmentIds, Parameter <IEnumerable <string> > categories, Parameter <long?> suppressionGroupId, Parameter <string> customUnsubscribeUrl, Parameter <string> ipPool, Parameter <EditorType?> editor) { var result = new StrongGridJsonObject(); result.AddProperty("title", title); result.AddProperty("subject", subject); result.AddProperty("sender_id", senderId); result.AddProperty("html_content", htmlContent); result.AddProperty("plain_content", textContent); result.AddProperty("list_ids", listIds); result.AddProperty("segment_ids", segmentIds); result.AddProperty("categories", categories); result.AddProperty("suppression_group_id", suppressionGroupId); result.AddProperty("custom_unsubscribe_url", customUnsubscribeUrl); result.AddProperty("ip_pool", ipPool); result.AddProperty("editor", editor); return(result); }
public Grouping(ProjectionExpression projectionExpression, TranslatedQuery translatedQuery, Parameter <Tuple> parameter, Tuple tuple, TKey key, ItemMaterializationContext context) : base(projectionExpression, translatedQuery, parameter, tuple, context) { Key = key; }
public override void CLIMarshalToNative(MarshalContext ctx) { var templateType = Type as TemplateSpecializationType; var type = templateType.Arguments[0].Type; var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType(); var managedType = isPointerToPrimitive ? new CILType(typeof(System.IntPtr)) : type.Type; var entryString = (ctx.Parameter != null) ? ctx.Parameter.Name : ctx.ArgName; var tmpVarName = "_tmp" + entryString; var cppTypePrinter = new CppTypePrinter(ctx.Driver.TypeDatabase); var nativeType = type.Type.Visit(cppTypePrinter); ctx.SupportBefore.WriteLine("auto {0} = std::vector<{1}>();", tmpVarName, nativeType); ctx.SupportBefore.WriteLine("for each({0} _element in {1})", managedType, entryString); ctx.SupportBefore.WriteStartBraceIndent(); { var param = new Parameter { Name = "_element", QualifiedType = type }; var elementCtx = new MarshalContext(ctx.Driver) { Parameter = param, ArgName = param.Name, }; var marshal = new CLIMarshalManagedToNativePrinter(elementCtx); type.Type.Visit(marshal); if (!string.IsNullOrWhiteSpace(marshal.Context.SupportBefore)) { ctx.SupportBefore.Write(marshal.Context.SupportBefore); } if (isPointerToPrimitive) { ctx.SupportBefore.WriteLine("auto _marshalElement = {0}.ToPointer();", marshal.Context.Return); } else { ctx.SupportBefore.WriteLine("auto _marshalElement = {0};", marshal.Context.Return); } ctx.SupportBefore.WriteLine("{0}.push_back(_marshalElement);", tmpVarName); } ctx.SupportBefore.WriteCloseBraceIndent(); ctx.Return.Write(tmpVarName); }
public TestBinder() { ruleFilesFolder = Parameter.GetString("unittest.ruleml.inputfolder") + "/"; }
static Action AnalyzeActionMethod( Compilation compilation, SemanticModel semanticModel, MethodDeclarationSyntax actionMethodDeclaration, Dictionary <string, Compilation> referencedSymbols) { // Get some symbols by full name. var httpGetSymbol = compilation.GetTypeByMetadataName("System.Web.Http.HttpGetAttribute"); var httpPostSymbol = compilation.GetTypeByMetadataName("System.Web.Http.HttpPostAttribute"); var httpPutSymbol = compilation.GetTypeByMetadataName("System.Web.Http.HttpPutAttribute"); var httpDeleteSymbol = compilation.GetTypeByMetadataName("System.Web.Http.HttpDeleteAttribute"); var routeSymbol = compilation.GetTypeByMetadataName("System.Web.Http.RouteAttribute"); var fromBodySymbol = compilation.GetTypeByMetadataName("System.Web.Http.FromBodyAttribute"); var fromUriSymbol = compilation.GetTypeByMetadataName("System.Web.Http.FromUriAttribute"); var methodSymbol = semanticModel.GetDeclaredSymbol(actionMethodDeclaration); var action = new Action { DocumentationCommentId = methodSymbol.GetDocumentationCommentId(), Name = methodSymbol.Name, BodyParameters = new List <Parameter>(), QueryParameters = new List <Parameter>(), RouteParameters = new List <Parameter>(), Examples = new List <Example>(), Results = new List <Result>() }; // Go through the method's XML comments. var methodCommentsXml = methodSymbol.GetDocumentationCommentXml(); var parameterNotes = new Dictionary <string, XElement>(); if (!string.IsNullOrWhiteSpace(methodCommentsXml)) { var methodCommentsRoot = XElement.Parse(methodCommentsXml); var summary = methodCommentsRoot.Element("summary"); if (summary != null) { foreach (var cref in summary.GetCrefs()) { if (!referencedSymbols.ContainsKey(cref)) { referencedSymbols.Add(cref, compilation); } } action.Summary = summary.ToMarkup(); } var remarks = methodCommentsRoot.Element("remarks"); if (remarks != null) { foreach (var cref in remarks.GetCrefs()) { if (!referencedSymbols.ContainsKey(cref)) { referencedSymbols.Add(cref, compilation); } } action.Remarks = remarks.ToMarkup(); } var returns = methodCommentsRoot.Element("returns"); if (returns != null) { foreach (var cref in returns.GetCrefs()) { if (!referencedSymbols.ContainsKey(cref)) { referencedSymbols.Add(cref, compilation); } } action.Returns = returns.ToMarkup(); } foreach (var example in methodCommentsRoot.Elements("example")) { action.Examples.Add(new Example { Label = example.Attribute("label").Value, Content = string .Concat(example.Nodes()) .NormalizeCodeIndentation() }); } parameterNotes = methodCommentsRoot .Elements("param") .ToDictionary( p => p.Attribute("name").Value, p => p); } var methodName = actionMethodDeclaration.Identifier.ValueText; var routeKeys = Enumerable.Empty <string>(); // Go through the method's attributes. foreach (var attributeList in actionMethodDeclaration.AttributeLists) { foreach (var attribute in attributeList.Attributes) { // For each attribute, try to pull a recognized value. var attributeTypeInfo = semanticModel.GetTypeInfo(attribute); if (attributeTypeInfo.Type.MetadataName == httpGetSymbol.MetadataName) { action.Method = "GET"; } else if (attributeTypeInfo.Type.MetadataName == httpPostSymbol.MetadataName) { action.Method = "POST"; } else if (attributeTypeInfo.Type.MetadataName == httpPutSymbol.MetadataName) { action.Method = "PUT"; } else if (attributeTypeInfo.Type.MetadataName == httpDeleteSymbol.MetadataName) { action.Method = "DELETE"; } else if (attributeTypeInfo.Type.MetadataName == routeSymbol.MetadataName) { var routeArgument = attribute .ArgumentList .Arguments .Single() .Expression as LiteralExpressionSyntax; action.Route = routeArgument.Token.ValueText; routeKeys = Regex .Matches(action.Route, "(?<={)[^}]+(?=})") .Cast <Match>() .Select(m => m.Value) .ToList(); } } } // Go through parameters foreach (var parameter in actionMethodDeclaration.ParameterList.Parameters) { var predefinedType = parameter.Type as PredefinedTypeSyntax; //var typeName = predefinedType != null ? // predefinedType.Keyword.ValueText : // (parameter.Type as SimpleNameSyntax).Identifier.ValueText; var typeInfo = semanticModel.GetTypeInfo(parameter.Type); var documentCommentId = typeInfo.Type.GetDocumentationCommentId(); if (!string.IsNullOrWhiteSpace(documentCommentId) && !referencedSymbols.ContainsKey(documentCommentId)) { referencedSymbols.Add(documentCommentId, compilation); } var parameterType = semanticModel.GetTypeInfo(parameter.Type); var parameterName = parameter.Identifier.ValueText; var fromBody = false; var fromUri = false; foreach (var attributeList in parameter.AttributeLists) { foreach (var attribute in attributeList.Attributes) { var attributeTypeInfo = semanticModel.GetTypeInfo(attribute); if (attributeTypeInfo.Type.MetadataName == fromBodySymbol.MetadataName) { fromBody = true; } else if (attributeTypeInfo.Type.MetadataName == fromUriSymbol.MetadataName) { fromUri = true; } } } var outParameter = new Parameter { Key = parameterName, TypeName = typeInfo.Type.ToTypeDisplayName(), TypeDocumentCommentId = typeInfo.Type.GetDocumentationCommentId(), Optional = false, // TODO: not this Notes = parameterNotes.ContainsKey(parameterName) ? parameterNotes[parameterName].ToMarkup() : null }; if (routeKeys.Contains(parameterName)) { action.RouteParameters.Add(outParameter); } else if (fromUri || parameterType.Type.IsValueType) { action.QueryParameters.Add(outParameter); } else if (fromBody || !parameterType.Type.IsValueType) { action.BodyParameters.Add(outParameter); } } var returnStatements = actionMethodDeclaration .DescendantNodes() .OfType <ReturnStatementSyntax>() .ToList(); foreach (var returnStatement in returnStatements) { var resultMethodInvocation = returnStatement .DescendantNodes() .OfType <InvocationExpressionSyntax>() .First(); var invokedMethodSymbol = semanticModel .GetSymbolInfo(resultMethodInvocation.Expression) .Symbol as IMethodSymbol; var argumentSyntax = resultMethodInvocation .ArgumentList .Arguments .SingleOrDefault(); var result = new Result { Kind = invokedMethodSymbol.Name }; if (argumentSyntax != null) { var l = argumentSyntax.DescendantNodes().First(); var literalExpression = l as LiteralExpressionSyntax; if (literalExpression != null) { result.ArgumentText = ScrubArgumentText(literalExpression.Token.ValueText); } var argumentSymbol = semanticModel.GetSymbolInfo(argumentSyntax); var argumentTypeInfo = semanticModel.GetTypeInfo(argumentSyntax.Expression); var typeName = argumentTypeInfo.Type.Name; result.ArgumentType = argumentTypeInfo.Type.ToDisplayString(); } action.Results.Add(result); } return(action); }
/// <summary cref="IBackendCodeGenerator.GenerateCode(Parameter)"/> public void GenerateCode(Parameter parameter) { // Parameters are already assigned to variables }
public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
/// <summary> /// 判断参数是否为输出型参数。 /// </summary> /// <param name="parameter">存储参数。</param> /// <returns></returns> public static bool IsOutput(this Parameter parameter) { return(parameter.Direction != ParameterDirection.Input); }
public void AddParameter(Parameter parameter) { contents[parameter.GetName()] = parameter; }
public ExtractMethodResult GetExtractionResult() { bool isStaticMethod = false, isClassMethod = false; var parameters = new List <Parameter>(); NameExpression selfParam = null; if (_targetScope is ClassDefinition && _scopes[_scopes.Count - 1] is FunctionDefinition fromScope) { foreach (var name in (fromScope?.Decorators?.Decorators).MaybeEnumerate().ExcludeDefault().OfType <NameExpression>()) { if (name.Name == "staticmethod") { isStaticMethod = true; } else if (name.Name == "classmethod") { isClassMethod = true; } } if (!isStaticMethod) { if (fromScope.Parameters.Length > 0) { selfParam = fromScope.Parameters[0].NameExpression; parameters.Add(new Parameter(selfParam, ParameterKind.Normal)); } } } foreach (var param in _parameters) { var paramName = new NameExpression(param); if (parameters.Count > 0) { paramName.AddPreceedingWhiteSpace(_ast, " "); } var newParam = new Parameter(paramName, ParameterKind.Normal); parameters.Add(newParam); } // include any non-closed over parameters as well... foreach (var input in _inputVars) { var variableScope = input.Scope; var parentScope = _targetScope; // are these variables a child of the target scope so we can close over them? while (parentScope != null && parentScope != variableScope) { parentScope = parentScope.Parent; } if (parentScope == null && input.Name != selfParam?.Name) { // we can either close over or pass these in as parameters, add them to the list var paramName = new NameExpression(input.Name); if (parameters.Count > 0) { paramName.AddPreceedingWhiteSpace(_ast, " "); } var newParam = new Parameter(paramName, ParameterKind.Normal); parameters.Add(newParam); } } var body = _target.GetBody(); var isCoroutine = IsCoroutine(body); // reset leading indentation to single newline + indentation, this // strips out any proceeding comments which we don't extract var leading = _newline + _target.IndentationLevel; body.SetLeadingWhiteSpace(_ast, leading); if (_outputVars.Count > 0) { // need to add a return statement Expression retValue; Expression[] names = new Expression[_outputVars.Count]; int outputIndex = 0; foreach (var name in _outputVars) { var nameExpr = new NameExpression(name.Name); nameExpr.AddPreceedingWhiteSpace(_ast, " "); names[outputIndex++] = nameExpr; } var tuple = new TupleExpression(false, names); tuple.RoundTripHasNoParenthesis(_ast); retValue = tuple; var retStmt = new ReturnStatement(retValue); retStmt.SetLeadingWhiteSpace(_ast, leading); body = new SuiteStatement( new Statement[] { body, retStmt } ); } else { // we need a SuiteStatement to give us our colon body = new SuiteStatement(new Statement[] { body }); } DecoratorStatement decorators = null; if (isStaticMethod) { decorators = new DecoratorStatement(new[] { new NameExpression("staticmethod") }); } else if (isClassMethod) { decorators = new DecoratorStatement(new[] { new NameExpression("classmethod") }); } var res = new FunctionDefinition(new NameExpression(_name), parameters.ToArray(), body, decorators); res.IsCoroutine = isCoroutine; StringBuilder newCall = new StringBuilder(); newCall.Append(_target.IndentationLevel); var method = res.ToCodeString(_ast); // fix up indentation... for (int curScope = 0; curScope < _scopes.Count; curScope++) { if (_scopes[curScope] == _targetScope) { // this is our target indentation level. var indentationLevel = _scopes[curScope].Body.GetIndentationLevel(_ast); var lines = method.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); int minWhiteSpace = Int32.MaxValue; for (int curLine = decorators == null ? 1 : 2; curLine < lines.Length; curLine++) { var line = lines[curLine]; for (int i = 0; i < line.Length; i++) { if (!Char.IsWhiteSpace(line[i])) { minWhiteSpace = Math.Min(minWhiteSpace, i); break; } } } StringBuilder newLines = new StringBuilder(); newLines.Append(indentationLevel); newLines.Append(lines[0]); if (decorators != null) { newLines.Append(_newline); newLines.Append(indentationLevel); newLines.Append(lines[1]); } // don't include a bunch of blank lines... int endLine = lines.Length - 1; for (; endLine >= 0 && String.IsNullOrWhiteSpace(lines[endLine]); endLine--) { } newLines.Append(_newline); for (int curLine = decorators == null ? 1 : 2; curLine <= endLine; curLine++) { var line = lines[curLine]; newLines.Append(indentationLevel); if (_insertTabs) { newLines.Append('\t'); } else { newLines.Append(' ', _indentSize); } if (line.Length > minWhiteSpace) { newLines.Append(line, minWhiteSpace, line.Length - minWhiteSpace); } newLines.Append(_newline); } newLines.Append(_newline); method = newLines.ToString(); break; } } string comma; if (_outputVars.Count > 0) { comma = ""; foreach (var outputVar in _outputVars) { newCall.Append(comma); newCall.Append(outputVar.Name); comma = ", "; } newCall.Append(" = "); } else if (_target.ContainsReturn) { newCall.Append("return "); } if (isCoroutine) { newCall.Append("await "); } if (_targetScope is ClassDefinition && _scopes[_scopes.Count - 1] is FunctionDefinition fromScope2) { if (isStaticMethod) { newCall.Append(_targetScope.Name); newCall.Append('.'); } else if (fromScope2 != null && fromScope2.Parameters.Length > 0) { newCall.Append(fromScope2.Parameters[0].Name); newCall.Append('.'); } } newCall.Append(_name); newCall.Append('('); comma = ""; foreach (var param in parameters) { if (param.Name != selfParam?.Name) { newCall.Append(comma); newCall.Append(param.Name); comma = ", "; } } newCall.Append(')'); return(new ExtractMethodResult( method, newCall.ToString() )); }
/// <summary> /// 操作参数节点 /// </summary> /// <param name="node">短路径节点</param> /// <param name="operationType">操作类型</param> /// <param name="value">数据</param> internal OperationReturnValue(ShortPath.Node node, OperationParameter.OperationType operationType, bool value) : base(node, operationType) { Parameter.Set(value); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Debug.Listeners.Clear(); Debug.Listeners.Add(new RbsLogger.Logger("Worksets")); Document doc = commandData.Application.ActiveUIDocument.Document; if (!doc.IsWorkshared) { message = "Файл не является файлом совместной работы"; Debug.WriteLine("File os not workshared document"); return(Result.Failed);; } //считываю список рабочих наборов string dllPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string dllFolder = System.IO.Path.GetDirectoryName(dllPath); string folder = System.IO.Path.Combine(dllPath, "RevitWorksets_data"); Debug.WriteLine("Default folder for xmls: " + folder); System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); dialog.InitialDirectory = folder; dialog.Multiselect = false; dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } string xmlFilePath = dialog.FileName; Debug.WriteLine("Xml path: " + xmlFilePath); InfosStorage storage = new InfosStorage(); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(InfosStorage)); using (StreamReader r = new StreamReader(xmlFilePath)) { storage = (InfosStorage)serializer.Deserialize(r); } if (storage == null) { string errormsg = "Unable to deserialize: " + xmlFilePath.Replace("\\", " \\"); Debug.WriteLine(errormsg); throw new Exception(errormsg); } Debug.WriteLine("Deserialize success"); using (Transaction t = new Transaction(doc)) { t.Start("Создание рабочих наборов"); Debug.WriteLine("Start worksets by category"); foreach (WorksetByCategory wb in storage.worksetsByCategory) { Debug.WriteLine("Current workset: " + wb.WorksetName); Workset wset = wb.GetWorkset(doc); List <BuiltInCategory> cats = wb.revitCategories; if (cats == null) { continue; } if (cats.Count == 0) { continue; } foreach (BuiltInCategory bic in cats) { List <Element> elems = new FilteredElementCollector(doc) .OfCategory(bic) .WhereElementIsNotElementType() .ToElements() .ToList(); foreach (Element elem in elems) { WorksetBy.SetWorkset(elem, wset); } } } Debug.WriteLine("Start worksets by family names"); List <FamilyInstance> famIns = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfClass(typeof(FamilyInstance)) .Cast <FamilyInstance>() .ToList(); Debug.WriteLine("Family instances found: " + famIns.Count); foreach (WorksetByFamily wb in storage.worksetsByFamily) { Debug.WriteLine("Current workset:" + wb.WorksetName); Workset wset = wb.GetWorkset(doc); List <string> families = wb.FamilyNames; if (families == null) { continue; } if (families.Count == 0) { continue; } foreach (string familyName in families) { List <FamilyInstance> curFamIns = famIns .Where(f => f.Symbol.FamilyName.StartsWith(familyName)) .ToList(); foreach (FamilyInstance fi in curFamIns) { WorksetBy.SetWorkset(fi, wset); } } } Debug.WriteLine("Start worksets by type names"); List <Element> allElems = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .Cast <Element>() .ToList(); Debug.WriteLine("Elements found: " + allElems.Count); foreach (WorksetByType wb in storage.worksetsByType) { Debug.WriteLine("Current workset:" + wb.WorksetName); Workset wset = wb.GetWorkset(doc); List <string> typeNames = wb.TypeNames; if (typeNames == null) { continue; } if (typeNames.Count == 0) { continue; } foreach (string typeName in typeNames) { foreach (Element elem in allElems) { ElementId typeId = elem.GetTypeId(); if (typeId == null || typeId == ElementId.InvalidElementId) { continue; } ElementType elemType = doc.GetElement(typeId) as ElementType; if (elemType == null) { continue; } Debug.WriteLine("Element id: " + elem.Id.IntegerValue + ", TypeName: " + elemType.Name); if (elemType.Name.StartsWith(typeName)) { WorksetBy.SetWorkset(elem, wset); } } } } if (storage.worksetByParameter != null) { Debug.WriteLine("Start worksets by parameters"); string paramName = storage.worksetByParameter.ParameterName; foreach (Element elem in allElems) { Parameter p = elem.LookupParameter(paramName); if (p == null) { continue; } if (!p.HasValue) { continue; } if (p.StorageType != StorageType.String) { string errmsg = "Parameter is not string: " + paramName; Debug.WriteLine(errmsg); throw new Exception(errmsg); } string wsetParamValue = p.AsString(); Workset wsetByparamval = WorksetBy.GetOrCreateWorkset(doc, wsetParamValue); WorksetBy.SetWorkset(elem, wsetByparamval); } } if (storage.worksetByLink != null) { WorksetByLink wsetbylink = storage.worksetByLink; Debug.WriteLine("Worksets for link files"); List <RevitLinkInstance> links = new FilteredElementCollector(doc) .OfClass(typeof(RevitLinkInstance)) .Cast <RevitLinkInstance>() .ToList(); Debug.WriteLine("Links found: " + links.Count); foreach (RevitLinkInstance rli in links) { Debug.WriteLine("Current link: " + rli.Name); RevitLinkType linkFileType = doc.GetElement(rli.GetTypeId()) as RevitLinkType; if (linkFileType == null) { Debug.WriteLine("LinkType is invalid"); continue; } if (linkFileType.IsNestedLink) { Debug.WriteLine("It is nested link"); continue; } char separator = wsetbylink.separator[0]; string linkWorksetName1 = linkFileType.Name.Split(separator)[wsetbylink.partNumberAfterSeparator]; string linkWorksetName2 = linkWorksetName1 .Substring(wsetbylink.ignoreFirstCharsAfterSeparation, linkWorksetName1.Length - wsetbylink.ignoreLastCharsAfterSeparation); string linkWorksetName = wsetbylink.prefixForLinkWorksets + linkWorksetName2; Debug.WriteLine("Workset name: " + linkWorksetName); Workset linkWorkset = WorksetBy.GetOrCreateWorkset(doc, linkWorksetName); WorksetBy.SetWorkset(rli, linkWorkset); WorksetBy.SetWorkset(linkFileType, linkWorkset); } } t.Commit(); } List <string> emptyWorksetsNames = WorksetTool.GetEmptyWorksets(doc); if (emptyWorksetsNames.Count > 0) { string msg = "Обнаружены пустые рабочие наборы! Их можно удалить вручную:\n"; foreach (string s in emptyWorksetsNames) { msg += s + "\n"; } Debug.WriteLine("Empty worksets found: " + msg); TaskDialog.Show("Отчёт", msg); } Debug.WriteLine("Finished"); return(Result.Succeeded); }
static Parser() { CreateTrigger = delegate (DependencyObject target, string triggerText) { if (triggerText == null) { return ConventionManager.GetElementConvention(target.GetType()).CreateTrigger(); } string str = triggerText.Replace("[", string.Empty).Replace("]", string.Empty).Replace("Event", string.Empty).Trim(); return new System.Windows.Interactivity.EventTrigger { EventName = str }; }; InterpretMessageText = (target, text) => new ActionMessage { MethodName = Regex.Replace(text, "^Action", string.Empty).Trim() }; CreateParameter = delegate (DependencyObject target, string parameterText) { Parameter actualParameter = new Parameter(); if (parameterText.StartsWith("'") && parameterText.EndsWith("'")) { actualParameter.Value = parameterText.Substring(1, parameterText.Length - 2); } else if (MessageBinder.SpecialValues.ContainsKey(parameterText.ToLower()) || char.IsNumber(parameterText[0])) { actualParameter.Value = parameterText; } else if (target is FrameworkElement) { FrameworkElement fe = (FrameworkElement) target; string[] nameAndBindingMode = (from x in parameterText.Split(new char[] { ':' }) select x.Trim()).ToArray<string>(); int index = nameAndBindingMode[0].IndexOf('.'); View.ExecuteOnLoad(fe, (, ) => BindParameter(fe, actualParameter, (index == -1) ? nameAndBindingMode[0] : nameAndBindingMode[0].Substring(0, index), (index == -1) ? null : nameAndBindingMode[0].Substring(index + 1), (nameAndBindingMode.Length == 2) ? ((BindingMode) Enum.Parse(typeof(BindingMode), nameAndBindingMode[1], true)) : BindingMode.OneWay)); } return actualParameter; }; }