private void GenerateMainboardProperty(CodeMemberProperty mainboard, GadgeteerModel model) { CodePropertyReferenceExpression baseMainboardReference = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("Gadgeteer.Program"), "Mainboard"); CodeTypeReference mainboardTypeReference = new CodeTypeReference("Gadgeteer.Mainboard"); if (model.Mainboard != null) { mainboardTypeReference = new CodeTypeReference(model.Mainboard.MainboardDefinitionTypeName); } mainboard.GetStatements.Add( new CodeMethodReturnStatement( new CodeCastExpression(mainboardTypeReference, baseMainboardReference))); mainboard.SetStatements.Add( new CodeAssignStatement( baseMainboardReference, new CodeVariableReferenceExpression("value"))); mainboard.Type = mainboardTypeReference; }
private void SerializeNormalProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor descriptor, CodeStatementCollection statements) { CodeExpression leftSide = base.SerializeToExpression(manager, value); CodeExpression rightSide = null; MemberRelationship relationship = GetRelationship(manager, value, descriptor); if (!relationship.IsEmpty) { rightSide = new CodePropertyReferenceExpression(base.SerializeToExpression(manager, relationship.Owner), relationship.Member.Name); } else { rightSide = base.SerializeToExpression(manager, descriptor.GetValue(value)); } statements.Add(new CodeAssignStatement(leftSide, rightSide)); }
private void BuildPropertyGetter(CodeMemberProperty memberProperty, PropertyInfo property) { if (property.IsIndexer()) { CodeExpression indexerExpression = new CodeIndexerExpression( WrappedField, memberProperty.Parameters.Cast <CodeParameterDeclarationExpression>() .Select(p => new CodeVariableReferenceExpression(p.Name)) .ToArray <CodeExpression>()); if (IsRegistered(property.PropertyType)) { indexerExpression = new CodeObjectCreateExpression(WrappedTypeDictionary.GetTypeNameFor(property.PropertyType), indexerExpression); } memberProperty.GetStatements.Add(new CodeMethodReturnStatement(indexerExpression)); return; } if (memberProperty.Type.IsArray() && IsRegistered(memberProperty.Type.ArrayElementType.BaseType)) { var array = InvokeConvertAllWrapped( new CodePropertyReferenceExpression(WrappedField, memberProperty.Name), memberProperty.Type.ArrayElementType.BaseType ); memberProperty.GetStatements.Add(new CodeMethodReturnStatement(array)); return; } CodeExpression expression = new CodePropertyReferenceExpression(WrappedField, memberProperty.Name); if (IsRegistered(property.PropertyType)) { expression = new CodeObjectCreateExpression(WrappedTypeDictionary.GetTypeNameFor(property.PropertyType), expression); } memberProperty.GetStatements.Add(new CodeMethodReturnStatement(expression)); }
public virtual CodeStatement[] DumpReadToken(string grammarId, SyntaxParserMapAlgorithm algorithm) { List <CodeStatement> list = new List <CodeStatement>(); { /// if ("XXX" == str) var ifStatement = new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePrimitiveExpression(this.Value.Content), CodeBinaryOperatorType.IdentityEquality, new CodeVariableReferenceExpression("str"))); { var convertor = new TreeNodeType2TokenType(); // result.TokenType = new TokenType("..", "..", ".."); var newTokenType = new CodeAssignStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("result"), "TokenType"), new CodeObjectCreateExpression(typeof(TokenType), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(Program.GetTokenConstTypeName(grammarId, algorithm)), Program.GetNodeNameInParser(this.Value)), new CodePrimitiveExpression(this.Value.Content), new CodePrimitiveExpression(this.Value.Nickname))); ifStatement.TrueStatements.Add(newTokenType); // context.NextLetterIndex = context.NextLetterIndex + {0} var pointer = new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("context"), "NextLetterIndex"); var incresePointer = new CodeAssignStatement( pointer, new CodeBinaryOperatorExpression( pointer, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(this.Value.Content.Length))); ifStatement.TrueStatements.Add(incresePointer); // return true; var returnTrue = new CodeMethodReturnStatement(new CodePrimitiveExpression(true)); ifStatement.TrueStatements.Add(returnTrue); } list.Add(ifStatement); } return(list.ToArray()); }
private void AddItem(string item) { AddVar(item); CodeMemberProperty _property = new CodeMemberProperty(); _property.Attributes = (_property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; _property.Name = item; CodeTypeReference _Keel_DBHelper1_type1 = new CodeTypeReference("Keel.DBHelper", CodeTypeReferenceOptions.GenericTypeParameter); _Keel_DBHelper1_type1.TypeArguments.Add(item); _property.Type = _Keel_DBHelper1_type1; _property.HasGet = true; AddSomeCode(item, _property);//在 get { }中 写入一部分代码 CodeMethodReturnStatement _return1 = new CodeMethodReturnStatement(); CodePropertyReferenceExpression _prop8 = new CodePropertyReferenceExpression(); _prop8.PropertyName = "var_" + item; CodeThisReferenceExpression _this8 = new CodeThisReferenceExpression(); _prop8.TargetObject = _this8; _return1.Expression = _prop8; _property.GetStatements.Add(_return1); _property.HasSet = true; CodeAssignStatement _assign3 = new CodeAssignStatement(); CodePropertyReferenceExpression _prop9 = new CodePropertyReferenceExpression(); _prop9.PropertyName = "var_" + item; CodeThisReferenceExpression _this9 = new CodeThisReferenceExpression(); _prop9.TargetObject = _this9; _assign3.Left = _prop9; _assign3.Right = new CodePropertySetValueReferenceExpression(); _property.SetStatements.Add(_assign3); ctd.Members.Add(_property); }
public void GetSectionNameNullTest() { var index = defaultIndexAfterOffset; var methodName = "__BuildControl__control"; Assert.IsNull(SectionControlBuilder.GetSectionName(new CodeTypeMember[] { }, defaultIndex)); var method = new CodeMemberMethod(); method = new CodeMemberMethod() { Name = methodName + index.ToString() }; method.Statements.Add(new CodeSnippetStatement("test")); Assert.IsNull(SectionControlBuilder.GetSectionName(new CodeTypeMember[] { method }, defaultIndex)); var statement = new CodeAssignStatement(null, null); method.Statements.Clear(); method.Statements.Add(statement); Assert.IsNull(SectionControlBuilder.GetSectionName(new CodeTypeMember[] { method }, defaultIndex)); var left = new CodePropertyReferenceExpression(null, "test"); statement = new CodeAssignStatement(left, null); method.Statements.Clear(); method.Statements.Add(statement); Assert.IsNull(SectionControlBuilder.GetSectionName(new CodeTypeMember[] { method }, defaultIndex)); left = new CodePropertyReferenceExpression(null, "Name"); statement = new CodeAssignStatement(left, null); method.Statements.Clear(); method.Statements.Add(statement); Assert.IsNull(SectionControlBuilder.GetSectionName(new CodeTypeMember[] { method }, defaultIndex)); left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("test"), "Name"); statement = new CodeAssignStatement(left, null); method.Statements.Clear(); method.Statements.Add(statement); Assert.IsNull(SectionControlBuilder.GetSectionName(new CodeTypeMember[] { method }, defaultIndex)); }
private static CodeAssignStatement GenerateConvertBackStatement(RequestParameter parameter, int?converterIndex) { var parametersReference = new CodeVariableReferenceExpression(parametersName); var castedOObjReference = new CodeVariableReferenceExpression(castedObjName); CodeExpression propertyReference = new CodePropertyReferenceExpression( castedOObjReference, parameter.Name); return(new CodeAssignStatement( new CodeArrayIndexerExpression( parametersReference, new CodePrimitiveExpression(parameter.Index)), converterIndex.HasValue ? new CodeMethodInvokeExpression( new CodeArrayIndexerExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), convertersFieldName), new CodePrimitiveExpression(converterIndex)), "Convert", propertyReference) : propertyReference)); }
private bool HandleDynamic(CodePropertyReferenceExpression obj, Context ctx) { if (string.IsNullOrEmpty(MemberAccessOperator)) { return(false); } if (obj.TargetObject != null) { WrapAccessorTargetIfNecessaryAndHandle(obj.TargetObject, ctx); ctx.Writer.Write(MemberAccessOperator); } if (_useAsIdentifierOnMemberAccess || obj.TargetObject == null) { ctx.Writer.Write(AsIdentifier(obj.PropertyName)); } else { ctx.Writer.Write(obj.PropertyName); } return(true); }
private static CodeStatement CreateCompareRevisionStatement(CodeTypeDeclaration classType, CodeGenerationInfo generationInfo) { var ccs = new CodeConditionStatement(); var left1 = new CodeVariableReferenceExpression("verifyRevision"); var right1 = new CodePrimitiveExpression(true); var left = new CodeBinaryOperatorExpression(left1, CodeBinaryOperatorType.IdentityEquality, right1); var left2 = new CodeCastExpression(typeof(string), new CodePrimitiveExpression(generationInfo.Revision)); var right2 = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("dataSet"), "Revision"); var right = new CodeBinaryOperatorExpression(left2, CodeBinaryOperatorType.IdentityInequality, right2); ccs.Condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.BooleanAnd, right); var message = string.Format("데이터의 리비전 코드 리비전({0})과 다릅니다.", generationInfo.Revision); var exception = new CodeObjectCreateExpression(typeof(Exception), new CodePrimitiveExpression(message)); ccs.TrueStatements.Add(new CodeThrowExceptionStatement(exception)); return(ccs); }
/// <summary> /// Serializes the given object into a CodeDom object. /// </summary> public override object Serialize(IDesignerSerializationManager manager, object value) { CodeDomSerializer baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(ImageList).BaseType, typeof(CodeDomSerializer)); object codeObject = baseSerializer.Serialize(manager, value); ImageList imageList = value as ImageList; if (imageList != null) { StringCollection imageKeys = imageList.Images.Keys; if (codeObject is CodeStatementCollection) { CodeExpression imageListObject = GetExpression(manager, value); if (imageListObject != null) { CodeExpression imageListImagesProperty = new CodePropertyReferenceExpression(imageListObject, "Images"); if (imageListImagesProperty != null) { for (int i = 0; i < imageKeys.Count; i++) { if ((imageKeys[i] != null) || (imageKeys[i].Length != 0)) { CodeMethodInvokeExpression setNameMethodCall = new CodeMethodInvokeExpression(imageListImagesProperty, "SetKeyName", new CodeExpression[] { new CodePrimitiveExpression(i), // SetKeyName(int, new CodePrimitiveExpression(imageKeys[i]) // string); }); ((CodeStatementCollection)codeObject).Add(setNameMethodCall); } } } } } } return(codeObject); }
/// <summary> /// Builds the method. /// </summary> public void Build() { result = new CodeMemberMethod(); result.Name = "InitializeHistoryTypes"; result.Attributes = MemberAttributes.Private; CodeThisReferenceExpression thisReference = new CodeThisReferenceExpression(); CodeFieldReferenceExpression stateField; CodePropertyReferenceExpression historyTypeProperty; CodeTypeReferenceExpression historyType = new CodeTypeReferenceExpression(typeof(HistoryType)); CodeFieldReferenceExpression historyTypeField; CodeAssignStatement historyTypeAssign; foreach (DictionaryEntry entry in stateHistoryTypes) { stateField = new CodeFieldReferenceExpression( thisReference, "state" + entry.Key.ToString()); historyTypeProperty = new CodePropertyReferenceExpression( stateField, "HistoryType"); if (entry.Value.ToString() == string.Empty || entry.Value.ToString() == null) { historyTypeField = new CodeFieldReferenceExpression( historyType, "None"); } else { historyTypeField = new CodeFieldReferenceExpression( historyType, entry.Value.ToString()); } historyTypeAssign = new CodeAssignStatement( historyTypeProperty, historyTypeField); result.Statements.Add(historyTypeAssign); } }
/* * Helper method for building application and session scope injected * properties. If useApplicationState, build application properties, otherwise * build session properties. */ private void BuildObjectPropertiesHelper(IDictionary objects, bool useApplicationState) { IDictionaryEnumerator en = objects.GetEnumerator(); while (en.MoveNext()) { HttpStaticObjectsEntry entry = (HttpStaticObjectsEntry)en.Value; // e.g. (PropType)Session.StaticObjects["PropName"] // Use the appropriate collection CodePropertyReferenceExpression stateObj = new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), useApplicationState ? "Application" : "Session"), "StaticObjects"); CodeMethodInvokeExpression getObject = new CodeMethodInvokeExpression(stateObj, "GetObject"); getObject.Parameters.Add(new CodePrimitiveExpression(entry.Name)); Type declaredType = entry.DeclaredType; Debug.Assert(!Util.IsLateBoundComClassicType(declaredType)); if (useApplicationState) { // for application state use property that does caching in a member BuildInjectedGetPropertyMethod(entry.Name, declaredType, new CodeCastExpression(declaredType, getObject), false /*fPublicProp*/); } else { // for session state use lookup every time, as one application instance deals with many sessions CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = entry.Name; prop.Type = new CodeTypeReference(declaredType); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(declaredType, getObject))); _sourceDataClass.Members.Add(prop); } } }
private void GenerateOverriddenParentReference(IReference input, CodeMemberProperty generatedProperty, ITransformationContext context) { if (input.UpperBound != 1) { throw new ArgumentException("The reference {0}.{1} is a container reference but has an upper bound greather than 1."); } generatedProperty.Type = CreateTypeReference(input, att => generatedProperty.CustomAttributes.Add(att), CreateCollectionInterfaceType, context); generatedProperty.HasGet = true; generatedProperty.HasSet = true; var parentRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Parent"); generatedProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ModelHelper).ToTypeReference()), "CastAs", generatedProperty.Type), parentRef))); generatedProperty.SetStatements.Add(new CodeAssignStatement(parentRef, new CodePropertySetValueReferenceExpression())); GenerateOnParentChangedMethod(input, generatedProperty); }
public Dictionary <IPropertyValueLinkHolder, Dictionary <IPropertyValueLink, CodeExpression> > GetPropertyValueLinks() { Dictionary <IPropertyValueLinkHolder, Dictionary <IPropertyValueLink, CodeExpression> > ret = new Dictionary <IPropertyValueLinkHolder, Dictionary <IPropertyValueLink, CodeExpression> >(); CodePropertyReferenceExpression p1; CodePropertyReferenceExpression p2; Dictionary <IPropertyValueLink, CodeExpression> kv; IPropertyValueLink pl = this.DataSource.TextSource.GetPropertyLink(FILENAME); if (pl != null && pl.IsValueLinkSet()) { p1 = new CodePropertyReferenceExpression(); p1.PropertyName = "TextSource"; p2 = new CodePropertyReferenceExpression(); p1.TargetObject = p2; p2.PropertyName = "DataSource"; p1.UserData.Add("name", FILENAME); kv = new Dictionary <IPropertyValueLink, CodeExpression>(); kv.Add(pl, p1); ret.Add(this.DataSource.TextSource, kv); } // pl = this.DataDestination.TextDestination.GetPropertyLink(FILENAME); if (pl != null && pl.IsValueLinkSet()) { p1 = new CodePropertyReferenceExpression(); p1.PropertyName = "TextDestination"; p2 = new CodePropertyReferenceExpression(); p1.TargetObject = p2; p2.PropertyName = "DataDestination"; p1.UserData.Add("name", FILENAME); kv = new Dictionary <IPropertyValueLink, CodeExpression>(); kv.Add(pl, p1); ret.Add(this.DataDestination.TextDestination, kv); } return(ret); }
private CodeExpression SerializeInstanceDescriptor(IDesignerSerializationManager manager, InstanceDescriptor descriptor) { CodeExpression expression = null; MemberInfo member = descriptor.MemberInfo; CodeExpression target = new CodeTypeReferenceExpression(member.DeclaringType); if (member is PropertyInfo) { expression = new CodePropertyReferenceExpression(target, member.Name); } else if (member is FieldInfo) { expression = new CodeFieldReferenceExpression(target, member.Name); } else if (member is MethodInfo) { CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(target, member.Name); manager.Context.Push(new ExpressionContext(methodInvoke, methodInvoke.GetType(), null, null)); if (descriptor.Arguments != null && descriptor.Arguments.Count > 0) { methodInvoke.Parameters.AddRange(SerializeParameters(manager, descriptor.Arguments)); } manager.Context.Pop(); expression = methodInvoke; } else if (member is ConstructorInfo) { CodeObjectCreateExpression createExpr = new CodeObjectCreateExpression(member.DeclaringType); manager.Context.Push(new ExpressionContext(createExpr, createExpr.GetType(), null, null)); if (descriptor.Arguments != null && descriptor.Arguments.Count > 0) { createExpr.Parameters.AddRange(SerializeParameters(manager, descriptor.Arguments)); } manager.Context.Pop(); expression = createExpr; } return(expression); }
public override CodeExpression ExportCode(IMethodCompile method) { CodeExpression ce; if (IsUTC) { ce = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(DateTime)), "UtcNow"); } else { ce = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(DateTime)), "Now"); } if (ToIsoString) { CodeMethodInvokeExpression cmi = new CodeMethodInvokeExpression(); cmi.Method = new CodeMethodReferenceExpression(ce, "ToString"); cmi.Parameters.Add(new CodePrimitiveExpression("yyyy-MM-dd hh:mm:ss")); cmi.Parameters.Add(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(CultureInfo)), "InvariantCulture")); return(cmi); } return(ce); }
/// <summary> /// Generates the update domain operation entry /// </summary> /// <param name="codeGenContext">The code gen context.></param> /// <param name="businessLogicClass">The business logic class.</param> /// <param name="entity">The entity.</param> protected override void GenerateUpdateMethod(CodeGenContext codeGenContext, CodeTypeDeclaration businessLogicClass, BusinessLogicEntity entity) { string currentParameterName = "current" + entity.ClrType.Name; // public void Update$EntityName$($entityType$ current) CodeMemberMethod method = new CodeMemberMethod(); businessLogicClass.Members.Add(method); LinqToSqlEntity ltsEntity = (LinqToSqlEntity)entity; method.Name = "Update" + CodeGenUtilities.MakeLegalEntityName(entity.Name); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; // final needed to prevent virtual // parameter declaration method.Parameters.Add(new CodeParameterDeclarationExpression(entity.ClrType.Name, currentParameterName)); if (!ltsEntity.HasTimestampMember) { // this.ChangeSet.GetOriginal(current) CodeExpression changeSetRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ChangeSet"); CodeMethodReferenceExpression getOrigMethodRef = new CodeMethodReferenceExpression(changeSetRef, "GetOriginal"); CodeMethodInvokeExpression changeSetGetOrig = new CodeMethodInvokeExpression(getOrigMethodRef, new CodeArgumentReferenceExpression(currentParameterName)); // this.DataContext.$TablePropertyName$.Attach(current, this.ChangeSet.GetOriginal(current)) CodeExpression contextRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "DataContext"); CodeExpression tableRef = new CodePropertyReferenceExpression(contextRef, ltsEntity.TablePropertyName); CodeMethodInvokeExpression attachCall = new CodeMethodInvokeExpression(tableRef, "Attach", new CodeArgumentReferenceExpression(currentParameterName), changeSetGetOrig); method.Statements.Add(attachCall); } else { // this.DataContext.$TablePropertyName$.Attach(current, true) CodeExpression contextRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "DataContext"); CodeExpression tableRef = new CodePropertyReferenceExpression(contextRef, ltsEntity.TablePropertyName); CodeMethodInvokeExpression attachCall = new CodeMethodInvokeExpression(tableRef, "Attach", new CodeArgumentReferenceExpression(currentParameterName), new CodePrimitiveExpression(true)); method.Statements.Add(attachCall); } }
public void ProcessRenderControlMethodTest() { // Create a statement of the following form: // parameterContainer.Controls[0].RenderControl(@__w); // where parameterContainer is a parameter. var container = new CodeArgumentReferenceExpression("parameterContainer"); var controls = new CodePropertyReferenceExpression(container, "Controls"); var indexer = new CodeIndexerExpression(controls, new CodeExpression[] { new CodePrimitiveExpression(defaultIndex) }); var invoke = new CodeMethodInvokeExpression(indexer, "RenderControl", new CodeExpression[] { new CodeArgumentReferenceExpression("__w") }); var stmt = new CodeExpressionStatement(invoke); var renderMethod = new CodeMemberMethod(); var renderMembers = GetRenderMembers(); var buildMembers = GetBuildMembers(); var members = new List <CodeTypeMember>(renderMembers); foreach (var m in buildMembers) { members.Add(m); } SectionControlBuilder.ProcessRenderControlMethod(members, renderMethod, stmt, Language.CSharp); VerifyDefineSection(((CodeMemberMethod)renderMembers[0]).Statements[0], renderMethod.Statements.OfType <CodeStatement>().ToList()); }
public override void GenerateSignals(IDLInterface idlIntf) { if (idlIntf.Signals != null && idlIntf.Signals.Count > 0) // If got signals { bAddNamespace = true; foreach (IDLSignal idlSignal in idlIntf.Signals) { // Signal. // * public System.EventHandler< <signal>Args > <signal> // * { // * get { return this.proxy.<signal>; } // * set { this.proxy.<signal> = value; } // * } CodeMemberProperty propSignal = CodeBuilderCommon.CreateSignalEventProperty(idlSignal); propSignal.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodePropertyReferenceExpression proprefProxySignal = new CodePropertyReferenceExpression(thisProxyFieldRef, propSignal.Name); propSignal.GetStatements.Add(new CodeMethodReturnStatement(proprefProxySignal)); propSignal.SetStatements.Add(new CodeAssignStatement(proprefProxySignal, new CodePropertySetValueReferenceExpression())); typeProxy.Members.Add(propSignal); } // Ends loop over signal } // Ends if got signals }
private void BuildApplicationInstanceProperty() { CodeMemberProperty property; Type globalAsaxType = BuildManager.GetGlobalAsaxType(); property = new CodeMemberProperty { Attributes = property.Attributes & ~MemberAttributes.AccessMask, Attributes = property.Attributes & ~MemberAttributes.ScopeMask, Attributes = property.Attributes | (MemberAttributes.Family | MemberAttributes.Final) }; if (base._designerMode) { base.ApplyEditorBrowsableCustomAttribute(property); } property.Name = "ApplicationInstance"; property.Type = new CodeTypeReference(globalAsaxType); CodePropertyReferenceExpression targetObject = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Context"); targetObject = new CodePropertyReferenceExpression(targetObject, "ApplicationInstance"); property.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(globalAsaxType, targetObject))); base._intermediateClass.Members.Add(property); }
/// <summary> /// Serializes a series of SetChildIndex() statements for each control iln a child control collection in /// reverse order. /// </summary> private void SerializeZOrder(IDesignerSerializationManager manager, CodeStatementCollection statements, Control control) { using (TraceScope("ControlCodeDomSerializer::SerializeZOrder()")) { // Push statements in reverse order so the first guy in the // collection is the last one to be brought to the front. for (int i = control.Controls.Count - 1; i >= 0; i--) { // Only serialize this control if it is (a) sited and // (b) not being privately inherited Control child = control.Controls[i]; if (child.Site is null || child.Site.Container != control.Site.Container) { continue; } InheritanceAttribute attr = (InheritanceAttribute)TypeDescriptor.GetAttributes(child)[typeof(InheritanceAttribute)]; if (attr.InheritanceLevel == InheritanceLevel.InheritedReadOnly) { continue; } // Create the "control.Controls.SetChildIndex" call CodeExpression controlsCollection = new CodePropertyReferenceExpression(SerializeToExpression(manager, control), "Controls"); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(controlsCollection, "SetChildIndex"); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); methodInvoke.Method = method; // Fill in parameters CodeExpression childControl = SerializeToExpression(manager, child); methodInvoke.Parameters.Add(childControl); methodInvoke.Parameters.Add(SerializeToExpression(manager, 0)); CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); statements.Add(statement); } } }
protected virtual void FixTestRunOrderingIssue(TestClassGenerationContext generationContext) { //see https://github.com/techtalk/SpecFlow/issues/96 //if (testRunner.FeatureContext != null && testRunner.FeatureContext.FeatureInfo.Title != "<current_feature_title>") // <TestClass>.<TestClassInitialize>(null); var featureContextExpression = new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(null, generationContext.TestRunnerField.Name), "FeatureContext"); var callTestClassInitializeMethodExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression( new CodeTypeReference( generationContext.Namespace.Name + "." + generationContext.TestClass.Name, CodeTypeReferenceOptions.GlobalReference)), generationContext.TestClassInitializeMethod.Name, new CodePrimitiveExpression(null)); CodeDomHelper.MarkCodeMethodInvokeExpressionAsAwait(callTestClassInitializeMethodExpression); generationContext.TestInitializeMethod.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( featureContextExpression, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( featureContextExpression, "FeatureInfo"), "Title"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(generationContext.Feature.Name))), new CodeExpressionStatement( callTestClassInitializeMethodExpression))); }
/// <summary> /// Serializes a specific property to code. /// </summary> /// <param name="instanceHolder">The parent expression that holds the instance.</param> /// <param name="instance">The instance to take away the values from.</param> /// <param name="property">The property to serialize.</param> /// <returns>A collection of code statements initiating the given property of the given object to its value.</returns> public CodeStatementCollection SerializeProperty(CodeExpression instanceHolder, object instance, PropertyDescriptor property) { CodeStatementCollection statements = new CodeStatementCollection(); var propertyExpression = new CodePropertyReferenceExpression( instanceHolder, property.Name); object propertyValue = property.GetValue(instance); if (property.PropertyType.HasInterface(typeof(ICollection))) { // If collection, create property.Add(...) statements. statements.AddRange(CreateCollectionInitialization(propertyExpression, instance, property)); } else if (CodeDomTypeFormatter.IsFormattableWithAssignment(property.PropertyType)) { // else, create normal property = value statement. statements.Add(CreatePropertyAssignmentExpression(propertyExpression, instance, property)); } if (!CodeDomTypeFormatter.IsFormattableWithAssignment(property.PropertyType)) { // serialize child properties. if (property.PropertyType.IsValueType) { // value types uses a temp var.to access properties. statements.AddRange(CreateValueTypeInitialization(propertyExpression, instance, property)); } else { // access properties directly. statements.AddRange(SerializeProperties(propertyExpression, propertyValue)); } } return(statements); }
private void ImplementIXmlSerializable() { string interfaceName = "IXmlSerializable"; string typeManagerName = NameGenerator.GetServicesClassName(); string methodName = string.Concat(this.clrTypeInfo.clrtypeName, "SchemaProvider"); CodeMemberMethod schemaProviderMethod = CodeDomHelper.CreateMethod(methodName, MemberAttributes.Abstract | MemberAttributes.Final | MemberAttributes.Static | MemberAttributes.FamilyAndAssembly | MemberAttributes.FamilyOrAssembly | MemberAttributes.Public, null); schemaProviderMethod.Parameters.Add(new CodeParameterDeclarationExpression("XmlSchemaSet", "schemas")); CodeStatementCollection statements = schemaProviderMethod.Statements; CodeTypeReferenceExpression codeTypeReferenceExpression = new CodeTypeReferenceExpression(typeManagerName); CodeExpression[] codeVariableReferenceExpression = new CodeExpression[] { new CodeVariableReferenceExpression("schemas") }; statements.Add(CodeDomHelper.CreateMethodCall(codeTypeReferenceExpression, "AddSchemas", codeVariableReferenceExpression)); codeVariableReferenceExpression = new CodeExpression[] { new CodePrimitiveExpression(this.clrTypeInfo.schemaName), new CodePrimitiveExpression(this.clrTypeInfo.schemaNs) }; CodeExpression qNameExp = new CodeObjectCreateExpression("XmlQualifiedName", codeVariableReferenceExpression); if (this.clrTypeInfo.typeOrigin != SchemaOrigin.Element) { schemaProviderMethod.ReturnType = new CodeTypeReference("XmlQualifiedName"); schemaProviderMethod.Statements.Add(new CodeMethodReturnStatement(qNameExp)); } else { CodeStatementCollection codeStatementCollection = schemaProviderMethod.Statements; CodePropertyReferenceExpression codePropertyReferenceExpression = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("schemas"), "GlobalElements"); codeVariableReferenceExpression = new CodeExpression[] { qNameExp }; codeStatementCollection.Add(new CodeVariableDeclarationStatement("XmlSchemaElement", "element", new CodeCastExpression("XmlSchemaElement", new CodeIndexerExpression(codePropertyReferenceExpression, codeVariableReferenceExpression)))); CodeStatementCollection statements1 = schemaProviderMethod.Statements; CodeBinaryOperatorExpression codeBinaryOperatorExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("element"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); CodeStatement[] codeMethodReturnStatement = new CodeStatement[] { new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("element"), "ElementSchemaType")) }; statements1.Add(new CodeConditionStatement(codeBinaryOperatorExpression, codeMethodReturnStatement)); schemaProviderMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); schemaProviderMethod.ReturnType = new CodeTypeReference("XmlSchemaType"); } this.decl.CustomAttributes.Add(CodeDomHelper.SchemaProviderAttribute(this.clrTypeInfo.clrtypeName)); this.decl.BaseTypes.Add(interfaceName); this.decl.Members.Add(schemaProviderMethod); }
private static CodeExpression CreateRestrictionInitializers(IEnumerable <KeyValuePair <string, IRouteParameterType> > routeParameters, CodeExpression parameterConstantsType, CodeExpression expression) { foreach (var routeParameter in routeParameters) { if (!routeParameter.Value.RequiresRestriction) { continue; } var propertyRef = new CodePropertyReferenceExpression(parameterConstantsType, routeParameter.Key); var restrict = new CodeMethodInvokeExpression(expression, "Restrict", propertyRef); if (routeParameter.Value is StringRouteParameterType) { var stringRouteParameterType = (StringRouteParameterType)routeParameter.Value; var expressions = new List <CodeExpression>(); foreach (var choice in stringRouteParameterType.anyOf) { expressions.Add(new CodePrimitiveExpression(choice)); } expression = new CodeMethodInvokeExpression(restrict, "AnyOf", expressions.ToArray()); } else if (routeParameter.Value is GuidRouteParameterType) { expression = new CodePropertyReferenceExpression(restrict, "ValidGuid"); } else if (routeParameter.Value is IntRouteParameterType) { expression = new CodePropertyReferenceExpression(restrict, "ValidInteger"); } } return(expression); }
public CodeExpression ParseExpression() { CodeExpression currentValue = ParseBaseExpression(); while (TokenType == CDILToken.Dot) { GetNextToken(); string name = EatKeyword(); if (TokenType == CDILToken.LeftParen) { CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(currentValue, name); GetNextToken(); while (TokenType != CDILToken.RightParen && TokenType != CDILToken.EOF) { CodeExpression expr = ParseExpression(); methodInvoke.Parameters.Add(expr); if (TokenType == CDILToken.Comma) { GetNextToken(); } } Expect(CDILToken.RightParen); currentValue = methodInvoke; continue; } else if (TokenType == CDILToken.Dollar) { GetNextToken(); currentValue = new CodeFieldReferenceExpression(currentValue, name); continue; } else { currentValue = new CodePropertyReferenceExpression(currentValue, name); } } return(currentValue); }
protected virtual Rule CreateRule2(string expressionKey, FilterExpressionNodeCollection filters) { Rule rule = new Rule(); rule.Active = true; //Mediachase.Web.Console.Providers.DomParser string expr = ConvertNodesToStringExpression(filters); RuleExpressionCondition conditionExpr = new RuleExpressionCondition(); if (!String.IsNullOrEmpty(expr)) { Parser p = new Parser(); conditionExpr.Expression = p.ParseExpression(expr); rule.Name = expressionKey; } else { CodePrimitiveExpression truePrimitive = new CodePrimitiveExpression(true); conditionExpr.Expression = truePrimitive; rule.Name = "AlwaysTrue"; } rule.Condition = conditionExpr; rule.Priority = 9999; //Nust be first evaluate rule.ReevaluationBehavior = RuleReevaluationBehavior.Never; // Create succeeded assignment // this.ValidationResult.IsValid = True CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression(); CodePropertyReferenceExpression resultRef = new CodePropertyReferenceExpression(thisRef, "ValidationResult"); CodePropertyReferenceExpression validRef = new CodePropertyReferenceExpression(resultRef, "IsValid"); CodeAssignStatement ruleIsValidAction = new CodeAssignStatement(validRef, new CodePrimitiveExpression(true)); rule.ThenActions.Add(new RuleStatementAction(ruleIsValidAction)); return(rule); }
private static bool IsWellKnownApplicationSettingsExpression(CodePropertyReferenceExpression expression) { if ((expression.UserData != null) && (expression.UserData.Count > 0)) { return(false); } if (!(expression.TargetObject is CodePropertyReferenceExpression)) { return(false); } CodePropertyReferenceExpression targetObject = (CodePropertyReferenceExpression)expression.TargetObject; if ((targetObject.UserData != null) && (targetObject.UserData.Count > 0)) { return(false); } if (!(targetObject.TargetObject is CodeTypeReferenceExpression)) { return(false); } CodeTypeReferenceExpression expression3 = (CodeTypeReferenceExpression)targetObject.TargetObject; if ((expression3.UserData != null) && (expression3.UserData.Count > 0)) { return(false); } CodeTypeReference type = expression3.Type; if ((type.UserData != null) && (type.UserData.Count > 0)) { return(false); } if ((type.TypeArguments != null) && (type.TypeArguments.Count > 0)) { return(false); } return((type.ArrayElementType == null) && (type.ArrayRank <= 0)); }
public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments) { if (!arguments.TryGetValue("name", out string name) || string.IsNullOrEmpty(name)) { throw new DirectiveProcessorException("Codeblockmanager directive has no name argument"); } var thisRef = new CodeThisReferenceExpression(); var typeRef = new CodeTypeReference(typeof(T4.CodeBlockManager)); // create field for code block manager object string fieldName = "_" + name + "Field"; var fieldRef = new CodeFieldReferenceExpression(thisRef, fieldName); members.Add(new CodeMemberField(typeRef, fieldName)); // create property for code block manager with creation of object on first use. var property = new CodeMemberProperty() { Name = name, Attributes = MemberAttributes.Public | MemberAttributes.Final, HasGet = true, HasSet = false, Type = typeRef }; var hostRef = new CodePropertyReferenceExpression(thisRef, "Host"); var generationEnvironmentRef = new CodePropertyReferenceExpression(thisRef, "GenerationEnvironment"); var statement = new CodeConditionStatement( IsNull(fieldRef), new CodeAssignStatement(fieldRef, new CodeObjectCreateExpression(typeRef, hostRef, generationEnvironmentRef))); property.GetStatements.Add(statement); property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); members.Add(property); }
public override object Deserialize(IDesignerSerializationManager manager, object codeObject) { CodeStatementCollection collection = codeObject as CodeStatementCollection; if (collection != null) { foreach (CodeStatement statement in collection) { CodeAssignStatement codeAssignment = statement as CodeAssignStatement; if (codeAssignment != null) { CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression; CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression; if (properyRef != null && properyRef.PropertyName == "Value" && primitiveExpression != null && primitiveExpression.Value != null) { primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value); break; } } } } return(base.Deserialize(manager, codeObject)); }
private void ValidatePropertyReferenceExpression(CodePropertyReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.PropertyName), e.PropertyName); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // namespace Foo { // public class Foo { // // public int _verifyGlobalGeneration1 = 2147483647; // // public int System { // get { return 42; } // } // // public int Property { // get { return 2147483647; } // } // // public int GlobalTestProperty1 { // get { // return _verifyGlobalGeneration1; // } // set { // _verifyGlobalGeneration1 = value; // } // } // // public global::System.Nullable<int> GlobalTestProperty2 { // get { // return _verifyGlobalGeneration2; // } // set { // _verifyGlobalGeneration2 = value; // } // } // // // public int TestMethod02() { // int iReturn; // iReturn = global::Foo.Foo.Property; // return iReturn; // } // // public int TestMethod03() { // int iReturn; // iReturn = global::System.Math.Abs(-1); // return iReturn; // } // // public int TestMethod04() { // int iReturn; // iReturn = System; // return iReturn; // } // } CodeNamespace ns = new CodeNamespace ("Foo"); ns.Comments.Add (new CodeCommentStatement ("Foo namespace")); cu.Namespaces.Add (ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("Foo"); ns.Types.Add (cd); CodeMemberProperty property = new CodeMemberProperty (); property.Name = "System"; property.Attributes = MemberAttributes.Public; property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static; property.Type = new CodeTypeReference (typeof (int)); property.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (42))); cd.Members.Add (property); property = new CodeMemberProperty (); property.Name = "Property"; property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static; property.Type = new CodeTypeReference (typeof (int)); property.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (Int32.MaxValue))); cd.Members.Add (property); AddScenario ("CallTestMethod02", "Call Foo.Foo.TestMethod02."); CodeMemberMethod method2 = new CodeMemberMethod (); method2.Name = "TestMethod02"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method2.ReturnType = new CodeTypeReference (typeof (int)); method2.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn")); CodePropertyReferenceExpression cpr = new CodePropertyReferenceExpression ( new CodeTypeReferenceExpression (new CodeTypeReference ("Foo.Foo", CodeTypeReferenceOptions.GlobalReference)), "Property"); CodeAssignStatement cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cpr); method2.Statements.Add (cas); method2.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn"))); cd.Members.Add (method2); AddScenario ("CallTestMethod03", "Call Foo.Foo.TestMethod02."); CodeMemberMethod method3 = new CodeMemberMethod (); method3.Name = "TestMethod03"; method3.Attributes = (method3.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method3.ReturnType = new CodeTypeReference (typeof (int)); method3.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn")); CodeTypeReferenceOptions ctro = CodeTypeReferenceOptions.GlobalReference; CodeTypeReference ctr = new CodeTypeReference (typeof (Math), ctro); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression ( new CodeTypeReferenceExpression (ctr), "Abs"), new CodeExpression[] { new CodePrimitiveExpression (-1) }); cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cmie); method3.Statements.Add (cas); method3.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn"))); cd.Members.Add (method3); AddScenario ("CallTestMethod04", "Call Foo.Foo.TestMethod04."); CodeMemberMethod method4 = new CodeMemberMethod (); method4.Name = "TestMethod04"; method4.Attributes = (method4.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method4.ReturnType = new CodeTypeReference (typeof (int)); method4.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn")); cpr = new CodePropertyReferenceExpression (null, "System"); cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cpr); method4.Statements.Add (cas); method4.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn"))); cd.Members.Add (method4); // Verify that what CodeTypeReferenceOptions are correctly set. // Basically this check gives the code coverage for the get property AddScenario ("CTR_GetGlobalRefCheck", "Check that CodeTypeReference.Options gives the proper value."); if (ctr.Options == CodeTypeReferenceOptions.GlobalReference) VerifyScenario ("CTR_GetGlobalRefCheck"); // one-off generate statements StringWriter sw = new StringWriter (); // global shouldn't be generated in this instance CodeTypeReference variableType = new CodeTypeReference (typeof (System.String), CodeTypeReferenceOptions.GlobalReference); CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement (variableType, "myVariable"); provider.GenerateCodeFromStatement (variable, sw, null); // global should be generated in this instance CodeTypeReference variableType2 = new CodeTypeReference (typeof (System.Array), CodeTypeReferenceOptions.GlobalReference); CodeVariableDeclarationStatement variable2 = new CodeVariableDeclarationStatement (variableType2, "myVariable2"); provider.GenerateCodeFromStatement (variable2, sw, null); AddScenario ("GlobalKeywordShouldExist", "When an array is referred to, a global qualifier should be generated on it."); if (sw.ToString ().IndexOf ("global") != -1 && sw.ToString ().IndexOf ("Global") != -1) { LogMessage ("Global keyword does not exist in statement: " + sw.ToString ()); } else VerifyScenario ("GlobalKeywordShouldExist"); } }
protected abstract void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e);
public void Visit(CodePropertyReferenceExpression o) { g.GeneratePropertyReferenceExpression(o); }
protected override void GeneratePropertyReferenceExpression (CodePropertyReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.PropertyName); }