public override object Serialize(IDesignerSerializationManager manager, object value) { var baseSerializer = (CodeDomSerializer)manager .GetSerializer(typeof(ResourceManagerSetter).BaseType, typeof(CodeDomSerializer)); object codeObject = baseSerializer.Serialize(manager, value); var statements = codeObject as CodeStatementCollection; if (statements != null) { CodeExpression leftCodeExpression = new CodeVariableReferenceExpression("resources"); var classTypeDeclaration = (CodeTypeDeclaration)manager.GetService(typeof(CodeTypeDeclaration)); CodeExpression typeofExpression = new CodeTypeOfExpression(classTypeDeclaration.Name); CodeExpression rightCodeExpression = new CodeObjectCreateExpression(typeof(XafComponentResourceManager), new[] { typeofExpression }); //CodeExpression rightCodeExpression = // new CodeTypeReferenceExpression( // "new DevExpress.ExpressApp.Win.Templates"), // "XafComponentResourceManager", new[] { typeofExpression }); statements.Insert(0, new CodeAssignStatement(leftCodeExpression, rightCodeExpression)); } return codeObject; }
public void Constructor1_Deny_Unrestricted () { CodeTypeReference type = new CodeTypeReference ("System.Void"); CodeTypeOfExpression ctm = new CodeTypeOfExpression (type); Assert.AreSame (type, ctm.Type, "Type"); ctm.Type = new CodeTypeReference ("System.Int32"); }
public CodeRectangularArrayCreateExpression(CodeTypeReference createType, params CodeExpression[] lengths) { _typeOfExpr = new CodeTypeOfExpression(createType); _lengths = new CodeNotificationExpressionCollection(Refresh, lengths); Initialize(); Refresh(); }
internal BindingElementExtensionSectionGenerator(Type bindingElementType, Assembly userAssembly, CodeDomProvider provider) { this.bindingElementType = bindingElementType; this.userAssembly = userAssembly; this.provider = provider; string typePrefix = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)); this.generatedClassName = typePrefix + Constants.ElementSuffix; this.constantsClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.ConfigurationStrings; this.defaultValuesClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.Defaults; this.customBEVarInstance = Helpers.TurnFirstCharLower(bindingElementType.Name); customBEArgRef = new CodeArgumentReferenceExpression(customBEVarInstance); this.customBETypeRef = new CodeTypeReference(bindingElementType.Name); this.customBETypeOfRef = new CodeTypeOfExpression(customBETypeRef); this.customBENewVarAssignRef = new CodeVariableDeclarationStatement( customBETypeRef, customBEVarInstance, new CodeObjectCreateExpression(customBETypeRef)); this.bindingElementMethodParamRef = new CodeParameterDeclarationExpression( CodeDomHelperObjects.bindingElementTypeRef, Constants.bindingElementParamName); }
public CodeRectangularArrayCreateExpression() { _typeOfExpr = new CodeTypeOfExpression(); _lengths = new CodeNotificationExpressionCollection(Refresh); Initialize(); Refresh(); }
public static CodeTypeOfExpression Clone(this CodeTypeOfExpression expression) { if (expression == null) return null; CodeTypeOfExpression e = new CodeTypeOfExpression(); e.Type = expression.Type.Clone(); e.UserData.AddRange(expression.UserData); return e; }
public TypescriptTypeOfExpression( CodeTypeOfExpression codeExpression, CodeGeneratorOptions options, ITypescriptTypeMapper typescriptTypeMapper) { _codeExpression = codeExpression; _options = options; _typescriptTypeMapper = typescriptTypeMapper; System.Diagnostics.Debug.WriteLine("TypescriptTypeOfExpression Created"); }
/// <summary> /// When overridden in a derived class, returns code that is used during page execution to obtain the evaluated expression. /// </summary> /// <param name="entry">The object that represents information about the property bound to by the expression.</param> /// <param name="parsedData">The object containing parsed data as returned by <see cref="M:System.Web.Compilation.ExpressionBuilder.ParseExpression(System.String,System.Type,System.Web.Compilation.ExpressionBuilderContext)" />.</param> /// <param name="context">Contextual information for the evaluation of the expression.</param> /// <returns> /// A <see cref="T:System.CodeDom.CodeExpression" /> that is used for property assignment. /// </returns> public override CodeExpression GetCodeExpression( BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context ) { // from http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.getcodeexpression.aspx Type type1 = entry.DeclaringType; PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties( type1 )[entry.PropertyInfo.Name]; CodeExpression[] expressionArray1 = new CodeExpression[3]; expressionArray1[0] = new CodePrimitiveExpression( entry.Expression.Trim() ); expressionArray1[1] = new CodeTypeOfExpression( type1 ); expressionArray1[2] = new CodePrimitiveExpression( entry.Name ); return new CodeCastExpression( descriptor1.PropertyType, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression( base.GetType() ), "GetEvalData", expressionArray1 ) ); }
public void Constructor2 () { string baseType = "mono"; CodeTypeOfExpression ctoe = new CodeTypeOfExpression (baseType); Assert.IsNotNull (ctoe.Type, "#1"); Assert.AreEqual (baseType, ctoe.Type.BaseType, "#2"); ctoe = new CodeTypeOfExpression ((string) null); Assert.IsNotNull (ctoe.Type, "#3"); Assert.AreEqual (typeof (void).FullName, ctoe.Type.BaseType, "#4"); }
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { var expression = new CodeExpression[3]; expression[0] = new CodePrimitiveExpression(entry.Expression.Trim()); expression[1] = new CodeTypeOfExpression(typeof(string)); expression[2] = new CodePrimitiveExpression(entry.Name); return new CodeCastExpression(typeof(string), new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(GetType()), "GetEvalData", expression)); }
public void Constructor0 () { CodeTypeOfExpression ctoe = new CodeTypeOfExpression (); Assert.IsNotNull (ctoe.Type, "#1"); Assert.AreEqual (typeof (void).FullName, ctoe.Type.BaseType, "#2"); CodeTypeReference type = new CodeTypeReference ("mono"); ctoe.Type = type; Assert.IsNotNull (ctoe.Type, "#3"); Assert.AreSame (type, ctoe.Type, "#4"); ctoe.Type = null; Assert.IsNotNull (ctoe.Type, "#5"); Assert.AreEqual (typeof (void).FullName, ctoe.Type.BaseType, "#6"); }
internal StandardBindingSectionGenerator(Type standardBindingType, Assembly userAssembly, CodeDomProvider provider) { this.standardBindingType = standardBindingType; this.userAssembly = userAssembly; this.provider = provider; this.generatedElementClassName = standardBindingType.Name + Constants.ElementSuffix; this.constantsClassName = standardBindingType.Name.Substring(0, standardBindingType.Name.IndexOf(TypeNameConstants.Binding)) + Constants.ConfigurationStrings; this.defaultValuesClassName = standardBindingType.Name.Substring(0, standardBindingType.Name.IndexOf(TypeNameConstants.Binding)) + Constants.Defaults; this.generatedCollectionElementClassName = standardBindingType.Name + Constants.CollectionElementSuffix; this.customSBTypeRef = new CodeTypeReference(standardBindingType.Name); this.customSBTypeOfRef = new CodeTypeOfExpression(customSBTypeRef); this.bindingMethodParamRef = new CodeParameterDeclarationExpression( CodeDomHelperObjects.bindingTypeRef, Constants.bindingParamName); }
public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator, CodeTypeMemberCollection members) { List<CodeExpression> initializers = new List<CodeExpression>(); generator.DispatchTablePairs(table.Get("overloads").Table, members, exp => { initializers.Add(exp); }); var name = new CodePrimitiveExpression((table["name"] as string)); var type = new CodeTypeOfExpression(table["decltype"] as string); var array = new CodeArrayCreateExpression(typeof(IOverloadableMemberDescriptor), initializers.ToArray()); return new CodeExpression[] { new CodeObjectCreateExpression(typeof(OverloadedMethodMemberDescriptor), name, type, array) }; }
public void Constructor1 () { CodeTypeReference type1 = new CodeTypeReference ("mono1"); CodeTypeOfExpression ctoe = new CodeTypeOfExpression (type1); Assert.IsNotNull (ctoe.Type, "#1"); Assert.AreSame (type1, ctoe.Type, "#2"); ctoe.Type = null; Assert.IsNotNull (ctoe.Type, "#3"); Assert.AreEqual (typeof (void).FullName, ctoe.Type.BaseType, "#4"); CodeTypeReference type2 = new CodeTypeReference ("mono2"); ctoe.Type = type2; Assert.IsNotNull (ctoe.Type, "#5"); Assert.AreSame (type2, ctoe.Type, "#6"); ctoe = new CodeTypeOfExpression ((CodeTypeReference) null); Assert.IsNotNull (ctoe.Type, "#7"); Assert.AreEqual (typeof (void).FullName, ctoe.Type.BaseType, "#8"); }
public HardwireParameterDescriptor(Table tpar) { CodeExpression ename = new CodePrimitiveExpression(tpar.Get("name").String); CodeExpression etype = new CodeTypeOfExpression(tpar.Get("origtype").String); CodeExpression hasDefaultValue = new CodePrimitiveExpression(tpar.Get("default").Boolean); CodeExpression defaultValue = tpar.Get("default").Boolean ? (CodeExpression)(new CodeObjectCreateExpression(typeof(DefaultValue))) : (CodeExpression)(new CodePrimitiveExpression(null)); CodeExpression isOut = new CodePrimitiveExpression(tpar.Get("out").Boolean); CodeExpression isRef = new CodePrimitiveExpression(tpar.Get("ref").Boolean); CodeExpression isVarArg = new CodePrimitiveExpression(tpar.Get("varargs").Boolean); CodeExpression restrictType = tpar.Get("restricted").Boolean ? (CodeExpression)(new CodeTypeOfExpression(tpar.Get("type").String)) : (CodeExpression)(new CodePrimitiveExpression(null)); Expression = new CodeObjectCreateExpression(typeof(ParameterDescriptor), new CodeExpression[] { ename, etype, hasDefaultValue, defaultValue, isOut, isRef, isVarArg } ); ParamType = tpar.Get("origtype").String; HasDefaultValue = tpar.Get("default").Boolean; IsOut = tpar.Get("out").Boolean; IsRef = tpar.Get("ref").Boolean; }
private CodeExpression BuildExpression(XSharpParser.PrimaryExpressionContext expression) { CodeExpression expr = null; XSharpParser.PrimaryContext ctx = expression.Expr; // if (ctx is XSharpParser.SelfExpressionContext) // Self { expr = new CodeThisReferenceExpression(); } else if (ctx is XSharpParser.SuperExpressionContext) // Super { expr = new CodeBaseReferenceExpression(); } else if (ctx is XSharpParser.LiteralExpressionContext) { XSharpParser.LiteralExpressionContext lit = (XSharpParser.LiteralExpressionContext)ctx; expr = BuildLiteralValue(lit.Literal); } else if (ctx is XSharpParser.LiteralArrayExpressionContext) // { expr [, expr] } { XSharpParser.LiteralArrayContext arr = ((XSharpParser.LiteralArrayExpressionContext)ctx).LiteralArray; // Typed Array ? if (arr.Type != null) { List<CodeExpression> exprlist = new List<CodeExpression>(); foreach (var Element in arr._Elements) { exprlist.Add(BuildExpression(Element.Expr,true)); } expr = new CodeArrayCreateExpression(BuildDataType(arr.Type), exprlist.ToArray()); } else { expr = new CodeSnippetExpression(arr.GetText()); } } else if (ctx is XSharpParser.DelegateCtorCallContext) { XSharpParser.DelegateCtorCallContext delg = (XSharpParser.DelegateCtorCallContext)ctx; // CodeTypeReference ctr = BuildDataType(delg.Type); CodeExpression ce = BuildExpression(delg.Obj,false); // expr = new CodeDelegateCreateExpression(BuildDataType(delg.Type), BuildExpression(delg.Obj,false), delg.Func.GetText()); } else if (ctx is XSharpParser.CtorCallContext) { XSharpParser.CtorCallContext ctor = (XSharpParser.CtorCallContext)ctx; CodeTypeReference ctr = BuildDataType(ctor.Type); List<CodeExpression> exprlist = new List<CodeExpression>(); if (ctor.ArgList != null) { foreach (var arg in ctor.ArgList._Args) { // We should handle arg.Name if arg.ASSIGN_OP is not null... exprlist.Add(BuildExpression(arg.Expr,false)); } } expr = new CodeObjectCreateExpression(ctr.BaseType, exprlist.ToArray()); } else if (ctx is XSharpParser.TypeOfExpressionContext) { CodeTypeReference ctr = BuildDataType(((XSharpParser.TypeOfExpressionContext)ctx).Type); expr = new CodeTypeOfExpression(ctr); } else if (ctx is XSharpParser.NameExpressionContext) { String name = ((XSharpParser.NameExpressionContext)ctx).Name.Id.GetText(); // Sometimes, we will need to do it that way.... if (name.ToLower() == "self") { expr = new CodeThisReferenceExpression(); } else if (name.ToLower() == "super") { expr = new CodeBaseReferenceExpression(); } else { CodeTypeReference ctr = BuildSimpleName(((XSharpParser.NameExpressionContext)ctx).Name); expr = new CodeVariableReferenceExpression(name); } } else { expr = new CodeSnippetExpression(ctx.GetText()); } return expr; }
/// <devdoc> /// <para> /// Generates code for the specified CodeDom based type of expression /// representation. /// </para> /// </devdoc> private void GenerateTypeOfExpression(CodeTypeOfExpression e) { Output.Write("typeof("); OutputType(e.Type); Output.Write(")"); }
private static void ValidateTypeOfExpression(CodeTypeOfExpression e) { ValidateTypeReference(e.Type); }
/// <summary> /// Generates the code to store the views in a C# or a VB file based on the /// options passed in by the user. /// </summary> /// <param name="mappingCollection"></param> /// <param name="generatedViews"></param> /// <param name="sourceWriter"></param> /// <param name="provider"></param> /// <returns></returns> private static void GenerateAndStoreViews(StorageMappingItemCollection mappingCollection, Dictionary<EntitySetBase, string> generatedViews, TextWriter sourceWriter, CodeDomProvider provider, IList<EdmSchemaError> schemaErrors) { EdmItemCollection edmCollection = mappingCollection.EdmItemCollection; StoreItemCollection storeCollection = mappingCollection.StoreItemCollection; //Create an emtpty compile unit and build up the generated code CodeCompileUnit compileUnit = new CodeCompileUnit(); //Add the namespace for generated code CodeNamespace codeNamespace = new CodeNamespace(EntityViewGenerationConstants.NamespaceName); //Add copyright notice to the namespace comment. compileUnit.Namespaces.Add(codeNamespace); foreach (var storageEntityContainerMapping in mappingCollection.GetItems<StorageEntityContainerMapping>()) { //Throw warning when containerMapping contains query view for bug 547285. if (HasQueryView(storageEntityContainerMapping)) { schemaErrors.Add(new EdmSchemaError( Strings.UnsupportedQueryViewInEntityContainerMapping(storageEntityContainerMapping.Identity), (int)StorageMappingErrorCode.UnsupportedQueryViewInEntityContainerMapping, EdmSchemaErrorSeverity.Warning)); continue; } #region Class Declaration string edmContainerName = storageEntityContainerMapping.EdmEntityContainer.Name; string storeContainerName = storageEntityContainerMapping.StorageEntityContainer.Name; string hashOverMappingClosure = MetadataMappingHasherVisitor.GetMappingClosureHash(edmCollection.EdmVersion, storageEntityContainerMapping); StringBuilder inputForTypeNameContent = new StringBuilder(hashOverMappingClosure); string viewStorageTypeName = EntityViewGenerationConstants.ViewGenerationTypeNamePrefix + StringHashBuilder.ComputeHash(MetadataHelper.CreateMetadataHashAlgorithm(edmCollection.EdmVersion), inputForTypeNameContent.ToString()).ToUpperInvariant(); //Add typeof expression to get the type that contains ViewGen type. This will help us in avoiding to go through //all the types in the assembly. I have also verified that this works with VB with a root namespace prepended to the //namespace since VB is picking up the type correctly as long as it is in the same assembly even with out the root namespace. CodeTypeOfExpression viewGenTypeOfExpression = new CodeTypeOfExpression(EntityViewGenerationConstants.NamespaceName + "." + viewStorageTypeName); //Add the assembly attribute that marks the assembly as the one that contains the generated views CodeAttributeDeclaration viewGenAttribute = new CodeAttributeDeclaration(EntityViewGenerationConstants.ViewGenerationCustomAttributeName); CodeAttributeArgument viewGenTypeArgument = new CodeAttributeArgument(viewGenTypeOfExpression); viewGenAttribute.Arguments.Add(viewGenTypeArgument); compileUnit.AssemblyCustomAttributes.Add(viewGenAttribute); //Add the type which will be the class that contains all the views in this assembly CodeTypeDeclaration viewStoringType = CreateTypeForStoringViews(viewStorageTypeName); //Add the constructor, this will be the only method that this type will contain //Create empty constructor. CodeConstructor viewStoringTypeConstructor = CreateConstructorForViewStoringType(); viewStoringType.Attributes = MemberAttributes.Public; //Get an expression that expresses this instance CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression(); string viewHash = MetadataHelper.GenerateHashForAllExtentViewsContent(edmCollection.EdmVersion, GenerateDictionaryForEntitySetNameAndView(generatedViews)); CodeAssignStatement EdmEntityContainerNameStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.EdmEntityContainerName), new CodePrimitiveExpression(edmContainerName)); CodeAssignStatement StoreEntityContainerNameStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.StoreEntityContainerName), new CodePrimitiveExpression(storeContainerName)); CodeAssignStatement HashOverMappingClosureStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.HashOverMappingClosure), new CodePrimitiveExpression(hashOverMappingClosure)); CodeAssignStatement HashOverAllExtentViewsStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.HashOverAllExtentViews), new CodePrimitiveExpression(viewHash)); CodeAssignStatement ViewCountStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.ViewCountPropertyName), new CodePrimitiveExpression(generatedViews.Count)); viewStoringTypeConstructor.Statements.Add(EdmEntityContainerNameStatement); viewStoringTypeConstructor.Statements.Add(StoreEntityContainerNameStatement); viewStoringTypeConstructor.Statements.Add(HashOverMappingClosureStatement); viewStoringTypeConstructor.Statements.Add(HashOverAllExtentViewsStatement); viewStoringTypeConstructor.Statements.Add(ViewCountStatement); //Add the constructor to the type viewStoringType.Members.Add(viewStoringTypeConstructor); //Add the method to store views to the type CreateAndAddGetViewAtMethod(viewStoringType, generatedViews); //Add the type to the namespace codeNamespace.Types.Add(viewStoringType); #endregion } if (codeNamespace.Types.Count > 0) { GenerateCode(sourceWriter, provider, compileUnit); sourceWriter.Flush(); } }
public void Visit (CodeTypeOfExpression o) { g.GenerateTypeOfExpression (o); }
public override object Serialize(IDesignerSerializationManager manager, object obj) { if (manager == null) throw new ArgumentNullException("manager"); if (manager.Context == null) throw new ArgumentException("manager", SR.GetString(SR.Error_MissingContextProperty)); if (obj == null) throw new ArgumentNullException("obj"); DependencyObject dependencyObject = obj as DependencyObject; if (dependencyObject == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "obj"); Activity activity = obj as Activity; if (activity != null) manager.Context.Push(activity); CodeStatementCollection retVal = null; try { if (activity != null) { CodeDomSerializer componentSerializer = manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)) as CodeDomSerializer; if (componentSerializer == null) throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(CodeDomSerializer).FullName)); retVal = componentSerializer.Serialize(manager, activity) as CodeStatementCollection; } else { retVal = base.Serialize(manager, obj) as CodeStatementCollection; } if (retVal != null) { CodeStatementCollection codeStatements = new CodeStatementCollection(retVal); CodeExpression objectExpression = SerializeToExpression(manager, obj); if (objectExpression != null) { ArrayList propertiesSerialized = new ArrayList(); List<DependencyProperty> dependencyProperties = new List<DependencyProperty>(dependencyObject.MetaDependencyProperties); foreach (DependencyProperty dp in dependencyObject.DependencyPropertyValues.Keys) { if (dp.IsAttached) { if ((dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) || (!dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null)) dependencyProperties.Add(dp); } } foreach (DependencyProperty dependencyProperty in dependencyProperties) { object value = null; if (dependencyObject.IsBindingSet(dependencyProperty)) value = dependencyObject.GetBinding(dependencyProperty); else if (!dependencyProperty.IsEvent) value = dependencyObject.GetValue(dependencyProperty); else value = dependencyObject.GetHandler(dependencyProperty); // Attached property should always be set through SetValue, no matter if it's a meta property or if there is a data context. // Other meta properties will be directly assigned. // Other instance property will go through SetValue if there is a data context or if it's of type Bind. if (value != null && (dependencyProperty.IsAttached || (!dependencyProperty.DefaultMetadata.IsMetaProperty && value is ActivityBind))) { object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute)); if (attributes.Length > 0) { DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute; if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden) continue; } // Events of type Bind will go through here. Regular events will go through IEventBindingService. CodeExpression param1 = null; string dependencyPropertyName = dependencyProperty.Name + ((dependencyProperty.IsEvent) ? "Event" : "Property"); FieldInfo fieldInfo = dependencyProperty.OwnerType.GetField(dependencyPropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (fieldInfo != null && !fieldInfo.IsPublic) param1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(DependencyProperty)), "FromName", new CodePrimitiveExpression(dependencyProperty.Name), new CodeTypeOfExpression(dependencyProperty.OwnerType)); else param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dependencyProperty.OwnerType), dependencyPropertyName); CodeExpression param2 = SerializeToExpression(manager, value); //Fields property fails to serialize to expression due to reference not being created, //the actual code for fields are generated in datacontext code generator so we do nothing here if (param1 != null && param2 != null) { CodeMethodInvokeExpression codeMethodInvokeExpr = null; if (value is ActivityBind) codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, "SetBinding", new CodeExpression[] { param1, new CodeCastExpression(new CodeTypeReference(typeof(ActivityBind)), param2) }); else codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, (dependencyProperty.IsEvent) ? "AddHandler" : "SetValue", new CodeExpression[] { param1, param2 }); retVal.Add(codeMethodInvokeExpr); // Remove the property set statement for the event which is replaced by the SetValue() expression. foreach (CodeStatement statement in codeStatements) { if (statement is CodeAssignStatement && ((CodeAssignStatement)statement).Left is CodePropertyReferenceExpression) { CodePropertyReferenceExpression prop = ((CodeAssignStatement)statement).Left as CodePropertyReferenceExpression; if (prop.PropertyName == dependencyProperty.Name && prop.TargetObject.Equals(objectExpression)) retVal.Remove(statement); } } } propertiesSerialized.Add(dependencyProperty); } } IEventBindingService eventBindingService = manager.GetService(typeof(IEventBindingService)) as IEventBindingService; if (eventBindingService == null) { // At compile time, we don't have an event binding service. We need to mannually emit the code to add // event handlers. foreach (EventDescriptor eventDesc in TypeDescriptor.GetEvents(dependencyObject)) { string handler = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, eventDesc.Name); if (!string.IsNullOrEmpty(handler)) { CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(objectExpression, eventDesc.Name); CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(new CodeTypeReference(eventDesc.EventType), new CodeThisReferenceExpression(), handler); retVal.Add(new CodeAttachEventStatement(eventRef, listener)); } } } // We also need to handle properties of type System.Type. If the value is a design time type, xomlserializer // is not going to be able to deserialize the type. We then store the type name in the user data and // output a "typeof(xxx)" expression using the type name w/o validating the type. if (dependencyObject.UserData.Contains(UserDataKeys.DesignTimeTypeNames)) { Hashtable typeNames = dependencyObject.UserData[UserDataKeys.DesignTimeTypeNames] as Hashtable; foreach (object key in typeNames.Keys) { string propName = null; string ownerTypeName = null; string typeName = typeNames[key] as string; DependencyProperty dependencyProperty = key as DependencyProperty; if (dependencyProperty != null) { if (propertiesSerialized.Contains(dependencyProperty)) continue; object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute)); if (attributes.Length > 0) { DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute; if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden) continue; } propName = dependencyProperty.Name; ownerTypeName = dependencyProperty.OwnerType.FullName; } else if (key is string) { int indexOfDot = ((string)key).LastIndexOf('.'); Debug.Assert(indexOfDot != -1, "Wrong property name in DesignTimeTypeNames hashtable."); if (indexOfDot != -1) { ownerTypeName = ((string)key).Substring(0, indexOfDot); propName = ((string)key).Substring(indexOfDot + 1); } } if (!string.IsNullOrEmpty(typeName) && !string.IsNullOrEmpty(propName) && !string.IsNullOrEmpty(ownerTypeName)) { if (ownerTypeName == obj.GetType().FullName) { // Property is not an attached property. Serialize using regular property set expression. CodePropertyReferenceExpression propertyRef = new CodePropertyReferenceExpression(objectExpression, propName); retVal.Add(new CodeAssignStatement(propertyRef, new CodeTypeOfExpression(typeName))); } else { // This is an attached property. Serialize using SetValue() expression. CodeExpression param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(ownerTypeName), propName + "Property"); CodeExpression param2 = new CodeTypeOfExpression(typeName); retVal.Add(new CodeMethodInvokeExpression(objectExpression, "SetValue", new CodeExpression[] { param1, param2 })); } } } } } } } finally { if (activity != null) { object pushedActivity = manager.Context.Pop(); System.Diagnostics.Debug.Assert(pushedActivity == activity); } } return retVal; }
protected override void GenerateTypeOfExpression (CodeTypeOfExpression e) { TextWriter output = Output; output.Write ("GetType("); OutputType (e.Type); output.Write (")"); }
protected virtual void GenerateTypeOfExpression (CodeTypeOfExpression e) { output.Write ("typeof("); OutputType (e.Type); output.Write (")"); }
public static string GetCollectionImplementationName(string typeName, GeneratorConfiguration configuration) { var typeRef = new CodeTypeReference(configuration.CollectionImplementationType ?? configuration.CollectionType); if (configuration.CollectionType.IsGenericTypeDefinition) typeRef.TypeArguments.Add(typeName); var typeOfExpr = new CodeTypeOfExpression(typeRef); var writer = new System.IO.StringWriter(); CSharpProvider.GenerateCodeFromExpression(typeOfExpr, writer, new CodeGeneratorOptions()); var fullTypeName = writer.ToString(); Debug.Assert(fullTypeName.StartsWith("typeof(") && fullTypeName.EndsWith(")")); fullTypeName = fullTypeName.Substring(7, fullTypeName.Length - 8); return fullTypeName; }
protected override void GenerateTypeOfExpression(CodeTypeOfExpression e) { base.Output.Write("GetType("); base.Output.Write(this.GetTypeOutput(e.Type)); base.Output.Write(")"); }
public static CodeMemberMethod GenerateFactoryMethod(IClassMap classMap, IList propertyMaps) { CodeMemberMethod methodMember = new CodeMemberMethod() ; methodMember.Name = GetFactoryMethodName(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); } CodeVariableDeclarationStatement contextVarDecl = new CodeVariableDeclarationStatement("IContext", "context", null) ; CodeVariableReferenceExpression contextVar = new CodeVariableReferenceExpression("context"); methodMember.Statements.Add(contextVarDecl); CodeTypeOfExpression typeOfExp = new CodeTypeOfExpression(typeReference) ; CodeMethodInvokeExpression newObjectInit = new CodeMethodInvokeExpression(contextVar, "CreateObject", new CodeExpression[] { 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); foreach(IPropertyMap propertyMap in propertyMaps) { 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); return methodMember; }
/// <summary> /// Creates a new body in stlye of an Ado.net Constructor and attaches it to the <paramref name="target"/> /// </summary> /// <param name="properties"></param> /// <param name="settings"></param> /// <param name="importNameSpace"></param> /// <param name="container"></param> /// <param name="target"></param> public static void GenerateBody(Dictionary<string, DbPropertyInfoCache> properties, FactoryHelperSettings settings, CodeNamespace importNameSpace, CodeMemberMethod container, CodeExpression target) { foreach (var propertyInfoCache in properties.Values) { propertyInfoCache.Refresh(); var columnName = propertyInfoCache.DbName; if (settings.EnforcePublicPropertys) { if (propertyInfoCache.Getter.MethodInfo.IsPrivate) throw new AccessViolationException(string.Format( "The Getter of {0} is private. Full creation cannot be enforced", propertyInfoCache.PropertyName)); if (propertyInfoCache.Setter.MethodInfo.IsPrivate) throw new AccessViolationException(string.Format( "The Setter of {0} is private. Full creation cannot be enforced", propertyInfoCache.PropertyName)); } var codeIndexerExpression = new CodeIndexerExpression(new CodeVariableReferenceExpression("record"), new CodePrimitiveExpression(columnName)); var variableName = columnName.ToLower(); CodeVariableDeclarationStatement bufferVariable = null; //var propertyRef = new CodeVariableReferenceExpression(propertyInfoCache.PropertyName); var refToProperty = new CodeFieldReferenceExpression(target, propertyInfoCache.PropertyName); var attributes = propertyInfoCache.Attributes; var valueConverterAttributeModel = attributes.FirstOrDefault(s => s.Attribute is ValueConverterAttribute); var isXmlProperty = attributes.FirstOrDefault(s => s.Attribute is FromXmlAttribute); CodeVariableReferenceExpression uncastLocalVariableRef = null; if (isXmlProperty != null) { bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName); container.Statements.Add(bufferVariable); uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName); var buffAssignment = new CodeAssignStatement(uncastLocalVariableRef, codeIndexerExpression); container.Statements.Add(buffAssignment); var checkXmlForNull = new CodeConditionStatement(); checkXmlForNull.Condition = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression(variableName), CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("System.DBNull"), "Value")); container.Statements.Add(checkXmlForNull); var xmlRecordType = new CodeTypeReferenceExpression(typeof(XmlDataRecord)); importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(DbClassInfoCache).Namespace)); importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(DataConverterExtensions).Namespace)); importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(DbConfigHelper).Namespace)); if (propertyInfoCache.CheckForListInterface()) { var typeArgument = propertyInfoCache.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault(); var codeTypeOfListArg = new CodeTypeOfExpression(typeArgument); var instanceHelper = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(NonObservableDbCollection<>).MakeGenericType(typeArgument)), "FromXml", new CodeCastExpression(typeof(string), new CodeVariableReferenceExpression(variableName))); //var tryParse = new CodeMethodInvokeExpression(xmlRecordType, // "TryParse", // new CodeCastExpression(typeof(string), uncastLocalVariableRef), // codeTypeOfListArg, // new CodePrimitiveExpression(false)); //var xmlDataRecords = new CodeMethodInvokeExpression(tryParse, "CreateListOfItems"); //var getClassInfo = new CodeMethodInvokeExpression(codeTypeOfListArg, "GetClassInfo"); //var xmlRecordsToObjects = new CodeMethodInvokeExpression(xmlDataRecords, "Select", // new CodeMethodReferenceExpression(getClassInfo, "SetPropertysViaReflection")); //CodeObjectCreateExpression collectionCreate; //if (typeArgument != null && (typeArgument.IsClass && typeArgument.GetInterface("INotifyPropertyChanged") != null)) //{ // collectionCreate = new CodeObjectCreateExpression(typeof(DbCollection<>).MakeGenericType(typeArgument), // xmlRecordsToObjects); //} //else //{ // collectionCreate = new CodeObjectCreateExpression(typeof(NonObservableDbCollection<>).MakeGenericType(typeArgument), // xmlRecordsToObjects); //} var setExpr = new CodeAssignStatement(refToProperty, instanceHelper); checkXmlForNull.TrueStatements.Add(setExpr); } else { var typeofProperty = new CodeTypeOfExpression(propertyInfoCache.PropertyType); var getClassInfo = new CodeMethodInvokeExpression(typeofProperty, "GetClassInfo"); var tryParse = new CodeMethodInvokeExpression(xmlRecordType, "TryParse", new CodeCastExpression(typeof(string), uncastLocalVariableRef), typeofProperty, new CodePrimitiveExpression(true)); var setProps = new CodeMethodInvokeExpression(getClassInfo, "SetPropertysViaReflection", tryParse, new CodeSnippetExpression("null"), new CodeSnippetExpression("null")); var setExpr = new CodeAssignStatement(refToProperty, new CodeCastExpression(propertyInfoCache.PropertyType, setProps)); checkXmlForNull.TrueStatements.Add(setExpr); } } else { //Should the SQL value be converted if (valueConverterAttributeModel != null) { //create object buff123; bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName); container.Statements.Add(bufferVariable); //Assing buff123 = record[x] uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName); var buffAssignment = new CodeAssignStatement(uncastLocalVariableRef, codeIndexerExpression); container.Statements.Add(buffAssignment); var converter = valueConverterAttributeModel.Attribute as ValueConverterAttribute; //Create the converter and then convert the value before everything else importNameSpace.Imports.Add(new CodeNamespaceImport(converter.Converter.Namespace)); var converterCall = new CodeObjectCreateExpression(converter.Converter); var converterInstanceCall = new CodeMethodInvokeExpression(converterCall, "Convert", new CodeVariableReferenceExpression(variableName), new CodeTypeOfExpression(propertyInfoCache.PropertyType), new CodePrimitiveExpression(converter.Parameter), new CodeVariableReferenceExpression("System.Globalization.CultureInfo.CurrentCulture")); var codeAssignment = new CodeAssignStatement(new CodeVariableReferenceExpression(variableName), converterInstanceCall); container.Statements.Add(codeAssignment); } else { if (propertyInfoCache.PropertyType.IsEnum) { bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName); container.Statements.Add(bufferVariable); uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName); var setToValue = new CodeAssignStatement(refToProperty, new CodeCastExpression( new CodeTypeReference(propertyInfoCache.PropertyType, CodeTypeReferenceOptions.GenericTypeParameter), uncastLocalVariableRef)); container.Statements.Add(setToValue); } } var isNullable = false; var baseType = Nullable.GetUnderlyingType(propertyInfoCache.PropertyType); if (baseType != null) isNullable = true; if (propertyInfoCache.PropertyType == typeof(string)) { baseType = typeof(string); } else if (propertyInfoCache.PropertyType.IsArray) { baseType = propertyInfoCache.PropertyType; } if (baseType != null) { if (bufferVariable == null) { bufferVariable = new CodeVariableDeclarationStatement(typeof(object), variableName); container.Statements.Add(bufferVariable); uncastLocalVariableRef = new CodeVariableReferenceExpression(variableName); var buffAssignment = new CodeAssignStatement(uncastLocalVariableRef, codeIndexerExpression); container.Statements.Add(buffAssignment); } var checkForDbNull = new CodeConditionStatement { Condition = new CodeBinaryOperatorExpression(uncastLocalVariableRef, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("System.DBNull"), "Value")) }; CodeAssignStatement setToNull; if (!isNullable && baseType != typeof(string)) { setToNull = new CodeAssignStatement(refToProperty, new CodeDefaultValueExpression( CreateShortCodeTypeReference(baseType, importNameSpace.Imports))); } else { setToNull = new CodeAssignStatement(refToProperty, new CodePrimitiveExpression(null)); } var setToValue = new CodeAssignStatement(refToProperty, new CodeCastExpression( new CodeTypeReference(baseType, CodeTypeReferenceOptions.GenericTypeParameter), uncastLocalVariableRef)); checkForDbNull.TrueStatements.Add(setToNull); checkForDbNull.FalseStatements.Add(setToValue); container.Statements.Add(checkForDbNull); } else { if (bufferVariable != null) { CodeExpression castExp = new CodeCastExpression( new CodeTypeReference(propertyInfoCache.PropertyType, CodeTypeReferenceOptions.GenericTypeParameter), new CodeVariableReferenceExpression(bufferVariable.Name)); var setExpr = new CodeAssignStatement(refToProperty, castExp); container.Statements.Add(setExpr); } else { CodeExpression castExp = new CodeCastExpression( new CodeTypeReference(propertyInfoCache.PropertyType, CodeTypeReferenceOptions.GenericTypeParameter), codeIndexerExpression); var setExpr = new CodeAssignStatement(refToProperty, castExp); container.Statements.Add(setExpr); } } } } }
public bool ValidateCodeTypeOfExpression (CodeTypeOfExpression exp) { return true; }
IEnumerable<IAttribute> ConvertAttributes (Attributes optAttributes, IMemberContext mc) { List<IAttribute> atts = new List<IAttribute> (); if (optAttributes == null || optAttributes.Attrs == null) return atts; ResolveContext ctx = new ResolveContext (mc); foreach (var section in optAttributes.Sections) { foreach (var attr in section) { DomAttribute domAttribute = new DomAttribute (); domAttribute.Name = ConvertQuoted (attr.Name); domAttribute.Region = ConvertRegion (attr.Location, attr.Location); domAttribute.AttributeType = ConvertReturnType (attr.TypeNameExpression); if (attr.PosArguments != null) { for (int i = 0; i < attr.PosArguments.Count; i++) { CodeExpression domExp; var exp = attr.PosArguments [i].Expr; if (exp is TypeOf) { TypeOf tof = (TypeOf)exp; IReturnType rt = ConvertReturnType (tof.TypeExpression); domExp = new CodeTypeOfExpression (rt.FullName); } else if (exp is Binary) { // Currently unsupported in the old dom (will be in the new dom) continue; } else if (exp is Constant) { try { var res = exp.Resolve (ctx); var val = res as Constant; if (val == null) continue; domExp = new CodePrimitiveExpression (val.GetValue ()); } catch { continue; } } else { try { domExp = ResolveMemberAccessExpression (exp); } catch { continue; } } if (domExp != null) domAttribute.AddPositionalArgument (domExp); } } if (attr.NamedArguments != null) { for (int i = 0; i < attr.NamedArguments.Count; i++) { var val = attr.NamedArguments [i].Expr as Constant; if (val == null) continue; domAttribute.AddNamedArgument (((NamedArgument)attr.NamedArguments [i]).Name, new CodePrimitiveExpression (val.GetValue ())); } } atts.Add (domAttribute); } } return atts; }
protected override void GenerateTypeOfExpression (CodeTypeOfExpression e) { Output.Write ("typeof("); OutputType (e.Type); Output.Write (")"); }