public SuggestedHandlerCompletionData (Project project, CodeMemberMethod methodInfo, IType codeBehindClass, IType codeBehindClassPart) { this.project = project; this.methodInfo = methodInfo; this.codeBehindClass = codeBehindClass; this.codeBehindClassPart = codeBehindClassPart; }
public void SetTestFixtureSetup(CodeMemberMethod fixtureSetupMethod) { // xUnit uses IUseFixture<T> on the class fixtureSetupMethod.Attributes |= MemberAttributes.Static; _currentFixtureTypeDeclaration = new CodeTypeDeclaration("FixtureData"); _currentTestTypeDeclaration.Members.Add(_currentFixtureTypeDeclaration); var fixtureDataType = CodeDomHelper.CreateNestedTypeReference(_currentTestTypeDeclaration, _currentFixtureTypeDeclaration.Name); var useFixtureType = new CodeTypeReference(IUSEFIXTURE_INTERFACE, fixtureDataType); CodeDomHelper.SetTypeReferenceAsInterface(useFixtureType); _currentTestTypeDeclaration.BaseTypes.Add(useFixtureType); // public void SetFixture(T) { } // explicit interface implementation for generic interfaces does not work with codedom CodeMemberMethod setFixtureMethod = new CodeMemberMethod(); setFixtureMethod.Attributes = MemberAttributes.Public; setFixtureMethod.Name = "SetFixture"; setFixtureMethod.Parameters.Add(new CodeParameterDeclarationExpression(fixtureDataType, "fixtureData")); setFixtureMethod.ImplementationTypes.Add(useFixtureType); _currentTestTypeDeclaration.Members.Add(setFixtureMethod); // public <_currentFixtureTypeDeclaration>() { <fixtureSetupMethod>(); } CodeConstructor ctorMethod = new CodeConstructor(); ctorMethod.Attributes = MemberAttributes.Public; _currentFixtureTypeDeclaration.Members.Add(ctorMethod); ctorMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(new CodeTypeReference(_currentTestTypeDeclaration.Name)), fixtureSetupMethod.Name)); }
private void AddCustomAttributesToMethod(CodeMemberMethod dbMethod) { if (base.methodSource.EnableWebMethods) { CodeAttributeDeclaration declaration = new CodeAttributeDeclaration("System.Web.Services.WebMethod"); declaration.Arguments.Add(new CodeAttributeArgument("Description", CodeGenHelper.Str(base.methodSource.WebMethodDescription))); dbMethod.CustomAttributes.Add(declaration); } DataObjectMethodType select = DataObjectMethodType.Select; if (base.methodSource.CommandOperation == CommandOperation.Update) { select = DataObjectMethodType.Update; } else if (base.methodSource.CommandOperation == CommandOperation.Delete) { select = DataObjectMethodType.Delete; } else if (base.methodSource.CommandOperation == CommandOperation.Insert) { select = DataObjectMethodType.Insert; } if (select != DataObjectMethodType.Select) { dbMethod.CustomAttributes.Add(new CodeAttributeDeclaration(CodeGenHelper.GlobalType(typeof(DataObjectMethodAttribute)), new CodeAttributeArgument[] { new CodeAttributeArgument(CodeGenHelper.Field(CodeGenHelper.GlobalTypeExpr(typeof(DataObjectMethodType)), select.ToString())), new CodeAttributeArgument(CodeGenHelper.Primitive(false)) })); } }
private void AddParametersToMethod(CodeMemberMethod dbMethod) { CodeParameterDeclarationExpression expression = null; if (base.activeCommand.Parameters != null) { DesignConnection connection = (DesignConnection) base.methodSource.Connection; if (connection == null) { throw new InternalException("Connection for query '" + base.methodSource.Name + "' is null."); } string parameterPrefix = connection.ParameterPrefix; foreach (DesignParameter parameter in base.activeCommand.Parameters) { if (parameter.Direction != ParameterDirection.ReturnValue) { Type parameterUrtType = base.GetParameterUrtType(parameter); string name = base.nameHandler.AddParameterNameToList(parameter.ParameterName, parameterPrefix); CodeTypeReference type = null; if (parameter.AllowDbNull && parameterUrtType.IsValueType) { type = CodeGenHelper.NullableType(parameterUrtType); } else { type = CodeGenHelper.Type(parameterUrtType); } expression = CodeGenHelper.ParameterDecl(type, name); expression.Direction = CodeGenHelper.ParameterDirectionToFieldDirection(parameter.Direction); dbMethod.Parameters.Add(expression); } } } }
/// <summary> /// Generates control fields /// </summary> /// <param name="source">The source.</param> /// <param name="classType">Type of the class.</param> /// <param name="method">The initialize method.</param> /// <param name="generateField">if set to <c>true</c> [generate field].</param> /// <returns></returns> public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField) { CodeExpression fieldReference = new CodeThisReferenceExpression(); CodeComHelper.GenerateBrushField(method, fieldReference, source, Control.BackgroundProperty); CodeComHelper.GenerateBrushField(method, fieldReference, source, Control.BorderBrushProperty); CodeComHelper.GenerateThicknessField(method, fieldReference, source, Control.BorderThicknessProperty); CodeComHelper.GenerateThicknessField(method, fieldReference, source, Control.PaddingProperty); CodeComHelper.GenerateBrushField(method, fieldReference, source, Control.ForegroundProperty); CodeComHelper.GenerateField<bool>(method, fieldReference, source, UIRoot.IsTabNavigationEnabledProperty); CodeComHelper.GenerateColorField(method, fieldReference, source, UIRoot.MessageBoxOverlayProperty); CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, FrameworkElement.StyleProperty); Control control = source as Control; if (!CodeComHelper.IsDefaultValue(source, Control.FontFamilyProperty) || !CodeComHelper.IsDefaultValue(source, Control.FontSizeProperty) || !CodeComHelper.IsDefaultValue(source, Control.FontStyleProperty) || !CodeComHelper.IsDefaultValue(source, Control.FontWeightProperty)) { FontGenerator.Instance.AddFont(control.FontFamily, control.FontSize, control.FontStyle, control.FontWeight, method); } CodeComHelper.GenerateFontFamilyField(method, fieldReference, source, Control.FontFamilyProperty); CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, Control.FontSizeProperty); CodeComHelper.GenerateFontStyleField(method, fieldReference, source, Control.FontStyleProperty, Control.FontWeightProperty); return fieldReference; }
/// <summary> /// Generates code for value /// </summary> /// <param name="parentClass">The parent class.</param> /// <param name="method">The method.</param> /// <param name="value">The value.</param> /// <param name="baseName">Name of the base.</param> /// <param name="dictionary">The dictionary.</param> /// <returns></returns> public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null) { string bitmapVarName = baseName + "_bm"; BitmapImage bitmap = value as BitmapImage; return CodeComHelper.GenerateBitmapImageValue(method, bitmap.UriSource, bitmapVarName); }
public SuggestedHandlerCompletionData (MonoDevelop.Projects.Project project, CodeMemberMethod methodInfo, INamedTypeSymbol codeBehindClass, Location codeBehindClassLocation) { this.project = project; this.methodInfo = methodInfo; this.codeBehindClass = codeBehindClass; this.codeBehindClassLocation = codeBehindClassLocation; }
CodeMemberMethod CreateMethod() { CodeMemberMethod method = new CodeMemberMethod(); // BeginInit method call. CodeExpressionStatement statement = new CodeExpressionStatement(); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); statement.Expression = methodInvoke; CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression(); methodRef.MethodName = "BeginInit"; CodeCastExpression cast = new CodeCastExpression(); cast.TargetType = new CodeTypeReference(); cast.TargetType.BaseType = "System.ComponentModel.ISupportInitialize"; CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression(); fieldRef.FieldName = "pictureBox1"; fieldRef.TargetObject = new CodeThisReferenceExpression(); cast.Expression = fieldRef; methodRef.TargetObject = cast; methodInvoke.Method = methodRef; method.Statements.Add(statement); return method; }
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod) { if (!String.IsNullOrWhiteSpace(Inherits)) { derivedType.BaseTypes[0] = new CodeTypeReference(Inherits); } }
private void AddCustomAttributesToMethod(CodeMemberMethod dbMethod) { DataObjectMethodType update = DataObjectMethodType.Update; if (base.methodSource.EnableWebMethods) { CodeAttributeDeclaration declaration = new CodeAttributeDeclaration("System.Web.Services.WebMethod"); declaration.Arguments.Add(new CodeAttributeArgument("Description", CodeGenHelper.Str(base.methodSource.WebMethodDescription))); dbMethod.CustomAttributes.Add(declaration); } if (base.MethodType != MethodTypeEnum.GenericUpdate) { if (base.activeCommand == base.methodSource.DeleteCommand) { update = DataObjectMethodType.Delete; } else if (base.activeCommand == base.methodSource.InsertCommand) { update = DataObjectMethodType.Insert; } else if (base.activeCommand == base.methodSource.UpdateCommand) { update = DataObjectMethodType.Update; } dbMethod.CustomAttributes.Add(new CodeAttributeDeclaration(CodeGenHelper.GlobalType(typeof(DataObjectMethodAttribute)), new CodeAttributeArgument[] { new CodeAttributeArgument(CodeGenHelper.Field(CodeGenHelper.GlobalTypeExpr(typeof(DataObjectMethodType)), update.ToString())), new CodeAttributeArgument(CodeGenHelper.Primitive(true)) })); } }
public override void SetTestMethod(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle) { base.SetTestMethod(generationContext, testMethod, scenarioTitle); if (generationContext.GenerateAsynchTests) SetupAsyncTest(testMethod); }
public override void Visit(ActionTreeNode node) { CodeTypeDeclaration type = _typeStack.Peek(); List<Type> actionArgumentTypes = new List<Type>(); CodeMemberMethod method = new CodeMemberMethod(); method.Name = node.Name; method.ReturnType = _source[typeof (IControllerActionReference)]; method.Attributes = MemberAttributes.Public; method.CustomAttributes.Add(_source.DebuggerAttribute); List<CodeExpression> actionArguments = CreateActionArgumentsAndAddParameters(method, node, actionArgumentTypes); method.Statements.Add( new CodeMethodReturnStatement(CreateNewActionReference(node, actionArguments, actionArgumentTypes))); type.Members.Add(method); if (actionArguments.Count > 0 && _occurences[node.Name] == 1) { method = new CodeMemberMethod(); method.Comments.Add( new CodeCommentStatement("Empty argument Action... Not sure if we want to pass MethodInformation to these...")); method.Name = node.Name; method.ReturnType = _source[typeof (IArgumentlessControllerActionReference)]; method.Attributes = MemberAttributes.Public; method.CustomAttributes.Add(_source.DebuggerAttribute); method.Statements.Add( new CodeMethodReturnStatement(CreateNewActionReference(node, new List<CodeExpression>(), actionArgumentTypes))); type.Members.Add(method); } base.Visit(node); }
private void RegisterClasspath(CodeMemberMethod composeMethod, XmlElement classpathElement, IList assemblies) { XmlNodeList children = classpathElement.ChildNodes; for (int i = 0; i < children.Count ; i++) { if (children[i] is XmlElement) { XmlElement childElement = (XmlElement) children[i]; string fileName = childElement.GetAttribute(FILE); string urlSpec = childElement.GetAttribute(URL); UriBuilder url = null; if (urlSpec != null && urlSpec.Length > 0) { url = new UriBuilder(urlSpec); assemblies.Add(url.ToString()); } else { if (!File.Exists(fileName)) { throw new IOException(Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName + " doesn't exist"); } assemblies.Add(fileName); } } } }
public void BuildTest() { var typeMember = new CodeMemberMethod() { Name = "TypeMemberTest" }; var propData = mocks.Stub<IBuilderData>(); Expect.Call(buildcontext.TypeMember).Return(typeMember); //Expect.Call(buildcontext.GetBuilderData("Property")).Return(propData); // is not relevant ... just a devel-testing call to // "var userData = context.GetBuilderData<BuildParametersOfPropertyBuilder>(this);" Expect.Call(buildcontext.GetBuilderData<BuildParametersOfPropertyBuilder>(testObject)).Return(null); Expect.Call(buildcontext.GetBuilderData("Property")).Return(propData).Repeat.Any(); var testClass = new CodeTypeDeclaration("TheClass"); Expect.Call(buildcontext.TestClassDeclaration).Return(testClass).Repeat.Any(); //Expect.Call(buildcontext.IsProperty).Return(true); mocks.ReplayAll(); testObject.Build(this.buildcontext); // Todo: check if only the ending "Test" gets replaced. var expected = "TypeMemberNormalBehavior"; var actual = typeMember.Name; Assert.AreEqual(expected, actual); mocks.VerifyAll(); }
public override void ProcessGeneratedCode( CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod) { ExampleDependencyInjectionLogic(buildMethod); base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod); }
internal void AddMethods(CodeTypeDeclaration dataSourceClass) { this.AddSchemaSerializationModeMembers(dataSourceClass); this.initExpressionsMethod = this.InitExpressionsMethod(); dataSourceClass.Members.Add(this.PublicConstructor()); dataSourceClass.Members.Add(this.DeserializingConstructor()); dataSourceClass.Members.Add(this.InitializeDerivedDataSet()); dataSourceClass.Members.Add(this.CloneMethod(this.initExpressionsMethod)); dataSourceClass.Members.Add(this.ShouldSerializeTablesMethod()); dataSourceClass.Members.Add(this.ShouldSerializeRelationsMethod()); dataSourceClass.Members.Add(this.ReadXmlSerializableMethod()); dataSourceClass.Members.Add(this.GetSchemaSerializableMethod()); dataSourceClass.Members.Add(this.InitVarsParamLess()); CodeMemberMethod initClassMethod = null; CodeMemberMethod initVarsMethod = null; this.InitClassAndInitVarsMethods(out initClassMethod, out initVarsMethod); dataSourceClass.Members.Add(initVarsMethod); dataSourceClass.Members.Add(initClassMethod); this.AddShouldSerializeSingleTableMethods(dataSourceClass); dataSourceClass.Members.Add(this.SchemaChangedMethod()); dataSourceClass.Members.Add(this.GetTypedDataSetSchema()); dataSourceClass.Members.Add(this.TablesProperty()); dataSourceClass.Members.Add(this.RelationsProperty()); if (this.initExpressionsMethod != null) { dataSourceClass.Members.Add(this.initExpressionsMethod); } }
public static void ExampleDependencyInjectionLogic(CodeMemberMethod buildMethod) { // Non file based controls are different than file based controls. // Non file based controls are instantiated with "new" inside of a method and returned. // They are declared in the first statement. CodeVariableDeclarationStatement declaration = (CodeVariableDeclarationStatement)buildMethod.Statements[0]; // Use the type of the declaration to get the type of the control. Type type = Type.GetType(declaration.Type.BaseType); // Standard reflection to get all of the properties. You could also look for fields. PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); foreach(PropertyInfo property in properties) { // See if the property has the specific attribute we care about. object[] injectDeps = property.GetCustomAttributes(typeof(InjectDepAttribute), true); if(injectDeps.Length == 1) { // Create the code dom to perform the injection. // In this example, set the property to the literal the attribute was given. CodeStatement setProperty = new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(declaration.Name), property.Name), new CodePrimitiveExpression((injectDeps[0] as InjectDepAttribute).Name + " (the builder method this is set in is '" + buildMethod.Name + "')") ); // Add the statement to the list of statements that make up the builder method. // The last statement is the return statement that returns the control. // So we insert out injection statement(s) right before it. buildMethod.Statements.Insert(buildMethod.Statements.Count - 1, setProperty); } } }
private void BuildAddContentPlaceHolderNames(CodeMemberMethod method, string placeHolderID) { CodePropertyReferenceExpression propertyExpr = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ContentPlaceHolders"); CodeExpressionStatement stmt = new CodeExpressionStatement(); stmt.Expression = new CodeMethodInvokeExpression(propertyExpr, "Add", new CodePrimitiveExpression(placeHolderID.ToLower(CultureInfo.InvariantCulture))); method.Statements.Add(stmt); }
static void GenerateWidgetCode(SteticCompilationUnit globalUnit, CodeNamespace globalNs, GenerationOptions options, List<SteticCompilationUnit> units, Gtk.Widget w, ArrayList warnings) { // Generate the build method CodeTypeDeclaration type = CreatePartialClass (globalUnit, units, options, w.Name); CodeMemberMethod met = new CodeMemberMethod (); met.Name = "Build"; type.Members.Add (met); met.ReturnType = new CodeTypeReference (typeof(void)); met.Attributes = MemberAttributes.Family; if (options.GenerateEmptyBuildMethod) { GenerateWrapperFields (type, Wrapper.Widget.Lookup (w)); return; } met.Statements.Add ( new CodeMethodInvokeExpression ( new CodeTypeReferenceExpression (globalNs.Name + ".Gui"), "Initialize", new CodeThisReferenceExpression () ) ); Stetic.Wrapper.Widget wwidget = Stetic.Wrapper.Widget.Lookup (w); if (wwidget.GeneratePublic) type.TypeAttributes = TypeAttributes.Public; else type.TypeAttributes = TypeAttributes.NotPublic; Stetic.WidgetMap map = Stetic.CodeGenerator.GenerateCreationCode (globalNs, type, w, new CodeThisReferenceExpression (), met.Statements, options, warnings); CodeGenerator.BindSignalHandlers (new CodeThisReferenceExpression (), wwidget, map, met.Statements, options); }
public void CanCreateDataTableAssignment() { CodeNamespace nsdecl = new CodeNamespace("My.Data"); CodeTypeDeclaration cdecl = new CodeTypeDeclaration("ResultSet"); CodeMemberMethod method = new CodeMemberMethod(); method.Name = "GetData"; method.Attributes = MemberAttributes.Public | MemberAttributes.Final; method.ReturnType = new CodeTypeReference("System.Data.DataTable"); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name")); method.Statements.Add(new CodeVariableDeclarationStatement( typeof(DataTable), "result", new CodeObjectCreateExpression(typeof(DataTable)))); cdecl.Members.Add(method); method.Statements.Add( new CodeVariableDeclarationStatement( typeof(DataColumnCollection), "columns", new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("result"), "Columns"))); method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("columns"), "Add", new CodeTypeOfExpression(typeof(string)), new CodeSnippetExpression("name"))); nsdecl.Types.Add(cdecl); CSharpCodeProvider provider = new CSharpCodeProvider(); provider.GenerateCodeFromNamespace(nsdecl, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); }
public override void GenerateMappingCode(CodeGenerationContext ctx, CodeMemberMethod method) { if (!String.IsNullOrEmpty(To)) MappedProperty = TypeReflector.GetProperty(ctx.MappedObjectType, To); if (MappedProperty != null) { if (MapNotBoolProperty) { // type value = bitReader.ReadBits(length); method.Statements.Add(new CodeVariableDeclarationStatement(MappedValueType, "value", new CodeMethodInvokeExpression(ctx.DataReader, "ReadBits", new CodePrimitiveExpression(Length)))); } else { method.Statements.Add( new CodeVariableDeclarationStatement(MappedValueType, "value", new CodeBinaryOperatorExpression( new CodeMethodInvokeExpression(ctx.DataReader, "ReadBits", new CodePrimitiveExpression(Length)), CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(0)))); } // add operations code CodeVariableReferenceExpression value = new CodeVariableReferenceExpression("value"); foreach (IOperation op in Operations) method.Statements.AddRange(op.BuildOperation(ctx, this, value)); method.Statements.AddRange(GenerateSetMappedPropertyCode(ctx.MappedObject, value)); } else { // just read method.Statements.Add( new CodeMethodInvokeExpression(ctx.DataReader, "ReadBits", new CodePrimitiveExpression(Length))); } }
public override void SetTestMethod(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string friendlyTestName) { base.SetTestMethod(generationContext, testMethod, friendlyTestName); if(generationContext.CustomData.ContainsKey("featureCategories")) { var featureCategories = (string[])generationContext.CustomData["featureCategories"]; CodeDomHelper.AddAttributeForEachValue(testMethod, CATEGORY_ATTR, featureCategories); } if(generationContext.CustomData.ContainsKey(OWNER_TAG)) { string ownerName = generationContext.CustomData[OWNER_TAG] as string; if(!String.IsNullOrEmpty(ownerName)) { CodeDomHelper.AddAttribute(testMethod, OWNER_ATTR, ownerName); } } if(generationContext.CustomData.ContainsKey(WORKITEM_TAG)) { IEnumerable<int> workitems = generationContext.CustomData[WORKITEM_TAG] as IEnumerable<int>; foreach(int workitem in workitems) { CodeDomHelper.AddAttribute(testMethod, WORKITEM_ATTR, workitem); } } }
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() { const string expectedPropertyCode = @" protected Foo.Bar ApplicationInstance { get { return ((Foo.Bar)(Context.ApplicationInstance)); } } "; // Arrange CodeCompileUnit generatedCode = new CodeCompileUnit(); CodeNamespace generatedNamespace = new CodeNamespace(); CodeTypeDeclaration generatedClass = new CodeTypeDeclaration(); CodeMemberMethod executeMethod = new CodeMemberMethod(); WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") { GlobalAsaxTypeName = "Foo.Bar" }; // Act host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod); // Assert CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty; Assert.IsNotNull(property); CSharpCodeProvider provider = new CSharpCodeProvider(); StringBuilder builder = new StringBuilder(); using(StringWriter writer = new StringWriter(builder)) { provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions()); } Assert.AreEqual(expectedPropertyCode, builder.ToString()); }
static CodeNamespace BuildProgram() { // namespaceの作成 var ns = new CodeNamespace("MetaWorld"); // import編成 var systemImport = new CodeNamespaceImport("System"); // class作成 var programClass = new CodeTypeDeclaration("Program"); // mainメソッドの定義 var methodMain = new CodeMemberMethod() { Attributes = MemberAttributes.Static, Name = "Main" }; methodMain.Statements.Add( new CodeMethodInvokeExpression( new CodeSnippetExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World") ) ); // コード構造の編成 programClass.Members.Add(methodMain); ns.Imports.Add(systemImport); ns.Types.Add(programClass); return ns; }
/// <summary> /// Initializes a new instance of the <see cref="CodeLocalVariableBinder"/> class /// with a local variable declaration. /// </summary> /// <param name="method">The method to add a <see cref="CodeTypeReference"/> to.</param> /// <param name="variableDeclaration">The variable declaration to add.</param> internal CodeLocalVariableBinder(CodeMemberMethod method, CodeVariableDeclarationStatement variableDeclaration) { Guard.NotNull(() => method, method); Guard.NotNull(() => variableDeclaration, variableDeclaration); this.method = method; this.variableDeclaration = variableDeclaration; }
/// <summary> /// Initializes a new instance of the <see cref="CodeLocalVariableBinder"/> class /// with a reference to a variable. /// </summary> /// <param name="method">The method to add a <see cref="CodeTypeReference"/> to.</param> /// <param name="reference">The reference to a local variable.</param> internal CodeLocalVariableBinder(CodeMemberMethod method, CodeVariableReferenceExpression reference) { Guard.NotNull(() => method, method); Guard.NotNull(() => reference, reference); this.method = method; this.reference = reference; }
protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value) { if (manager == null) { throw new ArgumentNullException("manager"); } if (typeDecl == null) { throw new ArgumentNullException("typeDecl"); } if (value == null) { throw new ArgumentNullException("value"); } CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod; if (method == null) { method = new CodeMemberMethod { Name = "InitializeComponent", Attributes = MemberAttributes.Private }; typeDecl.UserData[_initMethodKey] = method; CodeConstructor constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression[0])); typeDecl.Members.Add(constructor); } return method; }
protected override void WriteFunctionDefinition(CodeMemberMethod func) { Writer.Write("def "); Writer.Write(func.Name); Writer.Write("("); for (int i = 0; i < func.Parameters.Count; ++i) { if (i != 0) { Writer.Write(","); } Writer.Write(func.Parameters[i].Name); } Writer.Write("):\n"); int baseIndent = _indents.Peek(); _generatedIndent += 4; foreach (CodeStatement stmt in func.Statements) { WriteStatement(stmt); } _generatedIndent -= 4; while (_indents.Peek() > baseIndent) { _indents.Pop(); } }
/// <summary> /// Generates code /// </summary> /// <param name="source">The dependence object</param> /// <param name="classType">Type of the class.</param> /// <param name="initMethod">The initialize method.</param> /// <param name="generateField"></param> /// <returns></returns> public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod initMethod, bool generateField) { CodeExpression fieldReference = base.Generate(source, classType, initMethod, generateField); CodeComHelper.GenerateEnumField<Stretch>(initMethod, fieldReference, source, ImageButton.ImageStretchProperty); ImageButton imageButton = source as ImageButton; BitmapImage bitmap = imageButton.ImageNormal as BitmapImage; if (bitmap != null) { CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_normal_bm", ImageButton.ImageNormalProperty); } bitmap = imageButton.ImageDisabled as BitmapImage; if (bitmap != null) { CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_disabled_bm", ImageButton.ImageDisabledProperty); } bitmap = imageButton.ImageHover as BitmapImage; if (bitmap != null) { CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_hover_bm", ImageButton.ImageHoverProperty); } bitmap = imageButton.ImagePressed as BitmapImage; if (bitmap != null) { CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_pressed_bm", ImageButton.ImagePressedProperty); } return fieldReference; }
public override void SetTestMethodCategories(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> scenarioCategories) { IEnumerable<string> tags = scenarioCategories.ToList(); IEnumerable<string> ownerTags = tags.Where(t => t.StartsWith(OWNER_TAG, StringComparison.InvariantCultureIgnoreCase)).Select(t => t); if(ownerTags.Any()) { string ownerName = ownerTags.Select(t => t.Substring(OWNER_TAG.Length).Trim('\"')).FirstOrDefault(); if(!String.IsNullOrEmpty(ownerName)) { CodeDomHelper.AddAttribute(testMethod, OWNER_ATTR, ownerName); } } IEnumerable<string> workitemTags = tags.Where(t => t.StartsWith(WORKITEM_TAG, StringComparison.InvariantCultureIgnoreCase)).Select(t => t); if(workitemTags.Any()) { int temp; IEnumerable<string> workitemsAsStrings = workitemTags.Select(t => t.Substring(WORKITEM_TAG.Length).Trim('\"')); IEnumerable<int> workitems = workitemsAsStrings.Where(t => int.TryParse(t, out temp)).Select(t => int.Parse(t)); foreach(int workitem in workitems) { CodeDomHelper.AddAttribute(testMethod, WORKITEM_ATTR, workitem); } } CodeDomHelper.AddAttributeForEachValue(testMethod, CATEGORY_ATTR, GetNonMSTestSpecificTags(tags)); }
public async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(System.CodeDom.CodeMemberMethod Method, string valueName) { await EngineNS.Thread.AsyncDummyClass.DummyFunc(); var param = CSParam as CreateObjectConstructionParams; // 生成创建的代码 if (mVarDec == null || !Method.Statements.Contains(mVarDec)) { //var valueName = GCode_GetValueName(null, context); if (mTemplateClassInstance != null) { var type = mTemplateClassInstance.GetType(); foreach (var pro in mClassProperties) { var proInfo = type.GetProperty(pro.PropertyName); if (proInfo == null) { continue; } var defProInfo = param.CreateType.GetProperty(pro.PropertyName); var curValue = proInfo.GetValue(mTemplateClassInstance); var defValue = defProInfo.GetValue(mDefaultValueObj); if (object.Equals(curValue, defValue)) { continue; } if (pro.PropertyType.FullName == typeof(EngineNS.RName).FullName) { var rname = curValue as EngineNS.RName; if (rname == null) { Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodePrimitiveExpression(null))); } else { Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodeSnippetExpression($"EngineNS.CEngine.Instance.FileManager.GetRName(\"{rname.Name}\", {EngineNS.Rtti.RttiHelper.GetAppTypeString(typeof(EngineNS.RName.enRNameType))}.{rname.RNameType.ToString()})"))); } } else if (pro.PropertyType.IsEnum) { Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodeVariableReferenceExpression(EngineNS.Rtti.RttiHelper.GetAppTypeString(pro.PropertyType) + "." + curValue.ToString()))); } else { Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodePrimitiveExpression(curValue))); } } } mVarDec = new System.CodeDom.CodeVariableDeclarationStatement(param.CreateType, valueName, new CodeObjectCreateExpression(param.CreateType, new CodeExpression[0])); Method.Statements.Insert(0, mVarDec); } }
public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Class context) { if (!mCtrlValueInputHandle.HasLink) { return; } System.CodeDom.CodeMemberMethod initMethod = null; foreach (var member in codeClass.Members) { if (member.GetType() == typeof(CodeMemberMethod)) { var method = member as CodeMemberMethod; if (method.Name == "Init") { initMethod = method; } } } if (initMethod == null) { initMethod = new CodeMemberMethod(); initMethod.Name = "Init"; initMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public; codeClass.Members.Add(initMethod); } var linkObj = mCtrlValueInputHandle.GetLinkedObject(0, true); var linkElm = mCtrlValueInputHandle.GetLinkedPinControl(0, true); var methodContext = new GenerateCodeContext_Method(context, initMethod); methodContext.InstanceAnimPoseReferenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "AnimationPoseProxy"); methodContext.AnimAssetAnimPoseProxyReferenceExpression = methodContext.InstanceAnimPoseReferenceExpression; methodContext.AnimAssetTickHostReferenceExpression = new CodeThisReferenceExpression(); await linkObj.GCode_CodeDom_GenerateCode(codeClass, initMethod.Statements, linkElm, methodContext); var returnExpression = linkObj.GCode_CodeDom_GetSelfRefrence(mCtrlValueInputHandle, methodContext); CodeMethodInvokeExpression createCachedPose = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "GetCachedAnimPose"), new CodePrimitiveExpression("CachedPose_" + NodeName)); //CodeVariableDeclarationStatement cachedPoseRef = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(EngineNS.Graphics.Mesh.Animation.CGfxAnimationPose)), NodeName); //CodeAssignStatement cachedPoseAssign = new CodeAssignStatement(); //cachedPoseAssign.Left = cachedPoseRef; //cachedPoseAssign.Right = createCachedPose; //initMethod.Statements.Add(cachedPoseAssign); CodeFieldReferenceExpression animPoseField = new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(returnExpression, "AnimationPoseProxy"), "Pose"); CodeAssignStatement animPoseAssign = new CodeAssignStatement(); animPoseAssign.Left = animPoseField; animPoseAssign.Right = new CodeFieldReferenceExpression(createCachedPose, "CachedAnimationPose"); initMethod.Statements.Add(animPoseAssign); }
protected override void GenerateMethod(System.CodeDom.CodeMemberMethod e, System.CodeDom.CodeTypeDeclaration c) { if (e.ReturnType.BaseType == string_consts.void_type) { Output.Write("procedure "); } else { Output.Write("function "); } OutputMethodSignature(e.Attributes, e.ReturnType, e.Name, e.Parameters, false, false); GenerateBlock(e.Statements); Output.WriteLine(";"); }
public void ConstructWithParametersBuildDataSetUpMethodTestObjectMemberFieldTestObjectNameTestObjectTypeTest() { this.buildData = new NStub.CSharp.ObjectGeneration.BuildDataDictionary(); this.setUpMethod = new System.CodeDom.CodeMemberMethod(); this.testObjectMemberField = new System.CodeDom.CodeMemberField(); this.testObjectName = "myTestObjectName"; this.testObjectType = typeof(object); this.testObject = new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, this.testObjectName, this.testObjectType); Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(null, this.setUpMethod, this.testObjectMemberField, this.testObjectName, this.testObjectType)); Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, null, this.testObjectMemberField, this.testObjectName, this.testObjectType)); Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, null, this.testObjectName, this.testObjectType)); Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, null, this.testObjectType)); Assert.Throws <ArgumentException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, string.Empty, this.testObjectType)); Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, this.testObjectName, null)); }
public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Class context) { if (!mCtrlValueInputHandle.HasLink) return; System.CodeDom.CodeMemberMethod initMethod = null; foreach (var member in codeClass.Members) { if (member is CodeGenerateSystem.CodeDom.CodeMemberMethod) { var method = member as CodeGenerateSystem.CodeDom.CodeMemberMethod; if (method.Name == "Init") initMethod = method; } } if (initMethod == null) { initMethod = new CodeGenerateSystem.CodeDom.CodeMemberMethod(); initMethod.Name = "Init"; initMethod.Attributes = MemberAttributes.Override | MemberAttributes.Public; codeClass.Members.Add(initMethod); } var linkObj = mCtrlValueInputHandle.GetLinkedObject(0, true); var linkElm = mCtrlValueInputHandle.GetLinkedPinControl(0, true); var methodContext = new GenerateCodeContext_Method(context, initMethod); await GenerateCachedPose(codeClass, initMethod.Statements, linkElm, methodContext); methodContext.InstanceAnimPoseReferenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "AnimationPoseProxy"); methodContext.AnimAssetAnimPoseProxyReferenceExpression = methodContext.InstanceAnimPoseReferenceExpression; methodContext.AnimAssetTickHostReferenceExpression = new CodeThisReferenceExpression(); await linkObj.GCode_CodeDom_GenerateCode(codeClass, initMethod.Statements, linkElm, methodContext); var returnExp = linkObj.GCode_CodeDom_GetSelfRefrence(mCtrlValueInputHandle, methodContext); if (returnExp != null) { CodeFieldReferenceExpression animPoseField = new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(returnExp, "AnimationPoseProxy"),"Pose"); CodeAssignStatement animPoseAssign = new CodeAssignStatement(); animPoseAssign.Left = animPoseField; animPoseAssign.Right = new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "AnimationPoseProxy"),"Pose"); initMethod.Statements.Add(animPoseAssign); } }
protected override void GenerateMethod(System.CodeDom.CodeMemberMethod e, System.CodeDom.CodeTypeDeclaration c) { if (e.Name == "InitializeComponent" && own_output || !own_output && e.Name != "InitializeComponent") { if (e.ReturnType.BaseType == string_consts.void_type) { Output.Write("procedure "); } else { Output.Write("function "); } OutputMethodSignature(e.Attributes, e.ReturnType, e.Name, e.Parameters, false, false); GenerateBlock(e.Statements); Output.WriteLine(";"); } else if (!own_output && e.Name == "InitializeComponent") { Output.WriteLine(string.Format("{{$include {0}}}", UnitName + "." + c.Name + ".inc")); } }
public override void ExportCode(ActionBranch currentAction, ActionBranch nextAction, ILimnorCodeCompiler compiler, IMethodCompile methodToCompile, System.CodeDom.CodeMemberMethod method, System.CodeDom.CodeStatementCollection statements, bool debug) { IMathExpression mathExp = MathExp; if (mathExp != null) { CodeExpression ceCondition = null; if (Condition != null) { ceCondition = Condition.ExportCode(methodToCompile); if (ceCondition != null) { ceCondition = CompilerUtil.ConvertToBool(Condition.DataType, ceCondition); } } CodeExpression ce = mathExp.ReturnCodeExpression(methodToCompile); if (ce != null) { if (ceCondition == null) { statements.Add(new CodeMethodReturnStatement(ce)); } else { CodeConditionStatement cd = new CodeConditionStatement(); cd.Condition = ceCondition; cd.TrueStatements.Add(new CodeMethodReturnStatement(ce)); statements.Add(cd); } } } }
public void SetTestMethod(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, string scenarioTitle) { this.codeDomHelper.AddAttribute(testMethod, TEST_ATTR); this.codeDomHelper.AddAttribute(testMethod, DESCRIPTION_ATTR, scenarioTitle); }
public void ExportCode(ActionBranch currentAction, ActionBranch nextAction, ILimnorCodeCompiler compiler, MathExp.IMethodCompile methodToCompile, System.CodeDom.CodeMemberMethod method, System.CodeDom.CodeStatementCollection statements, bool debug) { }
public void SetTestMethodIgnore(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod) { this.codeDomHelper.AddAttribute(testMethod, IGNORE_ATTR); }
public void SetRowTest(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, string scenarioTitle) { this.SetTestMethod(generationContext, testMethod, scenarioTitle); }
public void SetRow(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, IEnumerable <string> arguments, IEnumerable <string> tags, bool isIgnored) { var args = arguments.Select( arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList(); // addressing ReSharper bug: TestCase attribute with empty string[] param causes inconclusive result - https://github.com/techtalk/SpecFlow/issues/116 var exampleTagExpressionList = tags.Select(t => new CodePrimitiveExpression(t)).ToArray(); CodeExpression exampleTagsExpression = exampleTagExpressionList.Length == 0 ? (CodeExpression) new CodePrimitiveExpression(null) : new CodeArrayCreateExpression(typeof(string[]), exampleTagExpressionList); args.Add(new CodeAttributeArgument(exampleTagsExpression)); if (isIgnored) { args.Add(new CodeAttributeArgument("Ignored", new CodePrimitiveExpression(true))); } var browsers = testMethod.UserData.Keys.OfType <string>() .Where(key => key.StartsWith("Browser:")) .Select(key => (string)testMethod.UserData[key]).ToArray(); if (browsers.Any()) { foreach (var codeAttributeDeclaration in testMethod.CustomAttributes.Cast <CodeAttributeDeclaration>().Where(attr => attr.Name == ROW_ATTR && attr.Arguments.Count == 3).ToList()) { testMethod.CustomAttributes.Remove(codeAttributeDeclaration); } foreach (var browser in browsers) { var argsString = string.Concat(args.Take(args.Count - 1).Select(arg => string.Format("\"{0}\" ,", ((CodePrimitiveExpression)arg.Value).Value))); argsString = argsString.TrimEnd(' ', ','); var withBrowserArgs = new[] { new CodeAttributeArgument(new CodePrimitiveExpression(browser)) } .Concat(args) .Concat(new [] { new CodeAttributeArgument("Category", new CodePrimitiveExpression(browser)), new CodeAttributeArgument("TestName", new CodePrimitiveExpression(string.Format("{0} on {1} with: {2}", testMethod.Name, browser, argsString))) }) .ToArray(); this.codeDomHelper.AddAttribute(testMethod, ROW_ATTR, withBrowserArgs); } } else { this.codeDomHelper.AddAttribute(testMethod, ROW_ATTR, args.ToArray()); } }
public void SetTestMethodCategories(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, IEnumerable <string> scenarioCategories) { this.codeDomHelper.AddAttributeForEachValue(testMethod, CATEGORY_ATTR, scenarioCategories.Where(cat => !cat.StartsWith("Browser:"))); bool hasBrowser = false; foreach (var browser in scenarioCategories.Where(cat => cat.StartsWith("Browser:")).Select(cat => cat.Replace("Browser:", ""))) { testMethod.UserData.Add("Browser:" + browser, browser); var withBrowserArgs = new[] { new CodeAttributeArgument(new CodePrimitiveExpression(browser)) } .Concat(new[] { new CodeAttributeArgument("Category", new CodePrimitiveExpression(browser)), new CodeAttributeArgument("TestName", new CodePrimitiveExpression(string.Format("{0} on {1}", testMethod.Name, browser))) }) .ToArray(); this.codeDomHelper.AddAttribute(testMethod, ROW_ATTR, withBrowserArgs); hasBrowser = true; } if (hasBrowser) { if (!scenarioSetupMethodsAdded) { generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement(" if(this.driver != null)")); generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement(" ScenarioContext.Current.Add(\"Driver\", this.driver);")); generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement(" if(this.container != null)")); generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement(" ScenarioContext.Current.Add(\"Container\", this.container);")); scenarioSetupMethodsAdded = true; } testMethod.Statements.Insert(0, new CodeSnippetStatement(" InitializeSelenium(browser);")); testMethod.Parameters.Insert(0, new System.CodeDom.CodeParameterDeclarationExpression("System.string", "browser")); } }
public void SetTestMethodAsRow(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, string scenarioTitle, string exampleSetName, string variantName, IEnumerable <KeyValuePair <string, string> > arguments) { }