public override object Serialize(IDesignerSerializationManager manager, object value) { ViewStyle viewStyle = (ViewStyle)value; CodeDomSerializer baseClassSerializer = (CodeDomSerializer)manager.GetSerializer(value.GetType().BaseType, typeof(CodeDomSerializer)); object codeObject = baseClassSerializer.Serialize(manager, value); if (codeObject is CodeStatementCollection) { CodeStatementCollection statements = (CodeStatementCollection)codeObject; ArrayList dontSerializeList = new ArrayList(); //--- loop through all statements foreach (CodeStatement st in statements) { if (st is CodeAssignStatement) { CodeAssignStatement cAssign = (CodeAssignStatement)st; // If left is eg. 'this.ViewStyle.BorderColor' if (cAssign.Left is CodePropertyReferenceExpression) { string propertyName = ((CodePropertyReferenceExpression)cAssign.Left).PropertyName; object propertyValue = null; // If right is eg. 'System.Drawing.Color.FromArgb(183,193,214)' if (cAssign.Right is CodeMethodInvokeExpression) { CodeMethodInvokeExpression mInvokeExp = (CodeMethodInvokeExpression)cAssign.Right; if (mInvokeExp.Method.MethodName == "FromArgb") { CodeCastExpression cCastExpR = (CodeCastExpression)mInvokeExp.Parameters[0]; CodeCastExpression cCastExpG = (CodeCastExpression)mInvokeExp.Parameters[1]; CodeCastExpression cCastExpB = (CodeCastExpression)mInvokeExp.Parameters[2]; int r = Convert.ToInt32(((CodePrimitiveExpression)cCastExpR.Expression).Value); int g = Convert.ToInt32(((CodePrimitiveExpression)cCastExpG.Expression).Value); int b = Convert.ToInt32(((CodePrimitiveExpression)cCastExpB.Expression).Value); propertyValue = Color.FromArgb(r, g, b); } } // If right is eg. 'System.Drawing.Color.Lime' if (cAssign.Right is CodePropertyReferenceExpression) { CodePropertyReferenceExpression propRefExp = (CodePropertyReferenceExpression)cAssign.Right; CodeTypeReferenceExpression tRefExp = (CodeTypeReferenceExpression)propRefExp.TargetObject; if (tRefExp.Type.BaseType == "System.Drawing.Color" || tRefExp.Type.BaseType == "System.Drawing.SystemColors") { propertyValue = Color.FromName(propRefExp.PropertyName); } } if (cAssign.Right is CodeFieldReferenceExpression) { CodeFieldReferenceExpression fRefExp = (CodeFieldReferenceExpression)cAssign.Right; if (fRefExp.FieldName == "FullSelect") { propertyValue = VRS.UI.Controls.WOutlookBar.ItemsStyle.FullSelect; } if (fRefExp.FieldName == "IconSelect") { propertyValue = VRS.UI.Controls.WOutlookBar.ItemsStyle.IconSelect; } if (fRefExp.FieldName == "UseDefault") { propertyValue = VRS.UI.Controls.WOutlookBar.ItemsStyle.UseDefault; } } //--- Check if we need to serialize property. if (!viewStyle.MustSerialize(propertyName, propertyValue)) { // Add to remove list dontSerializeList.Add(st); } } } } // Remove not neede properties foreach (CodeStatement obj in dontSerializeList) { statements.Remove(obj); } } return(codeObject); }
//} // StateMachineHelper.ProcessTransitionBegin<DoorContext, DoorContext, StateTop>(context, StateNext.Instance); // or // StateMachineHelper.ProcessTransitionEnd<DoorContext, DoorContext, StateTop>(context, StateNext.Instance); protected void WriteProcessTransition(CodeStatementCollection statements, StateType state, string nextStateName, string suffix) { CodeExpression[] paramsRef; StateType stateNext = Model.GetStateType(nextStateName); string stateTopClassName; string contextClassName; string contextParentClassName; // context or context.ContextParent or context.ContextParent.ContextParent .... depending where is stateNext compared to state. var contextExpression = GetContextParentExpression(state, stateNext); if (stateNext == null) { //Internal transition paramsRef = new CodeExpression[] { contextExpression, new CodePrimitiveExpression(null) }; stateTopClassName = GetStateClassName(Model.GetStateTop(state)); contextClassName = GetContextClassName(state); contextParentClassName = GetContextParentClassName(state); } else { CodeExpression nextStateExpression; if (stateNext.Type.HasFlag(StateType.TypeFlags.HISTORY)) { // context.StateHistory nextStateExpression = new CodeFieldReferenceExpression( new CodeVariableReferenceExpression(Model.settings.context.instance), "StateHistory"); } else { StateType stateLeaf = Model.GetStateLeaf(stateNext); // NextState.Instance nextStateExpression = new CodeFieldReferenceExpression( new CodeVariableReferenceExpression(GetStateClassName(stateLeaf)), "Instance"); } stateTopClassName = GetStateClassName(Model.GetStateTop(stateNext)); contextClassName = GetContextClassName(stateNext); contextParentClassName = GetContextParentClassName(stateNext); paramsRef = new CodeExpression[] { contextExpression, nextStateExpression }; } // param StateRunning.Instance var onMethodInvoke = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("StateMachineHelper"), "ProcessTransition" + suffix, new CodeTypeReference[] { new CodeTypeReference(contextClassName), new CodeTypeReference(contextParentClassName), new CodeTypeReference((stateTopClassName)) }), paramsRef); statements.Add(onMethodInvoke); }
public static void GenerateRepositoryUpdateObjectMethod(IClassMap classMap, CodeTypeDeclaration classDecl) { IList propertyMaps = classMap.GetAllPropertyMaps(); IList idPropertyMaps = classMap.GetIdentityPropertyMaps(); CodeMemberMethod methodMember = new CodeMemberMethod(); methodMember.Name = GetRepositoryUpdateObjectMethodName(classMap); CodeTypeReference typeReference = new CodeTypeReference(classMap.GetName()); methodMember.ReturnType = typeReference; methodMember.Attributes = MemberAttributes.Public; foreach (IPropertyMap propertyMap in propertyMaps) { if (!propertyMap.IsCollection) { CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference(propertyMap.DataType), MakeCamelCase(propertyMap.Name)); methodMember.Parameters.Add(parameter); } } CodeThisReferenceExpression thisExp = new CodeThisReferenceExpression(); CodeFieldReferenceExpression contextVar = new CodeFieldReferenceExpression(thisExp, "context"); CodeExpression[] createParams = new CodeExpression[idPropertyMaps.Count]; int i = 0; foreach (IPropertyMap idPropertyMap in idPropertyMaps) { CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression(MakeCamelCase(idPropertyMap.Name)); createParams[i] = argExp; i++; } CodeMethodInvokeExpression newObjectInit = new CodeMethodInvokeExpression(thisExp, GetRepositoryGetByIdentityMethodName(classMap), createParams); CodeVariableDeclarationStatement newObjectVarDecl = new CodeVariableDeclarationStatement(classMap.GetName(), MakeCamelCase(classMap.GetName()), newObjectInit); CodeVariableReferenceExpression newObjectVar = new CodeVariableReferenceExpression(MakeCamelCase(classMap.GetName())); methodMember.Statements.Add(newObjectVarDecl); foreach (IPropertyMap propertyMap in propertyMaps) { if (!propertyMap.IsIdentity) { if (!propertyMap.IsCollection) { CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression(MakeCamelCase(propertyMap.Name)); CodeVariableReferenceExpression propExp = new CodeVariableReferenceExpression(MakeCamelCase(classMap.Name) + "." + propertyMap.Name); CodeAssignStatement assignStatement = new CodeAssignStatement(propExp, argExp); methodMember.Statements.Add(assignStatement); } } } CodeMethodInvokeExpression commitCtx = new CodeMethodInvokeExpression(contextVar, "Commit", new CodeExpression[] {}); methodMember.Statements.Add(commitCtx); CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(newObjectVar); methodMember.Statements.Add(returnStmt); classDecl.Members.Add(methodMember); }
private void ValidateFieldReferenceExpression(CodeFieldReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.FieldName), e.FieldName); }
// TODO: Convert some internal parameters to members? public string GenerateCode(string codeNamespace, MessageData messages, string className) { this.defaultNamespace = codeNamespace; this.className = className; // We use "string" so much that we have a common reference... CodeTypeReference stringRef = new CodeTypeReference(typeof(string)); CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace cns = new CodeNamespace(codeNamespace); cns.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclarationCollection types = cns.Types; compileUnit.Namespaces.Add(cns); CodeTypeDeclaration theClass = new CodeTypeDeclaration(className); CodeTypeReference theClassRef = new CodeTypeReference(new CodeTypeParameter(className)); theClass.IsClass = true; theClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; types.Add(theClass); theClass.Comments.Add( new CodeCommentStatement( string.Format( "<summary>{0} generated messages class.</summary>", className), true)); theClass.Comments.Add( new CodeCommentStatement( "<remarks>To change any behavior in this class, the code generator will need to change.</remarks>", true)); CodeMethodReferenceExpression resManGetString = this.CreateResourceManager(theClass); CodeFieldReferenceExpression resCultureRef = this.CreateResourceCulture(theClass); // Add the message types (error, warning, verbose...) string messageTypeName = string.Concat(className, "Type"); CodeTypeDeclaration messageTypes = new CodeTypeDeclaration(messageTypeName); messageTypes.IsEnum = true; messageTypes.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; theClass.Members.Add(messageTypes); messageTypes.Comments.Add( new CodeCommentStatement( "<summary>The allowable types of messages.</summary>", true)); messageTypes.Comments.Add( new CodeCommentStatement( "<remarks>To change this list, add 'type' lines to your source file.</remarks>", true)); CodeTypeReferenceExpression messageTypeRef = new CodeTypeReferenceExpression(messageTypeName); Dictionary <MessageType, CodeFieldReferenceExpression> typeReferences = new Dictionary <MessageType, CodeFieldReferenceExpression>(); foreach (MessageType sourceMessageType in messages.Types) { CodeMemberField typeField = new CodeMemberField(); // We capitalize the message type's first letter for the code. typeField.Name = string.Concat( sourceMessageType.Name[0].ToString().ToUpperInvariant(), sourceMessageType.Name.Substring(1)); messageTypes.Members.Add(typeField); typeField.Comments.Add( new CodeCommentStatement( string.Format( "<summary>'{0}' message range: {1}-{2}</summary>", sourceMessageType.Name, sourceMessageType.FirstId, sourceMessageType.LastId), true)); typeReferences.Add(sourceMessageType, new CodeFieldReferenceExpression(messageTypeRef, typeField.Name)); } CodeConstructor classConstructor = new CodeConstructor(); classConstructor.Attributes = MemberAttributes.Private; theClass.Members.Add(classConstructor); // Add the members and private constructor... this.CreateProperty(theClass, classConstructor, "Type", new CodeTypeReference(messageTypeName), "Gets the type (error/warning/verbose) of the message"); this.CreateProperty(theClass, classConstructor, "Id", new CodeTypeReference(typeof(int)), "Gets the ID of the message."); this.CreateProperty(theClass, classConstructor, "Name", stringRef, "Gets the name of the message."); this.CreateProperty(theClass, classConstructor, "Message", stringRef, "Get the message text for the message."); foreach (var message in messages.Messages) { if (message.Type == null) { // TODO: throw an error? Skip? continue; } CodeFieldReferenceExpression messageType = typeReferences[message.Type]; foreach (var instance in message.Instances) { CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final; // final == non-virtual? method.ReturnType = theClassRef; method.Name = message.Name; method.LinePragma = new CodeLinePragma(messages.Filename, instance.PragmaLine); theClass.Members.Add(method); string messageVarName = "message"; // Ensure we don't have any variable name collisions... if (instance.ParameterList.Count > 0) { messageVarName = "messageFormat"; string messageVarNameBase = messageVarName; int suffixCount = 1; while (instance.ParameterList.Any(t => string.Equals(t.Item1, messageVarName, StringComparison.Ordinal))) { messageVarName = string.Concat(messageVarNameBase, (++suffixCount).ToString()); } } ////// TODO: Inject an error if there was an error in the source file? ////// This would help avoid missing these errors in a command-line scenario... ////if (!string.IsNullOrEmpty(message.Error)) ////{ //// method.Statements.Add(new CodePrimitiveExpression("ERROR!")); //// method.Statements.Add(new CodePrimitiveExpression(message.Error)); //// method.Statements.Add(new CodePrimitiveExpression("ERROR!")); ////} ////// TODO: Inject an error if there was an error in the source file? ////// This would help avoid missing these errors in a command-line scenario... ////if (!string.IsNullOrEmpty(instance.Error)) ////{ //// method.Statements.Add(new CodePrimitiveExpression("ERROR!")); //// method.Statements.Add(new CodePrimitiveExpression(instance.Error)); //// method.Statements.Add(new CodePrimitiveExpression("ERROR!")); ////} // Get the string from the generated resources... method.Statements.Add( new CodeVariableDeclarationStatement( stringRef, messageVarName, new CodeMethodInvokeExpression( resManGetString, new CodePrimitiveExpression(string.Concat(this.className, ".", instance.Name)), resCultureRef))); // Default the return expression to just the message itself. CodeExpression messageExpression = new CodeVariableReferenceExpression(messageVarName); // If we've got parameterList, we need a more complex expression. if (instance.ParameterList.Count > 0) { List <CodeExpression> formatParameters = new List <CodeExpression>(); formatParameters.Add(messageExpression); instance.ParameterList.ForEach(t => { method.Parameters.Add( new CodeParameterDeclarationExpression( new CodeTypeReference(t.Item2), t.Item1)); formatParameters.Add(new CodeVariableReferenceExpression(t.Item1)); }); messageExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(stringRef), "Format", formatParameters.ToArray()); } method.Statements.Add(new CodeMethodReturnStatement( new CodeObjectCreateExpression( theClassRef, messageType, // type new CodePrimitiveExpression(message.Id), // id new CodePrimitiveExpression(message.Name), // name messageExpression))); // message } } // Create the code... string output = null; using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp")) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; using (StringWriter sourceWriter = new StringWriter()) { provider.GenerateCodeFromCompileUnit(compileUnit, sourceWriter, options); output = sourceWriter.ToString(); } } return(output); }
private static void CreateConstructorFromTable(CodeTypeDeclaration classType, TableInfo tableInfo, CodeGenerationInfo generationInfo) { var cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public; cc.Name = tableInfo.TableName; cc.Parameters.Add(generationInfo.ReaderNamespace, "itable&", "table"); //cc.BaseConstructorArgs.Add("table"); //cc.AddConstructorStatement(string.Format("{0}(table)", CodeGenerationInfo.CremaTableName)); // verify hashValue { var css = CreateCompareTypeStatement(classType, tableInfo, generationInfo); var tst = CremaDataClassCreator.CreateTryCatchStatement(classType, css, generationInfo); cc.Statements.Add(css); } { var table = new CodeVariableReferenceExpression("table"); var dataSet = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(table, "dataset")); var tables = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(dataSet, "tables")); foreach (var item in generationInfo.GetChilds(tableInfo)) { var tableName = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(table, "name")); var childName = new CodeBinaryOperatorExpression(tableName, CodeBinaryOperatorType.Add, new CodePrimitiveExpression("." + item.TableName)); var childTable = new CodeIndexerExpression(tables, childName); var childField = new CodeFieldReferenceExpression(thisRef, item.TableName); var instance = new CodeObjectCreateExpression(item.GetCodeType(CodeType.None), childTable); cc.Statements.AddAssign(childField, instance); //cc.AddConstructorStatement(string.Format("{0}(table.dataset().tables()[\"{1}\"])", item.GetFieldName(), item.GetUniqueName())); } } { var table = new CodeVariableReferenceExpression("table"); var readFromFile = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "ReadFromTable"); var methodInvoke = new CodeMethodInvokeExpression(readFromFile, table); cc.Statements.Add(methodInvoke); } // SetRelations { var table = new CodeVariableReferenceExpression("table"); foreach (var item in generationInfo.GetChilds(tableInfo)) { var setRelations = new CodeMethodReferenceExpression(thisRef, "SetRelations"); var field = new CodeFieldPointerExpression(thisRef, item.TableName); var rows = new CodePropertyReferenceExpression(field, "Rows"); var codeTypeRef = new CodeTypeReferenceExpression(tableInfo.GetRowCodeType(CodeType.None)); var setChildAction = new CodePropertyReferenceExpression(null, tableInfo.TableName + "Set" + item.TableName); var tableName = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(table, "name")); var childName = new CodeBinaryOperatorExpression(tableName, CodeBinaryOperatorType.Add, new CodePrimitiveExpression("." + item.TableName)); var setRelationsInvoke = new CodeMethodInvokeExpression(setRelations, childName, rows, setChildAction); cc.Statements.Add(setRelationsInvoke); } } classType.Members.Add(cc); }
public CodeTypeDeclaration GenerateClass(Generator g, CodeTypeDeclaration libDecl, string libFieldName) { var decl = new CodeTypeDeclaration (Name); decl.IsPartial = true; if (BaseClasses.Count > 0) decl.BaseTypes.Add (new CodeTypeReference (BaseClasses [0].Name)); else decl.BaseTypes.Add (new CodeTypeReference ("ICppObject")); bool hasBase = BaseClasses.Count > 0; var layout = new CodeTypeDeclaration ("_" + Name); layout.IsStruct = true; layout.TypeAttributes = TypeAttributes.NotPublic; decl.Members.Add (layout); foreach (var f in Fields) { CodeMemberField field = new CodeMemberField { Name = f.Name, Type = g.CppTypeToCodeDomType (f.Type) }; layout.Members.Add (field); } var iface = new CodeTypeDeclaration ("I" + Name); iface.IsInterface = true; layout.TypeAttributes = TypeAttributes.NotPublic; iface.BaseTypes.Add (new CodeTypeReference ("ICppClassOverridable", new CodeTypeReference [] { new CodeTypeReference (decl.Name) })); decl.Members.Add (iface); var layoutField = new CodeMemberField (new CodeTypeReference (typeof (Type)), "native_layout"); layoutField.Attributes = MemberAttributes.Private|MemberAttributes.Static; layoutField.InitExpression = new CodeTypeOfExpression (layout.Name); decl.Members.Add (layoutField); var implField = new CodeMemberField (new CodeTypeReference (iface.Name), "impl"); implField.Attributes = MemberAttributes.Private|MemberAttributes.Static; var getclass = new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (libDecl.Name), libFieldName), "GetClass", new CodeTypeReference [] { new CodeTypeReference (iface.Name), new CodeTypeReference (layout.Name), new CodeTypeReference (decl.Name) }); implField.InitExpression = new CodeMethodInvokeExpression (getclass, new CodeExpression [] { new CodePrimitiveExpression (Name) }); decl.Members.Add (implField); //private static IClass impl = global::CppTests.Libs.Test.GetClass <IClass, _Class, Class>("Class"); if (!hasBase) { var ptrField = new CodeMemberField (new CodeTypeReference ("CppInstancePtr"), "native_ptr"); ptrField.Attributes = MemberAttributes.Family; decl.Members.Add (ptrField); } var allocCtor = new CodeConstructor () { }; allocCtor.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("CppLibrary"), "dummy")); allocCtor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "native_ptr"), new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Alloc"), new CodeExpression [] { new CodeThisReferenceExpression () }))); if (hasBase) { var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo"); allocCtor.BaseConstructorArgs.Add (implTypeInfo); } decl.Members.Add (allocCtor); var subclassCtor = new CodeConstructor () { Attributes = MemberAttributes.Family }; subclassCtor.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("CppTypeInfo"), "subClass")); subclassCtor.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeArgumentReferenceExpression ("subClass"), "AddBase"), new CodeExpression [] { new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "TypeInfo") }))); if (hasBase) { var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo"); subclassCtor.BaseConstructorArgs.Add (implTypeInfo); } decl.Members.Add (subclassCtor); if (!hasBase) { var nativeProperty = new CodeMemberProperty () { Name = "Native", Type = new CodeTypeReference ("CppInstancePtr"), Attributes = MemberAttributes.Public|MemberAttributes.Final }; nativeProperty.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "native_ptr"))); decl.Members.Add (nativeProperty); } var disposeMethod = new CodeMemberMethod () { Name = "Dispose", Attributes = MemberAttributes.Public }; if (Methods.Any (m => m.IsDestructor)) disposeMethod.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Destruct"), new CodeExpression [] { new CodeFieldReferenceExpression (null, "Native") }))); disposeMethod.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "Native"), "Dispose")))); decl.Members.Add (disposeMethod); foreach (Method m in Methods) { iface.Members.Add (m.GenerateIFaceMethod (g)); if (m.GenWrapperMethod) { var cm = m.GenerateWrapperMethod (g); if (m.IsConstructor && hasBase) { var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo"); (cm as CodeConstructor).BaseConstructorArgs.Add (implTypeInfo); } decl.Members.Add (cm); } } foreach (Property p in Properties) { decl.Members.Add (p.GenerateProperty (g)); } return decl; }
private void DefineWrapperClassFieldsAndMethods(Smoke.Class* smokeClass, CodeTypeDeclaration type) { // define the dummy constructor if (smokeClass->size > 0) { CodeConstructor dummyCtor = new CodeConstructor(); dummyCtor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Type)), "dummy")); if (data.Smoke->inheritanceList[smokeClass->parents] > 0) { dummyCtor.BaseConstructorArgs.Add(new CodeSnippetExpression("(System.Type) null")); } dummyCtor.Attributes = MemberAttributes.Family; if (SupportingMethodsHooks != null) { SupportingMethodsHooks(data.Smoke, (Smoke.Method*) 0, dummyCtor, type); } type.Members.Add(dummyCtor); } CodeMemberField staticInterceptor = new CodeMemberField("SmokeInvocation", "staticInterceptor"); staticInterceptor.Attributes = MemberAttributes.Static; CodeObjectCreateExpression initExpression = new CodeObjectCreateExpression("SmokeInvocation"); initExpression.Parameters.Add(new CodeTypeOfExpression(type.Name)); initExpression.Parameters.Add(new CodePrimitiveExpression(null)); staticInterceptor.InitExpression = initExpression; type.Members.Add(staticInterceptor); if (smokeClass->size == 0) return; // we only need this for real classes CodeMemberMethod createProxy = new CodeMemberMethod(); createProxy.Name = "CreateProxy"; createProxy.Attributes = MemberAttributes.Public; if (data.Smoke->inheritanceList[smokeClass->parents] != 0) { createProxy.Attributes |= MemberAttributes.Override; } createProxy.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "interceptor"), // left hand side new CodeObjectCreateExpression("SmokeInvocation", new CodeTypeOfExpression(type.Name), new CodeThisReferenceExpression()) // right hand side )); type.Members.Add(createProxy); if (data.Smoke->inheritanceList[smokeClass->parents] != 0) return; // The following fields are only necessary for classes without superclasses. CodeMemberField interceptor = new CodeMemberField("SmokeInvocation", "interceptor"); interceptor.Attributes = MemberAttributes.Family; type.Members.Add(interceptor); CodeMemberField smokeObject = new CodeMemberField(typeof(IntPtr), "smokeObject"); type.Members.Add(smokeObject); type.BaseTypes.Add(new CodeTypeReference("ISmokeObject")); CodeMemberProperty propertySmokeObject = new CodeMemberProperty(); propertySmokeObject.Name = "SmokeObject"; propertySmokeObject.Type = new CodeTypeReference(typeof(IntPtr)); propertySmokeObject.Attributes = MemberAttributes.Public; CodeFieldReferenceExpression smokeObjectReference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), smokeObject.Name); propertySmokeObject.GetStatements.Add(new CodeMethodReturnStatement(smokeObjectReference)); propertySmokeObject.SetStatements.Add(new CodeAssignStatement(smokeObjectReference, new CodePropertySetValueReferenceExpression())); type.Members.Add(propertySmokeObject); }
private void CodeDomProducer_CodeDomProduction(object sender, CodeDomProductionEventArgs e) { if (e.EventType == CodeDomProductionEventType.UnitsProducing) { if (e.Argument == null) return; foreach (var entity in Project.Entities) { if (!entity.GetAttributeValue("enabled", NamespaceUri, true)) continue; CodeTypeDeclaration typeDeclaration = _codeDomProducer.GetType(entity); if (typeDeclaration == null) continue; // Class var jsonObjectAttribute = new CodeAttributeDeclaration("Newtonsoft.Json.JsonObjectAttribute"); string optMode = entity.GetAttributeValue("optMode", NamespaceUri, "OptIn"); if (optMode != null) { var memberSerialization = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("Newtonsoft.Json.MemberSerialization"), optMode); jsonObjectAttribute.Arguments.Add(new CodeAttributeArgument("MemberSerialization", memberSerialization)); } CodeDomUtilities.EnsureAttribute(typeDeclaration, jsonObjectAttribute, true); // Properties foreach (CodeTypeMember member in typeDeclaration.Members) { PropertyDefinition propertyDefinition = null; CodeMemberProperty memberProperty = member as CodeMemberProperty; if (memberProperty != null) { propertyDefinition = UserData.GetPropertyDefinition(memberProperty); } Property property = null; if (propertyDefinition != null && propertyDefinition.Property != null) { property = propertyDefinition.Property; if (!property.GetAttributeValue("enabled", NamespaceUri, true)) continue; } else { if (!entity.GetAttributeValue("enabledForNonModelProperties", NamespaceUri, true)) continue; } bool? serialized = null; if (property != null) { serialized = property.GetAttributeValue("includeInSerialization", NamespaceUri, (bool?)null); } if (serialized == null) { //[System.NonSerializedAttribute()] => false //[System.Xml.Serialization.XmlIgnoreAttribute()] => false //[System.Runtime.Serialization.DataMemberAttribute()] => true if (CodeDomUtilities.GetAttribute(member, typeof(NonSerializedAttribute)) != null) { serialized = false; } else if (CodeDomUtilities.GetAttribute(member, typeof(XmlIgnoreAttribute)) != null) { serialized = false; } else if (CodeDomUtilities.GetAttribute(member, typeof(DataMemberAttribute)) != null) { serialized = true; } else if (CodeDomUtilities.GetAttribute(member, typeof(XmlAttribute)) != null) { serialized = true; } else if (CodeDomUtilities.GetAttribute(member, typeof(XmlElementAttribute)) != null) { serialized = true; } else if (property != null) { serialized = property.IsIncludedInSerialization; } } // [JsonIgnore] or [JsonProperty] if (serialized != null) { var jsonPropertyAttribute = new CodeAttributeDeclaration(); jsonPropertyAttribute.Name = serialized == true ? "Newtonsoft.Json.JsonPropertyAttribute" : "Newtonsoft.Json.JsonIgnoreAttribute"; CodeDomUtilities.EnsureAttribute(member, jsonPropertyAttribute, true); } } } } }
public void Visit(CodeFieldReferenceExpression o) { g.GenerateFieldReferenceExpression(o); }
static void BuildCity (City c, CodeMemberMethod method, CodeFieldReferenceExpression curVar, CodeFieldReferenceExpression curLocation) { CodeAssignStatement cityAssign = new CodeAssignStatement (); cityAssign.Left = curCity; cityAssign.Right = new CodeCastExpression (cityType, curLocation); method.Statements.Add (cityAssign); CodeMethodInvokeExpression locationAdd; foreach (Location l in c.Locations) { locationAdd = new CodeMethodInvokeExpression ( curCity, "Add", new CodeExpression[] {BuildCityLocation (l, method)} ); method.Statements.Add (locationAdd); } }
private static CodeMethodReturnStatement GenerateParameters(CodeMemberMethod helperMethod, CodeTypeDeclaration codeTypeDeclaration, CodeExpression target, FieldDirection dir) { CodeMethodReturnStatement statement = null; foreach (CodeTypeMember member in codeTypeDeclaration.Members) { CodeMemberField field = member as CodeMemberField; if (field != null) { CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(target, field.Name); CodeTypeDeclaration codeType = ServiceContractGenerator.NamespaceHelper.GetCodeType(field.Type); if (codeType != null) { if (dir == FieldDirection.In) { helperMethod.Statements.Add(new CodeAssignStatement(left, new CodeObjectCreateExpression(field.Type, new CodeExpression[0]))); } statement = GenerateParameters(helperMethod, codeType, left, dir); continue; } CodeParameterDeclarationExpression expression2 = GetRefParameter(helperMethod.Parameters, dir, field); if (((expression2 == null) && (dir == FieldDirection.Out)) && (helperMethod.ReturnType.BaseType == voidTypeRef.BaseType)) { helperMethod.ReturnType = field.Type; statement = new CodeMethodReturnStatement(left); } else { if (expression2 == null) { expression2 = new CodeParameterDeclarationExpression(field.Type, NamingHelper.GetUniqueName(field.Name, new NamingHelper.DoesNameExist(ClientClassGenerator.DoesParameterNameExist), helperMethod)); expression2.Direction = dir; helperMethod.Parameters.Add(expression2); } if (dir == FieldDirection.Out) { helperMethod.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression(expression2.Name), left)); continue; } helperMethod.Statements.Add(new CodeAssignStatement(left, new CodeArgumentReferenceExpression(expression2.Name))); } } } return statement; }
private static CodeTypeDeclaration CreateOperationCompletedEventArgsType(ServiceContractGenerationContext context, string syncMethodName, CodeMemberMethod endMethod) { if ((endMethod.Parameters.Count == 1) && (endMethod.ReturnType.BaseType == voidTypeRef.BaseType)) { return null; } CodeTypeDeclaration ownerTypeDecl = context.TypeFactory.CreateClassType(); ownerTypeDecl.BaseTypes.Add(new CodeTypeReference(asyncCompletedEventArgsType)); CodeMemberField field = new CodeMemberField(); field.Type = new CodeTypeReference(objectArrayType); CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(); left.TargetObject = new CodeThisReferenceExpression(); CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; for (int i = 0; i < EventArgsCtorParamTypes.Length; i++) { constructor.Parameters.Add(new CodeParameterDeclarationExpression(EventArgsCtorParamTypes[i], EventArgsCtorParamNames[i])); if (i > 0) { constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(EventArgsCtorParamNames[i])); } } ownerTypeDecl.Members.Add(constructor); constructor.Statements.Add(new CodeAssignStatement(left, new CodeVariableReferenceExpression(EventArgsCtorParamNames[0]))); int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod); int num3 = 0; for (int j = 0; j < endMethod.Parameters.Count; j++) { if (j != asyncResultParamIndex) { CreateEventAsyncCompletedArgsTypeProperty(ownerTypeDecl, endMethod.Parameters[j].Type, endMethod.Parameters[j].Name, new CodeArrayIndexerExpression(left, new CodeExpression[] { new CodePrimitiveExpression(num3++) })); } } if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType) { CreateEventAsyncCompletedArgsTypeProperty(ownerTypeDecl, endMethod.ReturnType, NamingHelper.GetUniqueName("Result", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMemberNameExist), ownerTypeDecl), new CodeArrayIndexerExpression(left, new CodeExpression[] { new CodePrimitiveExpression(num3) })); } field.Name = NamingHelper.GetUniqueName("results", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMemberNameExist), ownerTypeDecl); left.FieldName = field.Name; ownerTypeDecl.Members.Add(field); ownerTypeDecl.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventArgsTypeName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesTypeAndMemberNameExist), new object[] { context.Namespace.Types, ownerTypeDecl }); context.Namespace.Types.Add(ownerTypeDecl); return ownerTypeDecl; }
public void VisitFieldReference(CodeFieldReferenceExpression field) { field.Expression.Accept(this); writer.Write("."); writer.WriteName(field.FieldName); }
static CodeExpression GetXdmItemTypeExpression(XPathItemType itemType) { switch (itemType.Kind) { case XPathItemKind.AnyItem: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmAnyItemType)), "Instance" )); case XPathItemKind.Atomic: CodeExpression qnameRef = null; QName atomicSchemaType = GetAtomicSchemaType(itemType); if (atomicSchemaType.Uri == XMLSchemaNamespace) { FieldInfo qnameField = typeof(QName).GetField("XS_" + atomicSchemaType.LocalName.ToUpperInvariant(), BindingFlags.Public | BindingFlags.Static); if (qnameField != null) { qnameRef = new CodeFieldReferenceExpression { FieldName = qnameField.Name, TargetObject = new CodeTypeReferenceExpression(typeof(QName)) }; } } if (qnameRef == null) { qnameRef = new CodeObjectCreateExpression( typeof(QName), new CodePrimitiveExpression(atomicSchemaType.Uri), new CodePrimitiveExpression(atomicSchemaType.LocalName) ); } return(new CodeMethodInvokeExpression { Method = new CodeMethodReferenceExpression { MethodName = "BuiltInAtomicType", TargetObject = new CodeTypeReferenceExpression(typeof(XdmAtomicType)) }, Parameters = { qnameRef } }); case XPathItemKind.AnyNode: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmAnyNodeType)), "Instance" )); case XPathItemKind.Attribute: case XPathItemKind.SchemaAttribute: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmNodeKind)), "Attribute" )); case XPathItemKind.Comment: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmNodeKind)), "Comment" )); case XPathItemKind.Document: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmNodeKind)), "Document" )); case XPathItemKind.Element: case XPathItemKind.SchemaElement: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmNodeKind)), "Element" )); case XPathItemKind.ProcessingInstruction: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmNodeKind)), "ProcessingInstruction" )); case XPathItemKind.Text: return(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmNodeKind)), "Text" )); default: throw new ArgumentException("itemType not supported.", "itemType"); } }
protected override void GenerateFieldReferenceExpression (CodeFieldReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.FieldName); }
void ImportHeader(CodeMemberMethod method, SoapHeaderBinding hb, SoapHeaderDirection direction) { Message msg = ServiceDescriptions.GetMessage(hb.Message); if (msg == null) { throw new InvalidOperationException("Message " + hb.Message + " not found"); } MessagePart part = msg.Parts [hb.Part]; if (part == null) { throw new InvalidOperationException("Message part " + hb.Part + " not found in message " + hb.Message); } XmlTypeMapping map; string hname; if (hb.Use == SoapBindingUse.Literal) { map = xmlImporter.ImportDerivedTypeMapping(part.Element, typeof(SoapHeader)); hname = part.Element.Name; xmlExporter.ExportTypeMapping(map); } else { map = soapImporter.ImportDerivedTypeMapping(part.Type, typeof(SoapHeader), true); hname = part.Type.Name; soapExporter.ExportTypeMapping(map); } string varName = headerVariables [map] as string; if (varName == null) { if (hname == map.TypeName) { varName = memberIds.AddUnique(CodeIdentifier.MakeValid(hname + "Value"), hb); } else { varName = memberIds.AddUnique(CodeIdentifier.MakeValid(hname), hb); } string propName = varName; varName = varName + "Field"; headerVariables.Add(map, varName); CodeMemberField codeField = new CodeMemberField(map.TypeFullName, varName); CodeTypeDeclaration.Members.Add(codeField); codeField.Attributes = MemberAttributes.Private; CodeMemberProperty codeProperty = new CodeMemberProperty(); codeProperty.Name = propName; codeProperty.Type = new CodeTypeReference(map.TypeFullName); codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeProperty.HasGet = codeProperty.HasSet = true; CodeExpression ce = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), varName); codeProperty.SetStatements.Add(new CodeAssignStatement(ce, new CodePropertySetValueReferenceExpression())); codeProperty.GetStatements.Add(new CodeMethodReturnStatement(ce)); CodeTypeDeclaration.Members.Add(codeProperty); varName = propName; } CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapHeaderAttribute"); att.Arguments.Add(GetArg(varName)); if (direction != SoapHeaderDirection.In) { att.Arguments.Add(GetEnumArg("Direction", "System.Web.Services.Protocols.SoapHeaderDirection", direction.ToString())); } AddCustomAttribute(method, att, true); }
/// <summary> /// Implements the getter of the given property /// </summary> /// <param name="property">The property</param> /// <param name="fieldRef">A reference to the underlying field</param> public static void ImplementGetter(this CodeMemberProperty property, CodeFieldReferenceExpression fieldRef) { property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); property.HasGet = true; }
/// <summary> /// Gets all the anim event mappings for the given animator controller. /// </summary> private static CodeObjectCreateExpression CreateWithEventMappings(AnimatorController animatorController, CodeExpression layerDeclarations) { Dictionary <AnimatorState, AnimatorControllerLayer> layerMap = new Dictionary <AnimatorState, AnimatorControllerLayer>(); Dictionary <AnimEventType, List <AnimatorState> > bindings = new Dictionary <AnimEventType, List <AnimatorState> >(); Func <StateMachineBehaviour[], AnimEventBinder> containsBehaviour = (behaviourSet) => { for (int i = 0; i < behaviourSet.Length; i++) { if (behaviourSet[i].GetType() == typeof(AnimEventBinder)) { return((AnimEventBinder)behaviourSet[i]); } } return(null); }; Func <AnimatorControllerLayer, AnimatorState, int> getFullPathHash = (layer, state) => { return(Animator.StringToHash(layer.name + "." + state.name)); }; for (int l = 0; l < animatorController.layers.Length; l++) { for (int s = 0; s < animatorController.layers[l].stateMachine.states.Length; s++) { AnimEventBinder binder = containsBehaviour(animatorController.layers[l].stateMachine.states[s].state.behaviours); if (binder != null) { for (int a = 0; a < binder.animEventTypes.Length; a++) { if (!bindings.ContainsKey(binder.animEventTypes[a])) { bindings.Add(binder.animEventTypes[a], new List <AnimatorState>()); } bindings[binder.animEventTypes[a]].Add(animatorController.layers[l].stateMachine.states[s].state); layerMap.Add(animatorController.layers[l].stateMachine.states[s].state, animatorController.layers[l]); } } } } AnimEventType[] boundAnimEvents = new AnimEventType[bindings.Keys.Count]; int[][] hashSets = new int[boundAnimEvents.Length][]; CodeFieldReferenceExpression[] eventsRefs = new CodeFieldReferenceExpression[boundAnimEvents.Length]; CodePrimitiveExpression[][] hashRefs = new CodePrimitiveExpression[hashSets.Length][]; CodeArrayCreateExpression[] subarrays = new CodeArrayCreateExpression[hashRefs.Length]; bindings.Keys.CopyTo(boundAnimEvents, 0); for (int i = 0; i < boundAnimEvents.Length; i++) { hashSets[i] = new int[bindings[boundAnimEvents[i]].Count]; for (int s = 0; s < hashSets[i].Length; s++) { hashSets[i][s] = getFullPathHash(layerMap[bindings[boundAnimEvents[i]][s]], bindings[boundAnimEvents[i]][s]); } eventsRefs[i] = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(AnimEventType)), boundAnimEvents[i].ToString()); hashRefs[i] = new CodePrimitiveExpression[hashSets[i].Length]; for (int h = 0; h < hashSets[i].Length; i++) { hashRefs[i][h] = new CodePrimitiveExpression(hashSets[i][h]); } subarrays[i] = new CodeArrayCreateExpression(typeof(int[]), hashRefs[i]); } CodeExpression hashesMultiArrayDeclaration; // If subarrays.Length == 0, CodeDOM will "optimize" this argument straight into a type mismatch! // This is a hack that works around that by making sure we explicitly declare an empty array-of-arrays, // if need be. if (subarrays.Length > 0) { hashesMultiArrayDeclaration = new CodeArrayCreateExpression(typeof(int[][]), subarrays); } else { hashesMultiArrayDeclaration = new CodeSnippetExpression("new int[0][]"); } return(new CodeObjectCreateExpression(typeof(AnimatorMetadata), new CodeExpression[] { layerDeclarations, new CodeArrayCreateExpression(typeof(AnimEventType), eventsRefs), hashesMultiArrayDeclaration })); }
/// <summary> /// Implements the setter of the given property /// </summary> /// <param name="property">The code property</param> /// <param name="fieldRef">A reference to the underlying field</param> /// <param name="whenChanged">A collection of statements that should be performed when the value of the property changed</param> public static void ImplementSetter(this CodeMemberProperty property, CodeFieldReferenceExpression fieldRef, params CodeStatement[] whenChanged) { ImplementSetter(property, fieldRef, (IEnumerable <CodeStatement>)whenChanged); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace("NSPC"); nspace.Imports.Add(new CodeNamespaceImport("System")); cu.Namespaces.Add(nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration("TestFields"); cd.IsClass = true; nspace.Types.Add(cd); // GENERATES (C#): // public static int UseStaticPublicField(int i) { // ClassWithFields.StaticPublicField = i; // return ClassWithFields.StaticPublicField; // CodeMemberMethod cmm; if (Supports(provider, GeneratorSupport.PublicStaticMembers)) { AddScenario("CheckUseStaticPublicField"); cmm = new CodeMemberMethod(); cmm.Name = "UseStaticPublicField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression( new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"))); cd.Members.Add(cmm); } // GENERATES (C#): // public static int UseNonStaticPublicField(int i) { // ClassWithFields variable = new ClassWithFields(); // variable.NonStaticPublicField = i; // return variable.NonStaticPublicField; // } AddScenario("CheckUseNonStaticPublicField"); cmm = new CodeMemberMethod(); cmm.Name = "UseNonStaticPublicField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields"))); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"))); cd.Members.Add(cmm); // GENERATES (C#): // public static int UseNonStaticInternalField(int i) { // ClassWithFields variable = new ClassWithFields(); // variable.NonStaticInternalField = i; // return variable.NonStaticInternalField; // } if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { cmm = new CodeMemberMethod(); AddScenario("CheckUseNonStaticInternalField"); cmm.Name = "UseNonStaticInternalField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields"))); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"))); cd.Members.Add(cmm); } // GENERATES (C#): // public static int UseInternalField(int i) { // ClassWithFields.InternalField = i; // return ClassWithFields.InternalField; // } if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { AddScenario("CheckUseInternalField"); cmm = new CodeMemberMethod(); cmm.Name = "UseInternalField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "InternalField"), new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "InternalField"))); cd.Members.Add(cmm); } // GENERATES (C#): // public static int UseConstantField(int i) { // return ClassWithFields.ConstantField; // } AddScenario("CheckUseConstantField"); cmm = new CodeMemberMethod(); cmm.Name = "UseConstantField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ClassWithFields"), "ConstantField"))); cd.Members.Add(cmm); // code a new class to test that the protected field can be accessed by classes that inherit it // GENERATES (C#): // public class TestProtectedField : ClassWithFields { // public static int UseProtectedField(int i) { // ProtectedField = i; // return ProtectedField; // } // } cd = new CodeTypeDeclaration("TestProtectedField"); cd.BaseTypes.Add(new CodeTypeReference("ClassWithFields")); cd.IsClass = true; nspace.Types.Add(cd); cmm = new CodeMemberMethod(); AddScenario("CheckUseProtectedField"); cmm.Name = "UseProtectedField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); CodeFieldReferenceExpression reference = new CodeFieldReferenceExpression(); reference.FieldName = "ProtectedField"; reference.TargetObject = new CodeTypeReferenceExpression("ClassWithFields"); cmm.Statements.Add(new CodeAssignStatement(reference, new CodeArgumentReferenceExpression("i"))); cmm.Statements.Add(new CodeMethodReturnStatement(reference)); cd.Members.Add(cmm); // declare class with fields // GENERATES (C#): // public class ClassWithFields { // public static int StaticPublicField = 5; // /*FamANDAssem*/ internal static int InternalField = 0; // public const int ConstantField = 0; // protected static int ProtectedField = 0; // private static int PrivateField = 5; // public int NonStaticPublicField = 5; // /*FamANDAssem*/ internal int NonStaticInternalField = 0; // public static int UsePrivateField(int i) { // PrivateField = i; // return PrivateField; // } // } cd = new CodeTypeDeclaration ("ClassWithFields"); cd.IsClass = true; nspace.Types.Add (cd); CodeMemberField field; if (Supports (provider, GeneratorSupport.PublicStaticMembers)) { field = new CodeMemberField (); field.Name = "StaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (5); cd.Members.Add (field); } if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { field = new CodeMemberField (); field.Name = "InternalField"; field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); } field = new CodeMemberField (); field.Name = "ConstantField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Const; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); field = new CodeMemberField (); field.Name = "ProtectedField"; field.Attributes = MemberAttributes.Family | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); field = new CodeMemberField (); field.Name = "PrivateField"; field.Attributes = MemberAttributes.Private | MemberAttributes.Static; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (5); cd.Members.Add (field); field = new CodeMemberField (); field.Name = "NonStaticPublicField"; field.Attributes = MemberAttributes.Public | MemberAttributes.Final; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (5); cd.Members.Add (field); if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) { field = new CodeMemberField (); field.Name = "NonStaticInternalField"; field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final; field.Type = new CodeTypeReference (typeof (int)); field.InitExpression = new CodePrimitiveExpression (0); cd.Members.Add (field); } // create a method to test access to private field AddScenario ("CheckUsePrivateField"); cmm = new CodeMemberMethod (); cmm.Name = "UsePrivateField"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); CodeFieldReferenceExpression fieldref = new CodeFieldReferenceExpression (); fieldref.TargetObject = new CodeTypeReferenceExpression("ClassWithFields"); fieldref.FieldName = "PrivateField"; cmm.Statements.Add (new CodeAssignStatement (fieldref, new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (fieldref)); cd.Members.Add (cmm); }
public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments) { var name = arguments["name"]; var type = arguments["type"]; if (string.IsNullOrEmpty(name)) { throw new DirectiveProcessorException("Parameter directive has no name argument"); } if (string.IsNullOrEmpty(type)) { throw new DirectiveProcessorException("Parameter directive has no type argument"); } var fieldName = "_" + name + "Field"; var typeRef = new CodeTypeReference(type); var thisRef = new CodeThisReferenceExpression(); var fieldRef = new CodeFieldReferenceExpression(thisRef, fieldName); var property = new CodeMemberProperty() { Name = name, Attributes = MemberAttributes.Public | MemberAttributes.Final, HasGet = true, HasSet = false, Type = typeRef }; property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); this.members.Add(new CodeMemberField(typeRef, fieldName)); this.members.Add(property); var acquiredName = "_" + name + "Acquired"; var valRef = new CodeVariableReferenceExpression("data"); var namePrimitive = new CodePrimitiveExpression(name); var sessionRef = new CodePropertyReferenceExpression(thisRef, "Session"); var callContextTypeRefExpr = new CodeTypeReferenceExpression("System.Runtime.Remoting.Messaging.CallContext"); var nullPrim = new CodePrimitiveExpression(null); var acquiredVariable = new CodeVariableDeclarationStatement(typeof(bool), acquiredName, new CodePrimitiveExpression(false)); var acquiredVariableRef = new CodeVariableReferenceExpression(acquiredVariable.Name); this.postStatements.Add(acquiredVariable); //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true var checkCastThenAssignVal = new CodeConditionStatement( new CodeMethodInvokeExpression( new CodeTypeOfExpression(typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression(valRef, "GetType")), new CodeStatement[] { new CodeAssignStatement(fieldRef, new CodeCastExpression(typeRef, valRef)), new CodeAssignStatement(acquiredVariableRef, new CodePrimitiveExpression(true)), }, new CodeStatement[] { new CodeExpressionStatement(new CodeMethodInvokeExpression(thisRef, "Error", new CodePrimitiveExpression("The type '" + type + "' of the parameter '" + name + "' did not match the type passed to the template"))), }); //tries to gets the value from the session var checkSession = new CodeConditionStatement( new CodeBinaryOperatorExpression(NotNull(sessionRef), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression(sessionRef, "ContainsKey", namePrimitive)), new CodeVariableDeclarationStatement(typeof(object), "data", new CodeIndexerExpression(sessionRef, namePrimitive)), checkCastThenAssignVal); this.postStatements.Add(checkSession); //if acquiredVariable is false, tries to gets the value from the host if (this.hostSpecific) { var hostRef = new CodePropertyReferenceExpression(thisRef, "Host"); var checkHost = new CodeConditionStatement( BooleanAnd(IsFalse(acquiredVariableRef), NotNull(hostRef)), new CodeVariableDeclarationStatement(typeof(string), "data", new CodeMethodInvokeExpression(hostRef, "ResolveParameterValue", nullPrim, nullPrim, namePrimitive)), new CodeConditionStatement(NotNull(valRef), checkCastThenAssignVal)); this.postStatements.Add(checkHost); } //if acquiredVariable is false, tries to gets the value from the call context var checkCallContext = new CodeConditionStatement( IsFalse(acquiredVariableRef), new CodeVariableDeclarationStatement(typeof(object), "data", new CodeMethodInvokeExpression(callContextTypeRefExpr, "LogicalGetData", namePrimitive)), new CodeConditionStatement(NotNull(valRef), checkCastThenAssignVal)); this.postStatements.Add(checkCallContext); }
public void GenerateCode(CodeTypeDeclaration persClass) { if (this.relationNode != null && (this.relation is ForeignFkRelation) && this.relationNode.RelatedTableNode.Table.Skipped) { return; } if (this.relationNode != null && this.relation.IsElement && ((TableNode)relationNode.Parent).Table.Skipped) { return; } if (this.relationNode != null && relation.IsElement && relationNode.RelatedTableNode.Table.Skipped) { return; } string typeStr; string name; bool isContainer = false; string summary = null; if (columnNode == null) // We have a relation { isContainer = !relation.IsElement; string containerType = relation.CodingStyle.ToString(); typeStr = isContainer ? containerType : relationNode.RelatedTableNode.Table.ClassName; name = relation.FieldName; } else { typeStr = columnNode.ShortType; name = columnNode.Column.FieldName; summary = columnNode.Column.Summary; } string bigname; if (name.StartsWith("_")) { bigname = name.Substring(1); } else if (name.StartsWith("m_")) { bigname = name.Substring(2); } else { bigname = name; } bigname = bigname.Substring(0, 1).ToUpper() + bigname.Substring(1); string elementTyp = null; //CodeVariableReferenceExpression fieldReference = new CodeVariableReferenceExpression("this." + name); CodeFieldReferenceExpression fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name); if (isContainer) { elementTyp = relationNode.RelatedTableNode.Table.ClassName; string relationName; if (relation.RelationName != string.Empty) { relationName = relation.RelationName; } else { ForeignFkRelation foreignRelation = relation as ForeignFkRelation; if (foreignRelation != null && foreignRelation.SingularFieldName != null) { relationName = foreignRelation.SingularFieldName; } else { relationName = elementTyp; } } bool isComposite = (relation.IsComposite); string parameter = elementTyp.Substring(0, 1).ToLower(); CodeMemberMethod cmm; cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public; persClass.Members.Add(cmm); if (isComposite) { cmm.Name = "New" + relationName; cmm.ReturnType = new CodeTypeReference(elementTyp); cmm.Statements.Add(new CodeVariableDeclarationStatement(elementTyp, parameter, new CodeObjectCreateExpression(elementTyp, new CodeExpression[] { }))); cmm.Statements.Add(new CodeMethodInvokeExpression(fieldReference, "Add", new CodeVariableReferenceExpression(parameter))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(parameter))); } else { cmm.Name = "Add" + relationName; cmm.Parameters.Add(new CodeParameterDeclarationExpression(elementTyp, parameter)); cmm.Statements.Add(new CodeMethodInvokeExpression(fieldReference, "Add", new CodeVariableReferenceExpression(parameter))); } cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public; persClass.Members.Add(cmm); cmm.Parameters.Add(new CodeParameterDeclarationExpression(elementTyp, parameter)); cmm.Name = "Remove" + relationName; CodeConditionStatement css = new CodeConditionStatement(); css.Condition = new CodeMethodInvokeExpression(fieldReference, "Contains", new CodeVariableReferenceExpression(parameter)); css.TrueStatements.Add(new CodeMethodInvokeExpression(fieldReference, "Remove", new CodeVariableReferenceExpression(parameter))); cmm.Statements.Add(css); } CodeMemberProperty cmp = new CodeMemberProperty(); if (!string.IsNullOrEmpty(summary)) { cmp.Comments.Add(new CodeCommentStatement("<summary>", true)); cmp.Comments.Add(new CodeCommentStatement(summary, true)); cmp.Comments.Add(new CodeCommentStatement("</summary>", true)); } cmp.Attributes = MemberAttributes.Public; cmp.HasGet = true; cmp.HasSet = true; cmp.Name = bigname; cmp.SetStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression("value"))); if (!isContainer) { persClass.Members.Add(cmp); cmp.Type = new CodeTypeReference(typeStr); cmp.GetStatements.Add(new CodeMethodReturnStatement(fieldReference)); } else { CodeTypeReference containerType = null; if (relation.CodingStyle == CodingStyle.IList) { containerType = new CodeTypeReference("IList"); } else { containerType = new CodeTypeReference("List"); } containerType.TypeArguments.Add(new CodeTypeReference(elementTyp)); persClass.Members.Add(cmp); cmp.Type = containerType; CodeTypeReference readOnlyList = new CodeTypeReference("NDOReadOnlyGenericList"); readOnlyList.TypeArguments.Add(elementTyp); cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(readOnlyList, fieldReference))); } }
/// <summary> /// Serializes the given object into a CodeDom object. /// </summary> public override object Serialize(IDesignerSerializationManager manager, object value) { CodeStatementCollection statements = null; PropertyDescriptorCollection props = TypeDescriptor.GetProperties(value); using (TraceScope("ComponentCodeDomSerializer::Serialize")) { if (manager is null || value is null) { throw new ArgumentNullException(manager is null ? "manager" : "value"); } if (IsSerialized(manager, value)) { Debug.Fail("Serialize is being called twice for the same component"); return(GetExpression(manager, value)); } // If the object is being inherited, we will will not emit a variable declaration. Also, we won't // do any serialization at all if the object is privately inherited. InheritanceLevel inheritanceLevel = InheritanceLevel.NotInherited; InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; if (inheritanceAttribute != null) { inheritanceLevel = inheritanceAttribute.InheritanceLevel; } // First, skip everything if we're privately inherited. We cannot write any code that would affect this // component. TraceIf(inheritanceLevel == InheritanceLevel.InheritedReadOnly, "Skipping read only inherited component"); if (inheritanceLevel != InheritanceLevel.InheritedReadOnly) { // Things we need to know: // // 1. What expression should we use for the left hand side // a) already given to us via GetExpression? // b) a local variable? // c) a member variable? // // 2. Should we generate an init expression for this // object? // a) Inherited or existing expression: no // b) otherwise, yes. statements = new CodeStatementCollection(); CodeTypeDeclaration typeDecl = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration; RootContext rootCxt = manager.Context[typeof(RootContext)] as RootContext; CodeExpression assignLhs = null; CodeExpression assignRhs; // Defaults for components bool generateLocal = false; bool generateField = true; bool generateObject = true; bool isComplete = false; assignLhs = GetExpression(manager, value); if (assignLhs != null) { Trace("Existing expression for LHS of value"); generateLocal = false; generateField = false; generateObject = false; // if we have an existing expression and this is not // a sited component, do not serialize it. We need this for Everett / 1.0 // backwards compat (even though it's wrong). if (value is IComponent comp && comp.Site is null) { // We were in a serialize content // property and would still serialize it. This code reverses what the // outer if block does for this specific case. We also need this // for Everett / 1.0 backwards compat. if (!(manager.Context[typeof(ExpressionContext)] is ExpressionContext expCxt) || expCxt.PresetValue != value) { isComplete = true; } } } else { Trace("Creating LHS expression"); if (inheritanceLevel == InheritanceLevel.NotInherited) { // See if there is a "GenerateMember" property. If so, // we might want to generate a local variable. Otherwise, // we want to generate a field. PropertyDescriptor generateProp = props["GenerateMember"]; if (generateProp != null && generateProp.PropertyType == typeof(bool) && !(bool)generateProp.GetValue(value)) { Trace("Object GenerateMember property wants a local variable"); generateLocal = true; generateField = false; } } else { generateObject = false; } if (rootCxt is null) { generateLocal = true; generateField = false; } } // Push the component being serialized onto the stack. It may be handy to // be able to discover this. manager.Context.Push(value); manager.Context.Push(statements); try { string name = manager.GetName(value); string typeName = TypeDescriptor.GetClassName(value); // Output variable / field declarations if we need to if ((generateField || generateLocal) && name != null) { if (generateField) { if (inheritanceLevel == InheritanceLevel.NotInherited) { // We need to generate the field declaration. See if there is a modifiers property on // the object. If not, look for a DefaultModifies, and finally assume it's private. CodeMemberField field = new CodeMemberField(typeName, name); PropertyDescriptor modifersProp = props["Modifiers"]; MemberAttributes fieldAttrs; if (modifersProp is null) { modifersProp = props["DefaultModifiers"]; } if (modifersProp != null && modifersProp.PropertyType == typeof(MemberAttributes)) { fieldAttrs = (MemberAttributes)modifersProp.GetValue(value); } else { TraceWarning("No Modifiers or DefaultModifiers property on component {0}. We must assume private.", name); fieldAttrs = MemberAttributes.Private; } field.Attributes = fieldAttrs; typeDecl.Members.Add(field); Trace("Field {0} {1} {2} created.", fieldAttrs, typeName, name); } // Next, create a nice LHS for our pending assign statement, when we hook up the variable. assignLhs = new CodeFieldReferenceExpression(rootCxt.Expression, name); } else { if (inheritanceLevel == InheritanceLevel.NotInherited) { CodeVariableDeclarationStatement local = new CodeVariableDeclarationStatement(typeName, name); statements.Add(local); Trace("Local {0} {1} created.", typeName, name); } assignLhs = new CodeVariableReferenceExpression(name); } } // Now output an object create if we need to. We always see if there is a // type converter that can provide us guidance if (generateObject) { // Ok, now that we've decided if we have a local or a member variable, its now time to serialize the rest of the code. // The first step is to create an assign statement to "new" the object. For that, we need to know if // the component wants a special IContainer constructor or not. For that to be valid we must also know // that we can get to an actual IContainer. IContainer container = manager.GetService(typeof(IContainer)) as IContainer; ConstructorInfo ctor = null; if (container != null) { ctor = GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, GetContainerConstructor(manager), null); } if (ctor != null) { Trace("Component has IContainer constructor."); assignRhs = new CodeObjectCreateExpression(typeName, new CodeExpression[] { SerializeToExpression(manager, container) }); } else { // For compat reasons we ignore the isCompleteOld value here. assignRhs = SerializeCreationExpression(manager, value, out bool isCompleteOld); Debug.Assert(isCompleteOld == isComplete, "CCDS Differing"); } TraceErrorIf(assignRhs is null, "No RHS code assign for object {0}", value); if (assignRhs != null) { if (assignLhs is null) { // We cannot do much more for this object. If isComplete is true, // then the RHS now becomes our LHS. Otherwise, I'm afraid we have // just failed to serialize this object. if (isComplete) { assignLhs = assignRhs; } else { TraceError("Incomplete serialization of object, abandoning serialization."); } } else { CodeAssignStatement assign = new CodeAssignStatement(assignLhs, assignRhs); statements.Add(assign); } } } if (assignLhs != null) { SetExpression(manager, value, assignLhs); } // It should practically be an assert that isComplete is false, but someone may // have an unusual component. if (assignLhs != null && !isComplete) { // .NET CF needs us to verify that the ISupportInitialize interface exists // (they do not support this interface and will modify their DSM to resolve the type to null). bool supportInitialize = (value is ISupportInitialize); if (supportInitialize) { string fullName = typeof(ISupportInitialize).FullName; supportInitialize = manager.GetType(fullName) != null; } Type reflectionType = null; if (supportInitialize) { // Now verify that this control implements ISupportInitialize in the project target framework // Don't use operator "is" but rather use IsAssignableFrom on the reflection types. // We have other places where we use operator "is", for example "is IComponent" to generate // specific CodeDOM objects, however we don't have cases of objects which were not an IComponent // in a downlevel framework and became an IComponent in a newer framework, so I'm not replacing // all instances of operator "is" by IsAssignableFrom. reflectionType = GetReflectionTypeHelper(manager, value); supportInitialize = GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(reflectionType); } bool persistSettings = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings; if (persistSettings) { string fullName = typeof(IPersistComponentSettings).FullName; persistSettings = manager.GetType(fullName) != null; } if (persistSettings) { reflectionType = reflectionType ?? GetReflectionTypeHelper(manager, value); persistSettings = GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(reflectionType); } // We implement statement caching only for the main code generation phase. We don't implement it for other // serialization managers. How do we tell the difference? The main serialization manager exists as a service. IDesignerSerializationManager mainManager = manager.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager; if (supportInitialize) { Trace("Object implements ISupportInitialize."); SerializeSupportInitialize(manager, statements, assignLhs, value, "BeginInit"); } SerializePropertiesToResources(manager, statements, value, _designTimeFilter); // Writing out properties is expensive. But, we're very smart and we cache the results // in ComponentCache. See if we have cached results. If so, use 'em. If not, generate // code and then see if we can cache the results for later. ComponentCache cache = manager.GetService(typeof(ComponentCache)) as ComponentCache; ComponentCache.Entry entry = null; if (cache is null) { if (manager.GetService(typeof(IServiceContainer)) is ServiceContainer sc) { cache = new ComponentCache(manager); sc.AddService(typeof(ComponentCache), cache); } } else { if (manager == mainManager && cache.Enabled) { entry = cache[value]; } } if (entry is null || entry.Tracking) { // Pushing the entry here allows it to be found by the resource code dom serializer, // which will add data to the ResourceBlob property on the entry. if (entry is null) { entry = new ComponentCache.Entry(cache); // We cache components even if they're not valid so dependencies are // still tracked correctly (see comment below). The problem is, we will create a // new entry object even if there is still an existing one that is just invalid, and it // might have dependencies that will be lost. // we need to make sure we copy over any dependencies that are also tracked. ComponentCache.Entry oldEntry = cache?.GetEntryAll(value); if (oldEntry != null && oldEntry.Dependencies != null && oldEntry.Dependencies.Count > 0) { foreach (object dependency in oldEntry.Dependencies) { entry.AddDependency(dependency); } } } entry.Component = value; // we need to link the cached entry with its corresponding component right away, before it's put in the context // see CodeDomSerializerBase.cs::GetExpression for usage // This entry will only be used if the valid bit is set. // This is useful because we still need to setup depedency relationships // between components even if they are not cached. See VSWhidbey 263053. bool correctManager = manager == mainManager; entry.Valid = correctManager && CanCacheComponent(manager, value, props); if (correctManager && cache != null && cache.Enabled) { manager.Context.Push(cache); manager.Context.Push(entry); } try { entry.Statements = new CodeStatementCollection(); SerializeProperties(manager, entry.Statements, value, _runTimeFilter); SerializeEvents(manager, entry.Statements, value, null); foreach (CodeStatement statement in entry.Statements) { if (statement is CodeVariableDeclarationStatement local) { entry.Tracking = true; break; } } if (entry.Statements.Count > 0) { // if we added some statements, insert the comments // entry.Statements.Insert(0, new CodeCommentStatement(string.Empty)); entry.Statements.Insert(0, new CodeCommentStatement(name)); entry.Statements.Insert(0, new CodeCommentStatement(string.Empty)); // // cache the statements for future usage if possible. We only do this for the main serialization manager, not // for any other seriallization managers that may be calling us for undo or clipboard functions. if (correctManager && cache != null && cache.Enabled) { cache[value] = entry; } } } finally { if (correctManager && cache != null && cache.Enabled) { Debug.Assert(manager.Context.Current == entry, "Context stack corrupted"); manager.Context.Pop(); manager.Context.Pop(); } } } else { // If we got a cache entry, we will need to take all the resources out of // it and apply them too. if ((entry.Resources != null || entry.Metadata != null) && cache != null && cache.Enabled) { ResourceCodeDomSerializer res = ResourceCodeDomSerializer.Default; res.ApplyCacheEntry(manager, entry); } } // Regarless, apply statements. Either we created them or we got them // out of the cache. statements.AddRange(entry.Statements); if (persistSettings) { SerializeLoadComponentSettings(manager, statements, assignLhs, value); } if (supportInitialize) { SerializeSupportInitialize(manager, statements, assignLhs, value, "EndInit"); } } }
public CodeIndexerExpression CreateMemberGetter(CodeFieldReferenceExpression regRef, string paramName) { return(new CodeIndexerExpression(regRef, new CodeArgumentReferenceExpression(paramName))); }
public override object Serialize(IDesignerSerializationManager manager, object value) { CodeStatementCollection statements = null; PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); using (CodeDomSerializerBase.TraceScope("ComponentCodeDomSerializer::Serialize")) { if ((manager == null) || (value == null)) { throw new ArgumentNullException((manager == null) ? "manager" : "value"); } if (base.IsSerialized(manager, value)) { return(base.GetExpression(manager, value)); } InheritanceLevel notInherited = InheritanceLevel.NotInherited; InheritanceAttribute attribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; if (attribute != null) { notInherited = attribute.InheritanceLevel; } if (notInherited == InheritanceLevel.InheritedReadOnly) { return(statements); } statements = new CodeStatementCollection(); CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration; RootContext context = manager.Context[typeof(RootContext)] as RootContext; CodeExpression left = null; bool flag = false; bool flag2 = true; bool flag3 = true; bool flag4 = false; left = base.GetExpression(manager, value); if (left != null) { flag = false; flag2 = false; flag3 = false; IComponent component = value as IComponent; if ((component != null) && (component.Site == null)) { ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext; if ((context2 == null) || (context2.PresetValue != value)) { flag4 = true; } } } else { if (notInherited == InheritanceLevel.NotInherited) { PropertyDescriptor descriptor = properties["GenerateMember"]; if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && !((bool)descriptor.GetValue(value))) { flag = true; flag2 = false; } } else { flag3 = false; } if (context == null) { flag = true; flag2 = false; } } manager.Context.Push(value); manager.Context.Push(statements); try { try { string name = manager.GetName(value); string className = TypeDescriptor.GetClassName(value); if ((flag2 || flag) && (name != null)) { if (flag2) { if (notInherited == InheritanceLevel.NotInherited) { MemberAttributes @private; CodeMemberField field = new CodeMemberField(className, name); PropertyDescriptor descriptor2 = properties["Modifiers"]; if (descriptor2 == null) { descriptor2 = properties["DefaultModifiers"]; } if ((descriptor2 != null) && (descriptor2.PropertyType == typeof(MemberAttributes))) { @private = (MemberAttributes)descriptor2.GetValue(value); } else { @private = MemberAttributes.Private; } field.Attributes = @private; declaration.Members.Add(field); } left = new CodeFieldReferenceExpression(context.Expression, name); } else { if (notInherited == InheritanceLevel.NotInherited) { CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(className, name); statements.Add(statement); } left = new CodeVariableReferenceExpression(name); } } if (flag3) { CodeExpression expression2; IContainer service = manager.GetService(typeof(IContainer)) as IContainer; ConstructorInfo info = null; if (service != null) { info = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, this.GetContainerConstructor(manager), null); } if (info != null) { expression2 = new CodeObjectCreateExpression(className, new CodeExpression[] { base.SerializeToExpression(manager, service) }); } else { bool flag5; expression2 = base.SerializeCreationExpression(manager, value, out flag5); } if (expression2 != null) { if (left == null) { if (flag4) { left = expression2; } } else { CodeAssignStatement statement2 = new CodeAssignStatement(left, expression2); statements.Add(statement2); } } } if (left != null) { base.SetExpression(manager, value, left); } if ((left != null) && !flag4) { bool flag6 = value is ISupportInitialize; if (flag6) { string fullName = typeof(ISupportInitialize).FullName; flag6 = manager.GetType(fullName) != null; } Type c = null; if (flag6) { c = CodeDomSerializerBase.GetReflectionTypeHelper(manager, value); flag6 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(c); } bool flag7 = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings; if (flag7) { string typeName = typeof(IPersistComponentSettings).FullName; flag7 = manager.GetType(typeName) != null; } if (flag7) { c = c ?? CodeDomSerializerBase.GetReflectionTypeHelper(manager, value); flag7 = CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(c); } IDesignerSerializationManager manager2 = (IDesignerSerializationManager)manager.GetService(typeof(IDesignerSerializationManager)); if (flag6) { this.SerializeSupportInitialize(manager, statements, left, value, "BeginInit"); } base.SerializePropertiesToResources(manager, statements, value, _designTimeFilter); ComponentCache serviceInstance = (ComponentCache)manager.GetService(typeof(ComponentCache)); ComponentCache.Entry entry = null; if (serviceInstance == null) { IServiceContainer container2 = (IServiceContainer)manager.GetService(typeof(IServiceContainer)); if (container2 != null) { serviceInstance = new ComponentCache(manager); container2.AddService(typeof(ComponentCache), serviceInstance); } } else if (((manager == manager2) && (serviceInstance != null)) && serviceInstance.Enabled) { entry = serviceInstance[value]; } if ((entry == null) || entry.Tracking) { if (entry == null) { entry = new ComponentCache.Entry(serviceInstance); ComponentCache.Entry entryAll = null; entryAll = serviceInstance.GetEntryAll(value); if (((entryAll != null) && (entryAll.Dependencies != null)) && (entryAll.Dependencies.Count > 0)) { foreach (object obj2 in entryAll.Dependencies) { entry.AddDependency(obj2); } } } entry.Component = value; bool flag8 = manager == manager2; entry.Valid = flag8 && this.CanCacheComponent(manager, value, properties); if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled) { manager.Context.Push(serviceInstance); manager.Context.Push(entry); } try { entry.Statements = new CodeStatementCollection(); base.SerializeProperties(manager, entry.Statements, value, _runTimeFilter); base.SerializeEvents(manager, entry.Statements, value, null); foreach (CodeStatement statement3 in entry.Statements) { if (statement3 is CodeVariableDeclarationStatement) { entry.Tracking = true; break; } } if (entry.Statements.Count > 0) { entry.Statements.Insert(0, new CodeCommentStatement(string.Empty)); entry.Statements.Insert(0, new CodeCommentStatement(name)); entry.Statements.Insert(0, new CodeCommentStatement(string.Empty)); if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled) { serviceInstance[value] = entry; } } } finally { if ((flag8 && (serviceInstance != null)) && serviceInstance.Enabled) { manager.Context.Pop(); manager.Context.Pop(); } } } else if (((entry.Resources != null) || (entry.Metadata != null)) && ((serviceInstance != null) && serviceInstance.Enabled)) { ResourceCodeDomSerializer.Default.ApplyCacheEntry(manager, entry); } statements.AddRange(entry.Statements); if (flag7) { this.SerializeLoadComponentSettings(manager, statements, left, value); } if (flag6) { this.SerializeSupportInitialize(manager, statements, left, value, "EndInit"); } } return(statements); } catch (CheckoutException) { throw; } catch (Exception exception) { manager.ReportError(exception); } return(statements); } finally { manager.Context.Pop(); manager.Context.Pop(); } } return(statements); }
public static void GenerateRepositoryGetByIdentityMethod(IClassMap classMap, CodeTypeDeclaration classDecl, bool tryMethod) { IList propertyMaps = classMap.GetIdentityPropertyMaps(); CodeMemberMethod methodMember = new CodeMemberMethod(); if (tryMethod) { methodMember.Name = GetRepositoryGetByIdentityMethodName(classMap); } else { methodMember.Name = GetRepositoryTryGetByIdentityMethodName(classMap); } CodeTypeReference typeReference = new CodeTypeReference(classMap.GetName()); methodMember.ReturnType = typeReference; methodMember.Attributes = MemberAttributes.Public; foreach (IPropertyMap propertyMap in propertyMaps) { CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference(propertyMap.DataType), MakeCamelCase(propertyMap.Name)); methodMember.Parameters.Add(parameter); } CodeThisReferenceExpression thisExp = new CodeThisReferenceExpression(); CodeFieldReferenceExpression contextVar = new CodeFieldReferenceExpression(thisExp, "context"); CodeVariableDeclarationStatement dummyObjectVarDecl = new CodeVariableDeclarationStatement(classMap.GetName(), "identityObject"); CodeVariableReferenceExpression dummyObjectVar = new CodeVariableReferenceExpression("identityObject"); CodeObjectCreateExpression dummyObjectCreateExpr = new CodeObjectCreateExpression(typeReference, new CodeExpression[] {}); CodeAssignStatement assignDummyStatement = new CodeAssignStatement(dummyObjectVar, dummyObjectCreateExpr); methodMember.Statements.Add(dummyObjectVarDecl); methodMember.Statements.Add(assignDummyStatement); foreach (IPropertyMap propertyMap in propertyMaps) { CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression(MakeCamelCase(propertyMap.Name)); CodeVariableReferenceExpression propExp = new CodeVariableReferenceExpression("identityObject" + "." + propertyMap.Name); CodeAssignStatement assignStatement = new CodeAssignStatement(propExp, argExp); methodMember.Statements.Add(assignStatement); } CodeTypeOfExpression typeOfExp = new CodeTypeOfExpression(typeReference); CodeMethodInvokeExpression newObjectInit = null; if (tryMethod) { newObjectInit = new CodeMethodInvokeExpression(contextVar, "GetObjectById", new CodeExpression[] { dummyObjectVar, typeOfExp }); } else { newObjectInit = new CodeMethodInvokeExpression(contextVar, "TryGetObjectById", new CodeExpression[] { dummyObjectVar, typeOfExp }); } CodeCastExpression castExp = new CodeCastExpression(typeReference, newObjectInit); CodeVariableDeclarationStatement newObjectVarDecl = new CodeVariableDeclarationStatement(classMap.GetName(), MakeCamelCase(classMap.GetName()), castExp); CodeVariableReferenceExpression newObjectVar = new CodeVariableReferenceExpression(MakeCamelCase(classMap.GetName())); methodMember.Statements.Add(newObjectVarDecl); CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(newObjectVar); methodMember.Statements.Add(returnStmt); classDecl.Members.Add(methodMember); }
private void CodeDomProducer_CodeDomProduction(object sender, CodeDomProductionEventArgs e) { if (e.EventType == CodeDomProductionEventType.UnitsProducing) { if (e.Argument == null) { return; } foreach (var entity in Project.Entities) { if (!entity.GetAttributeValue("enabled", NamespaceUri, true)) { continue; } CodeTypeDeclaration typeDeclaration = _codeDomProducer.GetType(entity); if (typeDeclaration == null) { continue; } // Class var jsonObjectAttribute = new CodeAttributeDeclaration("Newtonsoft.Json.JsonObjectAttribute"); string optMode = entity.GetAttributeValue("optMode", NamespaceUri, "OptIn"); if (optMode != null) { var memberSerialization = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("Newtonsoft.Json.MemberSerialization"), optMode); jsonObjectAttribute.Arguments.Add(new CodeAttributeArgument("MemberSerialization", memberSerialization)); } CodeDomUtilities.EnsureAttribute(typeDeclaration, jsonObjectAttribute, true); // Properties foreach (CodeTypeMember member in typeDeclaration.Members) { PropertyDefinition propertyDefinition = null; CodeMemberProperty memberProperty = member as CodeMemberProperty; if (memberProperty != null) { propertyDefinition = UserData.GetPropertyDefinition(memberProperty); } Property property = null; if (propertyDefinition != null && propertyDefinition.Property != null) { property = propertyDefinition.Property; if (!property.GetAttributeValue("enabled", NamespaceUri, true)) { continue; } } else { if (!entity.GetAttributeValue("enabledForNonModelProperties", NamespaceUri, true)) { continue; } } bool?serialized = null; if (property != null) { serialized = property.GetAttributeValue("includeInSerialization", NamespaceUri, (bool?)null); } if (serialized == null) { //[System.NonSerializedAttribute()] => false //[System.Xml.Serialization.XmlIgnoreAttribute()] => false //[System.Runtime.Serialization.DataMemberAttribute()] => true if (CodeDomUtilities.GetAttribute(member, typeof(NonSerializedAttribute)) != null) { serialized = false; } else if (CodeDomUtilities.GetAttribute(member, typeof(XmlIgnoreAttribute)) != null) { serialized = false; } else if (CodeDomUtilities.GetAttribute(member, typeof(DataMemberAttribute)) != null) { serialized = true; } else if (CodeDomUtilities.GetAttribute(member, typeof(XmlAttribute)) != null) { serialized = true; } else if (CodeDomUtilities.GetAttribute(member, typeof(XmlElementAttribute)) != null) { serialized = true; } else if (property != null) { serialized = property.IsIncludedInSerialization; } } // [JsonIgnore] or [JsonProperty] if (serialized != null) { var jsonPropertyAttribute = new CodeAttributeDeclaration(); jsonPropertyAttribute.Name = serialized == true ? "Newtonsoft.Json.JsonPropertyAttribute" : "Newtonsoft.Json.JsonIgnoreAttribute"; CodeDomUtilities.EnsureAttribute(member, jsonPropertyAttribute, true); } } } } }
protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e) { }
private void GenerateOnParentChangedMethod(IReference input, CodeMemberProperty property, ITransformationContext context) { var onParentChanged = new CodeMemberMethod() { Name = "OnParentChanged", Attributes = MemberAttributes.Family | MemberAttributes.Override, ReturnType = new CodeTypeReference(typeof(void)) }; onParentChanged.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IModelElement).ToTypeReference(), "newParent")); onParentChanged.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IModelElement).ToTypeReference(), "oldParent")); var appendix = property.Name; if (appendix == "Parent") { appendix += "Reference"; } var oldElementVar = new CodeVariableReferenceExpression("old" + appendix); var newElementVar = new CodeVariableReferenceExpression("new" + appendix); var castRef = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ModelHelper).ToTypeReference()), "CastAs", property.Type); var nullRef = new CodePrimitiveExpression(null); var thisRef = new CodeThisReferenceExpression(); onParentChanged.Statements.Add(new CodeVariableDeclarationStatement(property.Type, oldElementVar.VariableName, new CodeMethodInvokeExpression(castRef, new CodeArgumentReferenceExpression("oldParent")))); onParentChanged.Statements.Add(new CodeVariableDeclarationStatement(property.Type, newElementVar.VariableName, new CodeMethodInvokeExpression(castRef, new CodeArgumentReferenceExpression("newParent")))); CodeStatement unsetOld; CodeStatement setNew; string oppositeName = context.Trace.ResolveIn(this, input.Opposite).Name; if (input.Opposite.UpperBound == 1) { unsetOld = new CodeAssignStatement(new CodePropertyReferenceExpression(oldElementVar, oppositeName), nullRef); setNew = new CodeAssignStatement(new CodePropertyReferenceExpression(newElementVar, oppositeName), thisRef); } else { unsetOld = new CodeExpressionStatement(new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(oldElementVar, oppositeName), "Remove", thisRef)); setNew = new CodeExpressionStatement(new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(newElementVar, oppositeName), "Add", thisRef)); } onParentChanged.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression(oldElementVar, CodeBinaryOperatorType.IdentityInequality, nullRef), unsetOld)); onParentChanged.Statements.Add(new CodeConditionStatement( new CodeBinaryOperatorExpression(newElementVar, CodeBinaryOperatorType.IdentityInequality, nullRef), setNew)); var valueChangedEvArgs = typeof(ValueChangedEventArgs).ToTypeReference(); var valueChangeDef = new CodeVariableDeclarationStatement(valueChangedEvArgs, "e", new CodeObjectCreateExpression(valueChangedEvArgs, oldElementVar, newElementVar)); var valueChangeRef = new CodeVariableReferenceExpression(valueChangeDef.Name); onParentChanged.Statements.Add(valueChangeDef); var referenceRef = new CodeFieldReferenceExpression(null, "_" + input.Name.ToCamelCase() + "Reference"); onParentChanged.Statements.Add(property.CreateOnChangedEventPattern(valueChangedEvArgs, valueChangeRef)); onParentChanged.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanged", new CodePrimitiveExpression(property.Name), valueChangeRef, referenceRef)); onParentChanged.Statements.Add(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), onParentChanged.Name, new CodeArgumentReferenceExpression("newParent"), new CodeArgumentReferenceExpression("oldParent"))); onParentChanged.WriteDocumentation("Gets called when the parent model element of the current model element changes", null, new Dictionary <string, string>() { { "oldParent", "The old parent model element" }, { "newParent", "The new parent model element" } }); onParentChanged.SetMerge(other => { var mergedOnParent = new CodeMemberMethod() { Name = "OnParentChanged", Attributes = MemberAttributes.Family | MemberAttributes.Override, ReturnType = new CodeTypeReference(typeof(void)) }; for (int i = 0; i < onParentChanged.Parameters.Count; i++) { mergedOnParent.Parameters.Add(onParentChanged.Parameters[i]); } var otherCasted = other as CodeMemberMethod; mergedOnParent.Statements.AddRange(otherCasted.Statements); mergedOnParent.Statements.RemoveAt(mergedOnParent.Statements.Count - 1); mergedOnParent.Statements.AddRange(onParentChanged.Statements); mergedOnParent.Statements.Remove(valueChangeDef); return(mergedOnParent); }); property.DependentMembers(true).Add(onParentChanged); }
Tuple <CodeTypeDeclaration, CodeTypeDeclaration> GenerateFunctionType(XPathFunctionInfo[] functions) { XPathFunctionInfo first = functions.First(); XPathFunctionInfo leastParameters = functions.OrderBy(f => f.Parameters.Count).First(); XPathFunctionInfo mostParameters = functions.OrderByDescending(f => f.Parameters.Count).First(); XPathModuleInfo module = first.Module; int minArgs = leastParameters.Parameters.Count; int maxArgs = mostParameters.Parameters.Count; CodeExpression thisRef = new CodeThisReferenceExpression(); var processorField = new CodeMemberField { Name = "_processor", Type = new CodeTypeReference(typeof(SaxonProcessor)) }; var funcNameField = new CodeMemberField { Name = "_FunctionName", Type = new CodeTypeReference(typeof(QName)), InitExpression = new CodeObjectCreateExpression( typeof(QName), new CodePrimitiveExpression(module.Namespace), new CodePrimitiveExpression(first.Name) ) }; var argTypesField = new CodeMemberField { Name = "_ArgumentTypes", Type = new CodeTypeReference(typeof(XdmSequenceType[])), InitExpression = new CodeArrayCreateExpression( typeof(XdmSequenceType), mostParameters.Parameters.Select(p => new CodeObjectCreateExpression( typeof(XdmSequenceType), GetXdmItemTypeExpression(p.Type.ItemType), new CodePrimitiveExpression(GetOcurrenceIndicator(p.Type.Cardinality)) )).ToArray() ) }; var resultTypesField = new CodeMemberField { Name = "_resultTypes", Type = new CodeTypeReference(typeof(XdmSequenceType[])) }; var resultTypesFieldInit = new CodeArrayCreateExpression { CreateType = resultTypesField.Type, Size = functions.Length }; for (int i = 0; i < functions.Length; i++) { XPathFunctionInfo function = functions[i]; resultTypesFieldInit.Initializers.Add( // Using item()? instead of empty-sequence() (function.ReturnType.IsEmptySequence) ? new CodeObjectCreateExpression( typeof(XdmSequenceType), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(XdmAnyItemType)), "Instance" ), new CodePrimitiveExpression(GetOcurrenceIndicator(XPathSequenceCardinality.ZeroOrOne)) ) : new CodeObjectCreateExpression( typeof(XdmSequenceType), GetXdmItemTypeExpression(function.ReturnType.ItemType), new CodePrimitiveExpression(GetOcurrenceIndicator(function.ReturnType.Cardinality)) ) ); } resultTypesField.InitExpression = resultTypesFieldInit; var defClass = new CodeTypeDeclaration { Name = first.Method.Name + "Function", Attributes = MemberAttributes.Public, BaseTypes = { typeof(ExtensionFunctionDefinition) }, Members = { processorField, funcNameField, argTypesField, resultTypesField, new CodeConstructor { Attributes = MemberAttributes.Public, Parameters = { new CodeParameterDeclarationExpression(processorField.Type, "processor") }, Statements = { new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, processorField.Name), new CodeVariableReferenceExpression("processor") ) } }, new CodeMemberProperty { Name = "FunctionName", Type = funcNameField.Type, Attributes = MemberAttributes.Public | MemberAttributes.Override, HasGet = true, GetStatements = { new CodeMethodReturnStatement(new CodeFieldReferenceExpression(thisRef,funcNameField.Name)) } }, new CodeMemberProperty { Name = "ArgumentTypes", Type = argTypesField.Type, Attributes = MemberAttributes.Public | MemberAttributes.Override, HasGet = true, GetStatements = { new CodeMethodReturnStatement(new CodeFieldReferenceExpression(thisRef,argTypesField.Name)) } }, new CodeMemberProperty { Name = "MaximumNumberOfArguments", Type = new CodeTypeReference(typeof(int)), Attributes = MemberAttributes.Public | MemberAttributes.Override, HasGet = true, GetStatements = { new CodeMethodReturnStatement(new CodePrimitiveExpression(maxArgs)) } }, new CodeMemberProperty { Name = "MinimumNumberOfArguments", Type = new CodeTypeReference(typeof(int)), Attributes = MemberAttributes.Public | MemberAttributes.Override, HasGet = true, GetStatements = { new CodeMethodReturnStatement(new CodePrimitiveExpression(minArgs)) } }, GenerateResultTypeMethod(thisRef, resultTypesField) } }; if (first.HasSideEffects) { defClass.Members.Add(new CodeMemberProperty { Name = "HasSideEffects", Type = new CodeTypeReference(typeof(bool)), Attributes = MemberAttributes.Public | MemberAttributes.Override, HasGet = true, GetStatements = { new CodeMethodReturnStatement(new CodePrimitiveExpression(true)) } }); } var callClass = new CodeTypeDeclaration { Name = defClass.Name + "Call", Attributes = MemberAttributes.Assembly, BaseTypes = { new CodeTypeReference(typeof(ExtensionFunctionCall)) }, Members = { processorField, new CodeConstructor { Attributes = MemberAttributes.Public, Parameters = { new CodeParameterDeclarationExpression(processorField.Type,"processor") }, Statements = { new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, processorField.Name), new CodeVariableReferenceExpression("processor") ) } } } }; CodeMemberMethod initializeMethod = null; if (!module.TypeIsStatic && module.Dependencies.Count > 0) { CodeExpression staticBaseUriExpr = null; if (module.Dependencies.Any(d => d.Type == typeof(XmlResolver))) { var staticBaseUriField = new CodeMemberField { Name = "_staticBaseUri", Type = new CodeTypeReference(typeof(Uri)) }; callClass.Members.Add(staticBaseUriField); var staticContextParam = new CodeParameterDeclarationExpression(typeof(StaticContext), "context"); staticBaseUriExpr = new CodeFieldReferenceExpression(thisRef, staticBaseUriField.Name); callClass.Members.Add(new CodeMemberMethod { Name = "SupplyStaticContext", Attributes = MemberAttributes.Public | MemberAttributes.Override, Parameters = { staticContextParam }, Statements = { new CodeAssignStatement { Left = staticBaseUriExpr, Right = new CodePropertyReferenceExpression{ PropertyName = "BaseUri", TargetObject = new CodeVariableReferenceExpression(staticContextParam.Name) } } } }); } initializeMethod = GenerateInitialize(module, new CodeFieldReferenceExpression(thisRef, processorField.Name), staticBaseUriExpr); callClass.Members.Add(initializeMethod); } callClass.Members.Add(GenerateCallMethod(functions, minArgs, maxArgs, new CodeFieldReferenceExpression(thisRef, processorField.Name), initializeMethod)); defClass.Members.Add( new CodeMemberMethod { Name = "MakeFunctionCall", Attributes = MemberAttributes.Public | MemberAttributes.Override, ReturnType = new CodeTypeReference(typeof(ExtensionFunctionCall)), Statements = { new CodeMethodReturnStatement( new CodeObjectCreateExpression( callClass.Name, new CodeFieldReferenceExpression(thisRef, processorField.Name) ) ) } } ); return(Tuple.Create(defClass, callClass)); }
/// <summary> /// Generates the set statements of a normal reference /// </summary> /// <param name="property">The NMeta reference</param> /// <param name="codeProperty">The generated code property</param> /// <param name="fieldReference">A reference to the backening field</param> /// <remarks>Normal means in this case that the reference is not an overridden container reference</remarks> protected virtual void GenerateSetStatement(IReference property, CodeMemberProperty codeProperty, CodeExpression fieldReference, ITransformationContext context) { var ifStmt = new CodeConditionStatement(); var val = new CodePropertySetValueReferenceExpression(); ifStmt.Condition = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityInequality, val); var assignment = new CodeAssignStatement(fieldReference, val); var oldDef = new CodeVariableDeclarationStatement(codeProperty.Type, "old", fieldReference); var oldRef = new CodeVariableReferenceExpression("old"); ifStmt.TrueStatements.Add(oldDef); var valueChangeTypeRef = typeof(ValueChangedEventArgs).ToTypeReference(); var valueChangeDef = new CodeVariableDeclarationStatement(valueChangeTypeRef, "e", new CodeObjectCreateExpression(typeof(ValueChangedEventArgs).ToTypeReference(), oldRef, val)); var valueChangeRef = new CodeVariableReferenceExpression(valueChangeDef.Name); ifStmt.TrueStatements.Add(valueChangeDef); var referenceRef = new CodeFieldReferenceExpression(null, "_" + property.Name.ToCamelCase() + "Reference"); ifStmt.TrueStatements.Add(codeProperty.CreateOnChangingEventPattern(typeof(ValueChangedEventArgs).ToTypeReference(), valueChangeRef)); ifStmt.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanging", new CodePrimitiveExpression(codeProperty.Name), valueChangeRef, referenceRef)); var targetClass = property.Type; var nullRef = new CodePrimitiveExpression(null); var thisRef = new CodeThisReferenceExpression(); var oldNotNull = new CodeBinaryOperatorExpression(oldRef, CodeBinaryOperatorType.IdentityInequality, nullRef); var valueNotNull = new CodeBinaryOperatorExpression(val, CodeBinaryOperatorType.IdentityInequality, nullRef); ifStmt.TrueStatements.Add(assignment); var oldCheck = new CodeConditionStatement(oldNotNull); var newCheck = new CodeConditionStatement(valueNotNull); if (property.Opposite != null) { var oppositeName = context.Trace.ResolveIn(this, property.Opposite).Name; var oldOpposite = new CodePropertyReferenceExpression(oldRef, oppositeName); var valOpposite = new CodePropertyReferenceExpression(val, oppositeName); if (property.Opposite.UpperBound == 1) { oldCheck.TrueStatements.Add(new CodeAssignStatement(oldOpposite, nullRef)); newCheck.TrueStatements.Add(new CodeAssignStatement(valOpposite, thisRef)); } else { oldCheck.TrueStatements.Add(new CodeMethodInvokeExpression(oldOpposite, "Remove", thisRef)); var addThis = new CodeMethodInvokeExpression(valOpposite, "Add", thisRef); if (property.Opposite.IsUnique) { newCheck.TrueStatements.Add(addThis); } else { var ifNotContains = new CodeConditionStatement(new CodeBinaryOperatorExpression( new CodeMethodInvokeExpression(valOpposite, "Contains", thisRef), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true))); ifNotContains.TrueStatements.Add(addThis); newCheck.TrueStatements.Add(ifNotContains); } } if (property.Opposite.IsContainment) { ifStmt.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(thisRef, "Parent"), val)); } } if (property.IsContainment) { oldCheck.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(oldRef, "Parent"), nullRef)); newCheck.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(val, "Parent"), thisRef)); } if (!(property.Opposite?.IsContainment).GetValueOrDefault(false)) { var resetEvent = property.IsContainment ? "ParentChanged" : "Deleted"; oldCheck.TrueStatements.Add(new CodeRemoveEventStatement( new CodeEventReferenceExpression(oldRef, resetEvent), new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name))); newCheck.TrueStatements.Add(new CodeAttachEventStatement( new CodeEventReferenceExpression(val, resetEvent), new CodeMethodReferenceExpression(thisRef, "OnReset" + codeProperty.Name))); } ifStmt.TrueStatements.Add(oldCheck); ifStmt.TrueStatements.Add(newCheck); ifStmt.TrueStatements.Add(codeProperty.CreateOnChangedEventPattern(typeof(ValueChangedEventArgs).ToTypeReference(), valueChangeRef)); ifStmt.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "OnPropertyChanged", new CodePrimitiveExpression(codeProperty.Name), valueChangeRef, referenceRef)); codeProperty.SetStatements.Add(ifStmt); codeProperty.HasSet = true; }
protected override CodeTypeDeclaration BeginClass() { soapBinding = (SoapBinding)Binding.Extensions.Find(typeof(SoapBinding)); CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName); codeClass.IsPartial = true; string location = null; if (Port != null) { SoapAddressBinding sab = (SoapAddressBinding)Port.Extensions.Find(typeof(SoapAddressBinding)); if (sab != null) { location = sab.Location; } } string namspace = (Port != null ? Port.Binding.Namespace : Binding.ServiceDescription.TargetNamespace); string name = (Port != null ? Port.Name : Binding.Name); if (Style == ServiceDescriptionImportStyle.Client) { CodeTypeReference ctr = new CodeTypeReference("System.Web.Services.Protocols.SoapHttpClientProtocol"); codeClass.BaseTypes.Add(ctr); } else { CodeTypeReference ctr = new CodeTypeReference("System.Web.Services.WebService"); codeClass.BaseTypes.Add(ctr); CodeAttributeDeclaration attws = new CodeAttributeDeclaration("System.Web.Services.WebServiceAttribute"); attws.Arguments.Add(GetArg("Namespace", namspace)); AddCustomAttribute(codeClass, attws, true); } CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.WebServiceBinding"); att.Arguments.Add(GetArg("Name", name)); att.Arguments.Add(GetArg("Namespace", namspace)); AddCustomAttribute(codeClass, att, true); if (Style == ServiceDescriptionImportStyle.Client) { CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public; GenerateServiceUrl(location, cc.Statements); if (ProtocolName.ToUpper() == "SOAP12") { CodeExpression thisSoapVer = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion"); CodeFieldReferenceExpression soap12Enum = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapProtocolVersion)), "Soap12"); cc.Statements.Add(new CodeAssignStatement(thisSoapVer, soap12Enum)); } codeClass.Members.Add(cc); } memberIds = new CodeIdentifiers(); headerVariables = new Hashtable(); return(codeClass); }
/// <summary> /// Creates a class declaration /// </summary> /// <param name="schema">record schema</param> /// <param name="ns">namespace</param> /// <returns></returns> protected virtual CodeTypeDeclaration processRecord(Schema schema) { RecordSchema recordSchema = schema as RecordSchema; if (null == recordSchema) { throw new CodeGenException("Unable to cast schema into a record"); } bool isError = recordSchema.Tag == Schema.Type.Error; // declare the class var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name)); ctd.BaseTypes.Add(isError ? "SpecificException" : "ISpecificRecord"); ctd.Attributes = MemberAttributes.Public; ctd.IsClass = true; ctd.IsPartial = true; if (recordSchema.Documentation != null) { ctd.Comments.Add(createDocComment(recordSchema.Documentation)); } createSchemaField(schema, ctd, isError); // declare Get() to be used by the Writer classes var cmmGet = new CodeMemberMethod(); cmmGet.Name = "Get"; cmmGet.Attributes = MemberAttributes.Public; cmmGet.ReturnType = new CodeTypeReference("System.Object"); cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); // declare Put() to be used by the Reader classes var cmmPut = new CodeMemberMethod(); cmmPut.Name = "Put"; cmmPut.Attributes = MemberAttributes.Public; cmmPut.ReturnType = new CodeTypeReference(typeof(void)); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue")); var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); if (isError) { cmmGet.Attributes |= MemberAttributes.Override; cmmPut.Attributes |= MemberAttributes.Override; } foreach (Field field in recordSchema.Fields) { // Determine type of field bool nullibleEnum = false; string baseType = getType(field.Schema, false, ref nullibleEnum); var ctrfield = new CodeTypeReference(baseType); // Create field string privFieldName = string.Concat("_", field.Name); var codeField = new CodeMemberField(ctrfield, privFieldName); codeField.Attributes = MemberAttributes.Private; // Process field documentation if it exist and add to the field CodeCommentStatement propertyComment = null; if (!string.IsNullOrEmpty(field.Documentation)) { propertyComment = createDocComment(field.Documentation); if (null != propertyComment) { codeField.Comments.Add(propertyComment); } } // Add field to class ctd.Members.Add(codeField); // Create reference to the field - this.fieldname var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName); var mangledName = CodeGenUtil.Instance.Mangle(field.Name); // Create field property with get and set methods var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = mangledName; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression())); if (null != propertyComment) { property.Comments.Add(propertyComment); } // Add field property to class ctd.Members.Add(property); // add to Get() getFieldStmt.Append("\t\t\tcase "); getFieldStmt.Append(field.Pos); getFieldStmt.Append(": return this."); getFieldStmt.Append(mangledName); getFieldStmt.Append(";\n"); // add to Put() putFieldStmt.Append("\t\t\tcase "); putFieldStmt.Append(field.Pos); putFieldStmt.Append(": this."); putFieldStmt.Append(mangledName); if (nullibleEnum) { putFieldStmt.Append(" = fieldValue == null ? ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")null : ("); string type = baseType.Remove(0, 16); // remove System.Nullable< type = type.Remove(type.Length - 1); // remove > putFieldStmt.Append(type); putFieldStmt.Append(")fieldValue; break;\n"); } else { putFieldStmt.Append(" = ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")fieldValue; break;\n"); } } // end switch block for Get() getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}"); var cseGet = new CodeSnippetExpression(getFieldStmt.ToString()); cmmGet.Statements.Add(cseGet); ctd.Members.Add(cmmGet); // end switch block for Put() putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}"); var csePut = new CodeSnippetExpression(putFieldStmt.ToString()); cmmPut.Statements.Add(csePut); ctd.Members.Add(cmmPut); string nspace = recordSchema.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for record schema " + recordSchema.Name); } CodeNamespace codens = addNamespace(nspace); codens.Types.Add(ctd); return(ctd); }
public static CodeCompileUnit GenerateCompileUnit(ITextTemplatingEngineHost host, ParsedTemplate pt, TemplateSettings settings) { //prep the compile unit var ccu = new CodeCompileUnit(); var namespac = new CodeNamespace(settings.Namespace); ccu.Namespaces.Add(namespac); var imports = new Dictionary <string, object> (); UnionWith(imports, settings.Imports); UnionWith(imports, host.StandardImports); foreach (string ns in imports.Keys) { namespac.Imports.Add(new CodeNamespaceImport(ns)); } //prep the type var type = new CodeTypeDeclaration(settings.Name); type.IsPartial = true; if (!String.IsNullOrEmpty(settings.Inherits)) { type.BaseTypes.Add(new CodeTypeReference(settings.Inherits)); } else { type.BaseTypes.Add(new CodeTypeReference(typeof(TextTransformation))); } namespac.Types.Add(type); //prep the transform method var transformMeth = new CodeMemberMethod() { Name = "TransformText", ReturnType = new CodeTypeReference(typeof(String)), Attributes = MemberAttributes.Public | MemberAttributes.Override }; AddCodeDocComment(transformMeth, @"<summary> Generates the text output of the transformation. </summary> <returns> A string representing the generated text output of the text template transformation process. </returns> <remarks> The text template transformation process has two steps. In the first step, the text template transformation engine creates a class that is named the generated transformation class. In the second step, the engine compiles and executes the generated transformation class, to produce the generated text output. The engine calls <see cref=""TransformText""/> on the compiled generated transformation class to execute the text template and generate the text output. </remarks>"); //method references that will need to be used multiple times var writeMeth = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "Write"); bool helperMode = false; //build the code from the segments foreach (TemplateSegment seg in pt.Content) { CodeStatement st = null; var location = new CodeLinePragma(seg.StartLocation.FileName ?? host.TemplateFile, seg.StartLocation.Line); switch (seg.Type) { case SegmentType.Block: if (helperMode) { //TODO: are blocks permitted after helpers? throw new ParserException("Blocks are not permitted after helpers", seg.StartLocation); } st = new CodeSnippetStatement(seg.Text); break; case SegmentType.Expression: st = new CodeExpressionStatement( new CodeMethodInvokeExpression(writeMeth, new CodeSnippetExpression(seg.Text))); break; case SegmentType.Content: st = new CodeExpressionStatement(new CodeMethodInvokeExpression(writeMeth, new CodePrimitiveExpression(seg.Text))); break; case SegmentType.Helper: type.Members.Add(new CodeSnippetTypeMember(seg.Text) { LinePragma = location }); helperMode = true; break; default: throw new InvalidOperationException(); } if (st != null) { if (helperMode) { //convert the statement into a snippet member and attach it to the top level type //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python? using (var writer = new StringWriter()) { settings.Provider.GenerateCodeFromStatement(st, writer, null); type.Members.Add(new CodeSnippetTypeMember(writer.ToString()) { LinePragma = location }); } } else { st.LinePragma = location; transformMeth.Statements.Add(st); continue; } } } //complete the transform method transformMeth.Statements.Add(new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodePropertyReferenceExpression( new CodeThisReferenceExpression(), "GenerationEnvironment"), "ToString"))); type.Members.Add(transformMeth); //generate the Host property if needed if (settings.HostSpecific) { var hostField = new CodeMemberField(new CodeTypeReference(typeof(ITextTemplatingEngineHost)), "hostValue"); hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private; type.Members.Add(hostField); var hostProp = new CodeMemberProperty() { Name = "Host", Attributes = MemberAttributes.Public, HasGet = true, HasSet = true, Type = hostField.Type }; var hostFieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "hostValue"); hostProp.SetStatements.Add(new CodeAssignStatement(hostFieldRef, new CodePropertySetValueReferenceExpression())); hostProp.GetStatements.Add(new CodeMethodReturnStatement(hostFieldRef)); type.Members.Add(hostProp); } return(ccu); }
public void Visit(CodeFieldReferenceExpression o) { g.GenerateFieldReferenceExpression(o); }
//Generate code for implementation of List interface private void GenerateListInterface() { CodeNamespace ns = new CodeNamespace("GenericList"); compileUnit.Namespaces.Add(ns); ns.Types.Add(GetListInterface()); //Partial class LinkedList CodeTypeDeclaration listClassPartTwo = new CodeTypeDeclaration("LinkedList"); //Add type parameters to class & mark partial listClassPartTwo.TypeParameters.Add(keyTypeParameter); listClassPartTwo.TypeParameters.Add(itemTypeParameter); listClassPartTwo.BaseTypes.Add(typeof(object)); CodeTypeReference listInterface = new CodeTypeReference("ILinkedList", new CodeTypeReference(keyTypeParameter), new CodeTypeReference(itemTypeParameter)); listClassPartTwo.BaseTypes.Add(listInterface); listClassPartTwo.IsPartial = true; //Add Method AddHead #region C# code //public void AddHead(K key,T item) //{ // Node<K,T> newNode = new Node<K,T>(key, item, header.NextNode); // header.NextNode = newNode; //} #endregion CodeStatementCollection addHeadColl = new CodeStatementCollection(); //header.NextNode CodeFieldReferenceExpression headerNextNodeRefExprn = new CodeFieldReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "header"), "NextNode"); //new Node<K,T>(key, item, header.NextNode) CodeObjectCreateExpression newExpr = new CodeObjectCreateExpression( nodeType, new CodeExpression[] { new CodeArgumentReferenceExpression("key"), new CodeArgumentReferenceExpression("item"), headerNextNodeRefExprn }); //Node<K,T> newNode = new Node<K,T>(key, item, header.NextNode) CodeVariableDeclarationStatement newNodeDecStmt = new CodeVariableDeclarationStatement( nodeType, "newNode", newExpr); //Header.NextNode = newNode CodeAssignStatement assignStmt = new CodeAssignStatement( headerNextNodeRefExprn, new CodeVariableReferenceExpression("newNode")); addHeadColl.Add(newNodeDecStmt); addHeadColl.Add(assignStmt); //Generate AddHead CodeMemberMethod addHeadMethod = GeneratePublicMethod("AddHead", null, new CodeTypeReference[] { keyType, itemType }, new string[] { "key", "item" }, addHeadColl); addHeadMethod.ImplementationTypes.Add(listInterface); listClassPartTwo.Members.Add(addHeadMethod); //Add method Find #region C# code //public T Find(K key) //{ // for (Node<K,T> current = this.header; (current != null); current = current.NextNode) { // if ((current.Key.CompareTo(key) == 0)) // { // return current.Item; // } //} #endregion CodeStatementCollection findColl = new CodeStatementCollection(); //current.Key CodeFieldReferenceExpression fieldRefExpr = new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("current"), "Key"); //current.Key.CompareTo(key) CodeMethodInvokeExpression compareToMethodInvStmt = new CodeMethodInvokeExpression( fieldRefExpr, "CompareTo", new CodeExpression[] { new CodeArgumentReferenceExpression("key") }); //(current.Key.CompareTo(key) == 0) CodeBinaryOperatorExpression ifCondExpr = new CodeBinaryOperatorExpression( compareToMethodInvStmt, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)); //return current.Item CodeMethodReturnStatement retStmt = new CodeMethodReturnStatement(new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("current"), "Item")); //if ((current.Key.CompareTo(key) == 0)) CodeConditionStatement ifStatement = new CodeConditionStatement( ifCondExpr, new CodeStatement[] { retStmt } ); //this.header CodeFieldReferenceExpression headerRefExpr = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "header"); //Node<K,T> current = this.header CodeVariableDeclarationStatement indexDeclrnStmt = new CodeVariableDeclarationStatement( nodeType, "current", headerRefExpr); //current != null CodeBinaryOperatorExpression condExpr = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("current"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); //current = current.NextNode CodeAssignStatement incrementStmt = new CodeAssignStatement( new CodeVariableReferenceExpression("current"), new CodeFieldReferenceExpression( new CodeVariableReferenceExpression("current"), "NextNode") ); //for (Node<K,T> current = this.header; (current != null); current = current.NextNode) CodeIterationStatement forStatement = new CodeIterationStatement( indexDeclrnStmt, condExpr, incrementStmt, new CodeStatement[] { ifStatement }); findColl.Add(forStatement); //return this.header.Item CodeMethodReturnStatement retHdrStmt = new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "header"), "Item") ); findColl.Add(retHdrStmt); //Find method CodeMemberMethod findMethod = GeneratePublicMethod("Find", itemType, new CodeTypeReference[] { keyType }, new string[] { "key" }, findColl); findMethod.ImplementationTypes.Add(listInterface); listClassPartTwo.Members.Add(findMethod); //Add property #region C# code //public T this[K key] //{ // get // { // return Find(key); // } //} #endregion CodeMemberProperty itemProperty = new CodeMemberProperty(); itemProperty.Attributes = (itemProperty.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; itemProperty.Parameters.Add(new CodeParameterDeclarationExpression(keyType, "key")); itemProperty.Name = "Item"; itemProperty.GetStatements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeThisReferenceExpression(), "Find"), new CodeArgumentReferenceExpression("key"))) ); itemProperty.Type = itemType; listClassPartTwo.Members.Add(itemProperty); ns.Types.Add(listClassPartTwo); TextWriter tw = new StreamWriter(path + @"\ListInterface." + provider.FileExtension, false); provider.GenerateCodeFromNamespace(ns, tw, options); tw.Close(); }
protected abstract void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e);
public FieldRef(CodeExpression targetObject, string fieldName) { myExpression = new CodeFieldReferenceExpression(targetObject, fieldName); }
protected override void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e) { Output.Write("[CodeFieldReferenceExpression: Name={0}, Target=", e.FieldName); this.GenerateExpression(e.TargetObject); Output.Write("]"); }
protected abstract void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e);
public static CodeMemberMethod CreateXRootMethod(string returnType, string methodName, string[][] paramList, GeneratedTypesVisibility visibility = GeneratedTypesVisibility.Public) { CodeTypeReference xRootType = new CodeTypeReference(returnType); CodeMemberMethod staticMethod = new CodeMemberMethod(); staticMethod.Name = methodName; staticMethod.Attributes = visibility.ToMemberAttribute() | MemberAttributes.Static; staticMethod.ReturnType = xRootType; CodeExpression[] parameterExp = new CodeExpression[paramList.Length]; for (int i = 0; i < paramList.Length; i++) { string[] paramRef = paramList[i]; // index 0 is the type name and index 1 is the parameter name staticMethod.Parameters.Add(CreateParameter(paramRef[1], paramRef[0])); parameterExp[i] = new CodeVariableReferenceExpression(paramRef[1]); } CodeExpression rootExp = new CodeVariableReferenceExpression("root"); CodeExpression doc = new CodeFieldReferenceExpression(rootExp, "doc"); staticMethod.Statements.Add( //XRoot root = new XRoot; new CodeVariableDeclarationStatement(xRootType, "root", new CodeObjectCreateExpression(xRootType))); staticMethod.Statements.Add( //root.doc = XDocument.Load(xmlFile); new CodeAssignStatement( doc, CreateMethodCall(new CodeTypeReferenceExpression("XDocument"), methodName, parameterExp))); staticMethod.Statements.Add( //XTypedElement typedRoot = XTypedServices.ToXTypedElement(....) new CodeVariableDeclarationStatement( Constants.XTypedElement, "typedRoot", CreateMethodCall( new CodeTypeReferenceExpression(Constants.XTypedServices), Constants.ToXTypedElement, new CodePropertyReferenceExpression(doc, "Root"), CodeDomHelper.SingletonTypeManager()))); staticMethod.Statements.Add( //if(typedRoot == null) new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("typedRoot"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeThrowExceptionStatement( new CodeObjectCreateExpression(Constants.LinqToXsdException, new CodePrimitiveExpression("Invalid root element in xml document.")) ))); staticMethod.Statements.Add( //root.rootObject = typedRoot new CodeAssignStatement( new CodeFieldReferenceExpression(rootExp, "rootObject"), new CodeVariableReferenceExpression("typedRoot"))); staticMethod.Statements.Add( //return root; new CodeMethodReturnStatement(rootExp)); return(staticMethod); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TestingStructs"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.DeclareValueTypes)) { // GENERATES (C#): // public int CallingStructMethod(int i) { // StructImplementation o = new StructImplementation (); // return o.StructMethod(i); // } AddScenario ("CheckCallingStructMethod"); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "CallingStructMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("StructImplementation"), "o", new CodeObjectCreateExpression (new CodeTypeReference ("StructImplementation")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression ( new CodeVariableReferenceExpression ("o"), "StructMethod"), new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingValueStruct(int i) { // ValueStruct StructObject = new ValueStruct(); // StructObject.x = i; // return StructObject.x; // } AddScenario ("CheckUsingValueStruct"); cmm = new CodeMemberMethod (); cmm.Name = "UsingValueStruct"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("ValueStruct", "StructObject", new CodeObjectCreateExpression ("ValueStruct"))); cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"), new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingStructProperty(int i) { // StructImplementation StructObject = new StructImplementation(); // StructObject.UseIField = i; // return StructObject.UseIField; // } AddScenario ("CheckUsingStructProperty"); cmm = new CodeMemberMethod (); cmm.Name = "UsingStructProperty"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("StructImplementation", "StructObject", new CodeObjectCreateExpression ("StructImplementation"))); cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("StructObject"), "UseIField"), new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "UseIField"))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingInterfaceStruct(int i) { // ImplementInterfaceStruct IStructObject = new ImplementInterfaceStruct(); // return IStructObject.InterfaceMethod(i); // } if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { AddScenario ("CheckUsingInterfaceStruct"); // method to test struct implementing interfaces cmm = new CodeMemberMethod (); cmm.Name = "UsingInterfaceStruct"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("ImplementInterfaceStruct", "IStructObject", new CodeObjectCreateExpression ("ImplementInterfaceStruct"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression ( new CodeVariableReferenceExpression ("IStructObject"), "InterfaceMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); } // GENERATES (C#): // public struct StructImplementation { // int i; // public int UseIField { // get { // return i; // } // set { // i = value; // } // } // public int StructMethod(int i) { // return (5 + i); // } // } cd = new CodeTypeDeclaration ("StructImplementation"); cd.IsStruct = true; nspace.Types.Add (cd); // declare an integer field CodeMemberField field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "UseIField"; prop.Type = new CodeTypeReference (typeof (int)); prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression (); fref.FieldName = "i"; prop.GetStatements.Add (new CodeMethodReturnStatement (fref)); prop.SetStatements.Add (new CodeAssignStatement (fref, new CodePropertySetValueReferenceExpression ())); cd.Members.Add (prop); cmm = new CodeMemberMethod (); cmm.Name = "StructMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (5), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); // GENERATES (C#): // public struct ValueStruct { // public int x; // } cd = new CodeTypeDeclaration ("ValueStruct"); cd.IsStruct = true; nspace.Types.Add (cd); // declare an integer field field = new CodeMemberField (new CodeTypeReference (typeof (int)), "x"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // interface to be implemented // GENERATES (C#): // public interface InterfaceStruct { // int InterfaceMethod(int i); // } cd = new CodeTypeDeclaration ("InterfaceStruct"); cd.IsInterface = true; nspace.Types.Add (cd); // method in the interface cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cd.Members.Add (cmm); // struct to implement an interface // GENERATES (C#): // public struct ImplementInterfaceStruct : InterfaceStruct { // public int InterfaceMethod(int i) { // return (8 + i); // } // } cd = new CodeTypeDeclaration ("ImplementInterfaceStruct"); cd.BaseTypes.Add (new CodeTypeReference ("InterfaceStruct")); cd.IsStruct = true; nspace.Types.Add (cd); field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); // implement interface method cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceStruct")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (8), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i")))); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cd.Members.Add (cmm); } } }
public CodeMemberMethod GenerateWrapperMethod(Generator g) { CodeMemberMethod method; if (IsConstructor) method = new CodeConstructor () { Name = GetCSharpMethodName (Name) }; else method = new CodeMemberMethod () { Name = GetCSharpMethodName (Name) }; method.Attributes = MemberAttributes.Public; if (IsStatic) method.Attributes |= MemberAttributes.Static; CodeTypeReference rtype = g.CppTypeToCodeDomType (ReturnType); method.ReturnType = rtype; foreach (var p in Parameters) { bool byref; var ptype = g.CppTypeToCodeDomType (p.Type, out byref); var param = new CodeParameterDeclarationExpression (ptype, p.Name); if (byref) param.Direction = FieldDirection.Ref; method.Parameters.Add (param); } if (IsConstructor) { //this.native_ptr = impl.Alloc(this); method.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "native_ptr"), new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Alloc"), new CodeExpression [] { new CodeThisReferenceExpression () }))); } // Call the iface method CodeExpression[] args = new CodeExpression [Parameters.Count + (IsStatic ? 0 : 1)]; if (!IsStatic) args [0] = new CodeFieldReferenceExpression (null, "Native"); for (int i = 0; i < Parameters.Count; ++i) { bool byref; g.CppTypeToCodeDomType (Parameters [i].Type, out byref); CodeExpression arg = new CodeArgumentReferenceExpression (Parameters [i].Name); if (byref) arg = new CodeDirectionExpression (FieldDirection.Ref, arg); args [i + (IsStatic ? 0 : 1)] = arg; } var call = new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), Name), args); if (rtype.BaseType == "System.Void" || IsConstructor) method.Statements.Add (call); else method.Statements.Add (new CodeMethodReturnStatement (call)); return method; }