private static void GenerateSmartPartCode(IDesignerSerializationManager manager, object value, CodeStatementCollection statements) { IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); CodeTypeDeclaration declaration = (CodeTypeDeclaration)manager.GetService(typeof(CodeTypeDeclaration)); if (host.Container.Components[ProviderField] == null) { IComponent provider = host.CreateComponent(typeof(SmartPartInfoProvider), ProviderField); host.Container.Add(provider, ProviderField); } // Make sure this will break a test if we modify the ISmartPartInfoProvider interface. MethodInfo interfaceMethod = typeof(ISmartPartInfoProvider).GetMethod(GetSmartPartInfoMethod); Debug.Assert(interfaceMethod != null, "ISmartPartInfoProvider interface definition changed. GetSmartPartInfo method not found."); CodeMemberMethod getInfo = FindMember <CodeMemberMethod>(declaration, GetSmartPartInfoMethod); if (getInfo == null) { getInfo = GenerateGetSmartPartInfo(interfaceMethod); declaration.Members.Add(getInfo); } AddToProvider(manager, value, statements); }
internal ComponentCache(IDesignerSerializationManager manager) { this.serManager = manager; IComponentChangeService service = (IComponentChangeService) manager.GetService(typeof(IComponentChangeService)); if (service != null) { service.ComponentChanging += new ComponentChangingEventHandler(this.OnComponentChanging); service.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged); service.ComponentRemoving += new ComponentEventHandler(this.OnComponentRemove); service.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemove); service.ComponentRename += new ComponentRenameEventHandler(this.OnComponentRename); } DesignerOptionService service2 = manager.GetService(typeof(DesignerOptionService)) as DesignerOptionService; object obj2 = null; if (service2 != null) { PropertyDescriptor descriptor = service2.Options.Properties["UseOptimizedCodeGeneration"]; if (descriptor != null) { obj2 = descriptor.GetValue(null); } if ((obj2 != null) && (obj2 is bool)) { this.enabled = (bool) obj2; } } }
internal ComponentCache(IDesignerSerializationManager manager) { _serManager = manager; if (manager.GetService(typeof(IComponentChangeService)) is IComponentChangeService cs) { cs.ComponentChanging += new ComponentChangingEventHandler(OnComponentChanging); cs.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); cs.ComponentRemoving += new ComponentEventHandler(OnComponentRemove); cs.ComponentRemoved += new ComponentEventHandler(OnComponentRemove); cs.ComponentRename += new ComponentRenameEventHandler(OnComponentRename); } object optionValue = null; if (manager.GetService(typeof(DesignerOptionService)) is DesignerOptionService options) { PropertyDescriptor componentCacheProp = options.Options.Properties["UseOptimizedCodeGeneration"]; if (componentCacheProp != null) { optionValue = componentCacheProp.GetValue(null); } if (optionValue != null && optionValue is bool) { _enabled = (bool)optionValue; } } }
internal ComponentCache(IDesignerSerializationManager manager) { this.serManager = manager; IComponentChangeService service = (IComponentChangeService)manager.GetService(typeof(IComponentChangeService)); if (service != null) { service.ComponentChanging += new ComponentChangingEventHandler(this.OnComponentChanging); service.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged); service.ComponentRemoving += new ComponentEventHandler(this.OnComponentRemove); service.ComponentRemoved += new ComponentEventHandler(this.OnComponentRemove); service.ComponentRename += new ComponentRenameEventHandler(this.OnComponentRename); } DesignerOptionService service2 = manager.GetService(typeof(DesignerOptionService)) as DesignerOptionService; object obj2 = null; if (service2 != null) { PropertyDescriptor descriptor = service2.Options.Properties["UseOptimizedCodeGeneration"]; if (descriptor != null) { obj2 = descriptor.GetValue(null); } if ((obj2 != null) && (obj2 is bool)) { this.enabled = (bool)obj2; } } }
/// <include file='doc\ComponentCodeDomSerializer.uex' path='docs/doc[@for="ComponentCodeDomSerializer.SerializeSupportInitialize"]/*' /> /// <devdoc> /// This emits a method invoke to ISupportInitialize. /// </devdoc> private void SerializeSupportInitialize(IDesignerSerializationManager manager, CodeStatementCollection statements, object value, string methodName) { Debug.WriteLineIf(traceSerialization.TraceVerbose, "ComponentCodeDomSerializer::SerializeSupportInitialize"); Debug.Indent(); string name = manager.GetName(value); if (name == null) { IReferenceService referenceService = (IReferenceService)manager.GetService(typeof(IReferenceService)); if (referenceService != null) { name = referenceService.GetName(value); } } Debug.WriteLineIf(traceSerialization.TraceVerbose, name + "." + methodName); // Assemble a cast to ISupportInitialize, and then invoke the method. // CodeExpression targetExpr = null; IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); if (host != null && host.RootComponent == value) { targetExpr = new CodeThisReferenceExpression(); } else { targetExpr = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name); } CodeTypeReference type = new CodeTypeReference(typeof(ISupportInitialize)); CodeCastExpression castExp = new CodeCastExpression(type, targetExpr); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(castExp, methodName); CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(); methodInvoke.Method = method; CodeExpressionStatement statement = new CodeExpressionStatement(methodInvoke); if (methodName == "BeginInit") { statement.UserData["statement-ordering"] = "begin"; } else { statement.UserData["statement-ordering"] = "end"; } statements.Add(statement); Debug.Unindent(); }
public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { if (statements == null) { throw new ArgumentNullException("statements"); } if (manager == null) { throw new ArgumentNullException("manager"); } if (value == null) { throw new ArgumentNullException("value"); } if (descriptor == null) { throw new ArgumentNullException("descriptor"); } IEventBindingService service = manager.GetService(typeof(IEventBindingService)) as IEventBindingService; if (service != null) { // In the propertygrid the events are represented by PropertyDescriptors and the value is a string // which contains the method name to bind to. The propertydescriptors are managed and created by the // IEventBindingService // EventDescriptor ev = (EventDescriptor)descriptor; string methodName = (string)service.GetEventProperty(ev).GetValue(value); CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(new CodeTypeReference(ev.EventType), _thisReference, methodName); CodeExpression targetObject = base.SerializeToExpression(manager, value); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(targetObject, ev.Name); statements.Add(new CodeAttachEventStatement(eventRef, listener)); } }
public override void Serialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { if (statements == null) throw new ArgumentNullException ("statements"); if (manager == null) throw new ArgumentNullException ("manager"); if (value == null) throw new ArgumentNullException ("value"); if (descriptor == null) throw new ArgumentNullException ("descriptor"); IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService; if (service != null) { // In the propertygrid the events are represented by PropertyDescriptors and the value is a string // which contains the method name to bind to. The propertydescriptors are managed and created by the // IEventBindingService // EventDescriptor ev = (EventDescriptor) descriptor; string methodName = (string) service.GetEventProperty (ev).GetValue (value); CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression (new CodeTypeReference (ev.EventType), _thisReference, methodName); CodeExpression targetObject = base.SerializeToExpression (manager, value); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression (targetObject, ev.Name); statements.Add (new CodeAttachEventStatement (eventRef, listener)); } }
public override object Deserialize(IDesignerSerializationManager manager, object codeObject) { CodeTypeDeclaration declaration = (CodeTypeDeclaration)manager.GetService(typeof(CodeTypeDeclaration)); CodeStatementCollection statements = codeObject as CodeStatementCollection; if (statements != null) { // Before deserialization, remove statements we added. RemoveFromStatements <CodeMethodInvokeExpression>(statements, delegate(CodeMethodInvokeExpression invoke) { CodePropertyReferenceExpression propref = invoke.Method.TargetObject as CodePropertyReferenceExpression; if (propref != null) { CodeFieldReferenceExpression fieldref = propref.TargetObject as CodeFieldReferenceExpression; return(fieldref.FieldName == ProviderField && fieldref.TargetObject is CodeThisReferenceExpression); } return(false); }); CodeMemberField providerField = FindMember <CodeMemberField>(declaration, ProviderField); if (providerField != null) { declaration.Members.Remove(providerField); } } return(base.Deserialize(manager, codeObject)); }
public override object Serialize(IDesignerSerializationManager manager, object value) { object obj2 = this.GetBaseSerializer(manager).Serialize(manager, value); TableLayoutPanel component = value as TableLayoutPanel; if (component != null) { InheritanceAttribute attribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(component)[typeof(InheritanceAttribute)]; if ((attribute == null) || (attribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly)) { IDesignerHost service = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); if (this.IsLocalizable(service)) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(component)[LayoutSettingsPropName]; object obj3 = (descriptor != null) ? descriptor.GetValue(component) : null; if (obj3 != null) { string resourceName = manager.GetName(component) + "." + LayoutSettingsPropName; base.SerializeResourceInvariant(manager, resourceName, obj3); } } } } return(obj2); }
public override void Serialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { if (statements == null) throw new ArgumentNullException ("statements"); if (manager == null) throw new ArgumentNullException ("manager"); if (value == null) throw new ArgumentNullException ("value"); if (descriptor == null) throw new ArgumentNullException ("descriptor"); IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService; if (service != null) { EventDescriptor eventDescriptor = (EventDescriptor) descriptor; string methodName = (string) service.GetEventProperty (eventDescriptor).GetValue (value); if (methodName != null) { CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression (new CodeTypeReference (eventDescriptor.EventType), _thisReference, methodName); CodeExpression targetObject = base.SerializeToExpression (manager, value); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression (targetObject, eventDescriptor.Name); statements.Add (new CodeAttachEventStatement (eventRef, listener)); } } }
public override object Serialize(IDesignerSerializationManager manager, object value) { try { CodeDomSerializer serial = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)); if (serial == null) { return(null); } CodeStatementCollection statements = (CodeStatementCollection)serial.Serialize(manager, value); IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); if (host == value) { return(statements); } InsertCodeCommentHeader(statements); Calendar cdr = (Calendar)value; CodeExpression cnref = SerializeToExpression(manager, value); CodePropertyReferenceExpression propref = null; //CodeAssignStatement cassign = null; //cdr.CalendarStyle.CalendarHeader = new HeaderStyle(Font, foreColor, backColor, height); // CalendarStyle.CalendarHeader propref = new CodePropertyReferenceExpression(cnref, "CalendarStyle.CalendarHeader"); return(statements); } catch (Exception ex) { MessageBox.Show("Error during Serialize : " + ex.ToString()); return(null); } }
protected string GetUniqueName(IDesignerSerializationManager manager, object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } if (manager == null) { throw new ArgumentNullException("manager"); } string name = manager.GetName(instance); if (name == null) { INameCreationService service = manager.GetService(typeof(INameCreationService)) as INameCreationService; name = service.CreateName(null, instance.GetType()); if (name == null) { name = instance.GetType().Name.ToLower(); } manager.SetName(instance, name); } return(name); }
public object GetService(Type serviceType) { object service = null; if (serviceType == typeof(IReferenceService)) { service = new ActivityCodeDomReferenceService(this.serializationManager.GetService(serviceType) as IReferenceService); } if (serviceType == typeof(IServiceContainer)) { service = serializationManager.GetService(serviceType); if (service == null) { service = serviceContainer; } } // If we haven't provded the service, try the serialization manager we wrap if (service == null) { service = this.serializationManager.GetService(serviceType); } // Last ditch effort, see if our consumer had added the service if (service == null) { service = serviceContainer.GetService(serviceType); } return(service); }
private CodeDomSerializer GetSerializer(IDesignerSerializationManager manager) { var attribute = TypeDescriptor.GetAttributes(typeof(System.ComponentModel.Component))[typeof(RootDesignerSerializerAttribute)] as RootDesignerSerializerAttribute; if (attribute == null) { return(null); } IDesignerHost host = manager.GetService(typeof(IDesignerHost)) as IDesignerHost; if (host == null) { return(null); } Type type = host.GetType(attribute.SerializerTypeName); if (type == null) { return(null); } return(Activator.CreateInstance(type) as CodeDomSerializer); }
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 override bool ShouldSerialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService; if (service != null) // serialize only if there is an event to serialize return service.GetEventProperty ((EventDescriptor)descriptor).GetValue (value) != null; return false; }
/// <summary> /// We don't actually want to serialize any code here, so we just delegate that to the base type's /// serializer. All we want to do is if we are in a localizable form, we want to push a /// 'LayoutSettings' entry into the resx. /// </summary> public override object Serialize(IDesignerSerializationManager manager, object value) { // First call the base serializer to serialize the object. object codeObject = GetBaseSerializer(manager).Serialize(manager, value); // Now push our layout settings stuff into the resx if we are not inherited read only and // are in a localizable Form. TableLayoutPanel tlp = value as TableLayoutPanel; Debug.Assert(tlp != null, "Huh? We were expecting to be serializing a TableLayoutPanel here."); if (tlp != null) { InheritanceAttribute ia = (InheritanceAttribute)TypeDescriptor.GetAttributes(tlp)[typeof(InheritanceAttribute)]; if (ia is null || ia.InheritanceLevel != InheritanceLevel.InheritedReadOnly) { IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); if (IsLocalizable(host)) { PropertyDescriptor lsProp = TypeDescriptor.GetProperties(tlp)[LayoutSettingsPropName]; object val = (lsProp != null) ? lsProp.GetValue(tlp) : null; if (val != null) { string key = manager.GetName(tlp) + "." + LayoutSettingsPropName; SerializeResourceInvariant(manager, key, val); } } } } return(codeObject); }
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 WorkflowMarkupSerializationManager(IDesignerSerializationManager manager) { if (manager == null) { throw new ArgumentNullException("manager"); } this.serializationManager = manager; this.AddSerializationProvider(new WellKnownTypeSerializationProvider()); this.AddMappings(WorkflowMarkupSerializerMapping.WellKnownMappings); ITypeProvider service = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (service != null) { this.LocalAssembly = service.LocalAssembly; } this.designMode = manager.GetService(typeof(ITypeResolutionService)) != null; }
/// <summary> /// This method actually performs the serialization. When the member is serialized /// the necessary statements will be added to the statements collection. /// </summary> public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { if (manager is null) { throw new ArgumentNullException(nameof(manager)); } if (value is null) { throw new ArgumentNullException(nameof(value)); } if (!(descriptor is EventDescriptor eventToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } if (statements is null) { throw new ArgumentNullException(nameof(statements)); } try { // If the IEventBindingService is not available, we don't throw - we just don't do anything. if (manager.GetService(typeof(IEventBindingService)) is IEventBindingService eventBindings) { PropertyDescriptor prop = eventBindings.GetEventProperty(eventToSerialize); string methodName = (string)prop.GetValue(value); if (methodName != null) { CodeDomSerializer.Trace("Event {0} bound to {1}", eventToSerialize.Name, methodName); CodeExpression eventTarget = SerializeToExpression(manager, value); CodeDomSerializer.TraceWarningIf(eventTarget is null, "Object has no name and no propery ref in context so we cannot serialize events: {0}", value); if (eventTarget != null) { CodeTypeReference delegateTypeRef = new CodeTypeReference(eventToSerialize.EventType); CodeDelegateCreateExpression delegateCreate = new CodeDelegateCreateExpression(delegateTypeRef, _thisRef, methodName); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(eventTarget, eventToSerialize.Name); CodeAttachEventStatement attach = new CodeAttachEventStatement(eventRef, delegateCreate); attach.UserData[typeof(Delegate)] = eventToSerialize.EventType; statements.Add(attach); } } } } catch (Exception e) { // Since we usually go through reflection, don't // show what our engine does, show what caused // the problem. // if (e is TargetInvocationException) { e = e.InnerException; } manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, eventToSerialize.Name, e.Message), manager)); } }
protected CodeExpression GetExpression(IDesignerSerializationManager manager, object instance) { if (manager == null) { throw new ArgumentNullException("manager"); } if (instance == null) { throw new ArgumentNullException("instance"); } CodeExpression expression = null; ExpressionTable expressions = manager.Context[typeof(ExpressionTable)] as ExpressionTable; if (expressions != null) // 1st try: ExpressionTable { expression = expressions [instance] as CodeExpression; } if (expression == null) // 2nd try: RootContext { RootContext context = manager.Context[typeof(RootContext)] as RootContext; if (context != null && context.Value == instance) { expression = context.Expression; } } if (expression == null) // 3rd try: IReferenceService (instnace.property.property.property { string name = manager.GetName(instance); if (name == null || name.IndexOf(".") == -1) { IReferenceService service = manager.GetService(typeof(IReferenceService)) as IReferenceService; if (service != null) { name = service.GetName(instance); if (name != null && name.IndexOf(".") != -1) { string[] parts = name.Split(new char[] { ',' }); instance = manager.GetInstance(parts[0]); if (instance != null) { expression = SerializeToExpression(manager, instance); if (expression != null) { for (int i = 1; i < parts.Length; i++) { expression = new CodePropertyReferenceExpression(expression, parts[i]); } } } } } } } return(expression); }
/// <summary> /// This method returns true if the given member descriptor should be serialized, /// or false if there is no need to serialize the member. /// </summary> public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { ArgumentNullException.ThrowIfNull(manager); ArgumentNullException.ThrowIfNull(value); if (!(descriptor is PropertyDescriptor propertyToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } bool shouldSerializeProperty = propertyToSerialize.ShouldSerializeValue(value); if (!shouldSerializeProperty) { SerializeAbsoluteContext absolute = (SerializeAbsoluteContext)manager.Context[typeof(SerializeAbsoluteContext)]; if (absolute is not null && absolute.ShouldSerialize(propertyToSerialize)) { // For ReadOnly properties, we only want to override the value returned from // ShouldSerializeValue() if the property is marked with DesignerSerializationVisibilityAttribute(Content). // Consider the case of a property with just a getter - we only want to serialize those // if they're marked in this way (see ReflectPropertyDescriptor::ShouldSerializeValue()) if (!propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)) { shouldSerializeProperty = false; // it's already false at this point, but this is clearer. } else { shouldSerializeProperty = true; // Always serialize difference properties } } } if (shouldSerializeProperty) { bool isDesignTime = propertyToSerialize.Attributes.Contains(DesignOnlyAttribute.Yes); if (!isDesignTime) { return(true); } } // If we don't have to serialize, we need to make sure there isn't a member // relationship with this property. If there is, we still need to serialize. if (manager.GetService(typeof(MemberRelationshipService)) is MemberRelationshipService relationships) { MemberRelationship relationship = relationships[value, descriptor]; if (relationship != MemberRelationship.Empty) { return(true); } } return(false); }
public WorkflowMarkupSerializationManager(IDesignerSerializationManager manager) { if (manager == null) throw new ArgumentNullException("manager"); this.serializationManager = manager; AddSerializationProvider(new WellKnownTypeSerializationProvider()); // push standard mappings AddMappings(WorkflowMarkupSerializerMapping.WellKnownMappings); //Set the local assembly correctly ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider != null) LocalAssembly = typeProvider.LocalAssembly; this.designMode = (manager.GetService(typeof(ITypeResolutionService)) != null); }
public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { IEventBindingService service = manager.GetService(typeof(IEventBindingService)) as IEventBindingService; if (service != null) // serialize only if there is an event to serialize { return(service.GetEventProperty((EventDescriptor)descriptor).GetValue(value) != null); } return(false); }
public override object Serialize(IDesignerSerializationManager manager, object value) { if (manager == null || value == null) { throw new ArgumentNullException((manager == null) ? "manager" : "value"); } CodeDomSerializer codeDomSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)); if (codeDomSerializer == null) { return(null); } object obj = codeDomSerializer.Serialize(manager, value); InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; InheritanceLevel inheritanceLevel = InheritanceLevel.NotInherited; if (inheritanceAttribute != null) { inheritanceLevel = inheritanceAttribute.InheritanceLevel; } if (inheritanceLevel != InheritanceLevel.InheritedReadOnly) { IDesignerHost designerHost = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); if (designerHost != null) { PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(designerHost.RootComponent)["Localizable"]; if (propertyDescriptor != null && propertyDescriptor.PropertyType == typeof(bool) && (bool)propertyDescriptor.GetValue(designerHost.RootComponent)) { this.SerializeControlHierarchy(manager, designerHost, value); } } CodeStatementCollection codeStatementCollection = obj as CodeStatementCollection; if (codeStatementCollection != null) { Control control = (Control)value; if ((designerHost != null && control == designerHost.RootComponent) || this.HasSitedNonReadonlyChildren(control)) { this.SerializeSuspendLayout(manager, codeStatementCollection, value); this.SerializeResumeLayout(manager, codeStatementCollection, value); ControlDesigner controlDesigner = designerHost.GetDesigner(control) as ControlDesigner; var serializePerformLayoutProp = typeof(ControlDesigner).GetProperty("SerializePerformLayout", BindingFlags.NonPublic | BindingFlags.Instance); if (this.HasAutoSizedChildren(control) || (controlDesigner != null && (bool)serializePerformLayoutProp.GetValue(controlDesigner))) { this.SerializePerformLayout(manager, codeStatementCollection, value); } } if (this.HasMixedInheritedChildren(control)) { this.SerializeZOrder(manager, codeStatementCollection, control); } } } return(obj); }
private void SerializeNormalProperty(IDesignerSerializationManager manager, object value, PropertyDescriptor property, CodeStatementCollection statements) { using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::SerializeProperty")) { CodeExpression targetObject = base.SerializeToExpression(manager, value); if (targetObject != null) { CodeExpression expression = new CodePropertyReferenceExpression(targetObject, property.Name); CodeExpression right = null; MemberRelationshipService service = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; if (service != null) { MemberRelationship relationship = service[value, property]; if (relationship != MemberRelationship.Empty) { CodeExpression expression4 = base.SerializeToExpression(manager, relationship.Owner); if (expression4 != null) { right = new CodePropertyReferenceExpression(expression4, relationship.Member.Name); } } } if (right == null) { bool flag; object obj2 = this.GetPropertyValue(manager, property, value, out flag); if (flag) { ExpressionContext context = null; if (obj2 != value) { context = new ExpressionContext(expression, property.PropertyType, value); manager.Context.Push(context); } try { right = base.SerializeToExpression(manager, obj2); } finally { if (context != null) { manager.Context.Pop(); } } } } if (right != null) { CodeAssignStatement statement = new CodeAssignStatement(expression, right); statements.Add(statement); } } } }
public WorkflowMarkupSerializationManager(IDesignerSerializationManager manager) { this.serializationManager = manager ?? throw new ArgumentNullException("manager"); AddSerializationProvider(new WellKnownTypeSerializationProvider()); // push standard mappings AddMappings(WorkflowMarkupSerializerMapping.WellKnownMappings); this.designMode = (manager.GetService(typeof(ITypeResolutionService)) != null); }
static ProjectResourceInfo GetProjectResourceFromPropertyReference(IDesignerSerializationManager manager, CodePropertyReferenceExpression propRefSource) { ProjectResourceService prs = manager.GetService(typeof(ProjectResourceService)) as ProjectResourceService; if (prs == null) { throw new InvalidOperationException("The required ProjectResourceService is not available."); } return(prs.GetProjectResource(propRefSource)); }
public override object Serialize(IDesignerSerializationManager manager, object value) { if ((manager == null) || (value == null)) { throw new ArgumentNullException((manager == null) ? "manager" : "value"); } CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)); if (serializer == null) { return(null); } object obj2 = serializer.Serialize(manager, value); InheritanceAttribute attribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; InheritanceLevel notInherited = InheritanceLevel.NotInherited; if (attribute != null) { notInherited = attribute.InheritanceLevel; } if (notInherited != InheritanceLevel.InheritedReadOnly) { IDesignerHost service = (IDesignerHost)manager.GetService(typeof(IDesignerHost)); if (service != null) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(service.RootComponent)["Localizable"]; if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool)descriptor.GetValue(service.RootComponent))) { this.SerializeControlHierarchy(manager, service, value); } } CodeStatementCollection statements = obj2 as CodeStatementCollection; if (statements == null) { return(obj2); } Control parent = (Control)value; if (((service != null) && (parent == service.RootComponent)) || this.HasSitedNonReadonlyChildren(parent)) { this.SerializeSuspendLayout(manager, statements, value); this.SerializeResumeLayout(manager, statements, value); ControlDesigner designer = service.GetDesigner(parent) as ControlDesigner; if (this.HasAutoSizedChildren(parent) || ((designer != null) && designer.SerializePerformLayout)) { this.SerializePerformLayout(manager, statements, value); } } if (this.HasMixedInheritedChildren(parent)) { this.SerializeZOrder(manager, statements, parent); } } return(obj2); }
/// <summary> /// Deserializes a PaletteGroupView object from the code DOM. /// </summary> /// <param name="manager"></param> /// <param name="codeObject"></param> /// <returns></returns> public override object Deserialize(IDesignerSerializationManager manager, object codeObject) { object retVal = null; // Get base class serializer CodeDomSerializer baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(GroupView), typeof(CodeDomSerializer)); if (baseSerializer != null) { // Deserialize palette group view using base class serializer retVal = baseSerializer.Deserialize(manager, codeObject); if (retVal != null) { // Downcast to PaletteGroupView PaletteGroupView palGrpVw = retVal as PaletteGroupView; if (palGrpVw != null) { // Load symbol palette from the resource file and attach // to the palette group view string resName = palGrpVw.Name + "." + "Palette"; System.ComponentModel.Design.IResourceService resSvc = manager.GetService(typeof(System.ComponentModel.Design.IResourceService)) as System.ComponentModel.Design.IResourceService; if (resSvc != null) { System.Resources.IResourceReader resReader = resSvc.GetResourceReader(System.Globalization.CultureInfo.InvariantCulture); if (resReader != null) { // Iterate through the resource file using the resource // reader and find the byte stream for the palette byte[] strmData = null; bool resFound = false; IDictionaryEnumerator resEnum = resReader.GetEnumerator(); while (resEnum.MoveNext() && !resFound) { if ((string)resEnum.Key == resName) { strmData = (byte[])resEnum.Value; resFound = true; } } if (resFound && strmData != null) { palGrpVw.LoadPalette(strmData); } } } } } } return(retVal); }
/// <summary> /// Serializes a PaletteGroupView object to the code DOM. /// </summary> /// <param name="manager"></param> /// <param name="value"></param> /// <returns></returns> public override object Serialize(IDesignerSerializationManager manager, object value) { object retVal = value; CodeDomSerializer baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(GroupView), typeof(CodeDomSerializer)); if (baseSerializer != null) { retVal = baseSerializer.Serialize(manager, value); if (retVal != null) { System.CodeDom.CodeStatementCollection stmts = retVal as System.CodeDom.CodeStatementCollection; if (stmts != null) { PaletteGroupView palGrpVw = value as PaletteGroupView; if (palGrpVw != null) { SymbolPalette pal = palGrpVw.Palette; if (pal != null) { // Serialize the palette into the resource file BinaryFormatter formatter = new BinaryFormatter(); System.IO.MemoryStream oStream = new System.IO.MemoryStream(); formatter.Serialize(oStream, pal); string resName = palGrpVw.Name + "." + "Palette"; this.SerializeResource(manager, resName, oStream.GetBuffer()); oStream.Close(); // Add statements to CodeDom to load the palette from // the resource file at run-time string formClassName = ""; IDesignerHost designerHost = manager.GetService(typeof(IDesignerHost)) as IDesignerHost; if (designerHost != null) { formClassName = designerHost.RootComponentClassName; CodePropertyReferenceExpression exprRefGroupView = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), palGrpVw.Name); CodeExpression[] loadPalParams = new CodeExpression[] { new CodePropertyReferenceExpression(new CodeTypeOfExpression(formClassName), "Assembly"), new CodePrimitiveExpression(formClassName), new CodePrimitiveExpression(resName) }; CodeMethodInvokeExpression stmtLoadPalette = new CodeMethodInvokeExpression(exprRefGroupView, "LoadPalette", loadPalParams); stmts.Add(stmtLoadPalette); } } } } } } return(retVal); }
protected CodeDomSerializer GetConfiguredSerializer(IDesignerSerializationManager manager, object value) { object[] attrs = value.GetType().GetCustomAttributes(typeof(DesignerSerializerAttribute), true); if (attrs.Length == 0) { return(null); } DesignerSerializerAttribute serializer = (DesignerSerializerAttribute)attrs[0]; return((CodeDomSerializer) Activator.CreateInstance(((ITypeResolutionService)manager.GetService(typeof(ITypeResolutionService))).GetType(serializer.SerializerTypeName))); }
private static TypeDescriptionProvider GetTargetFrameworkProviderForType(Type type) { IDesignerSerializationManager manager = DocumentDesigner.manager; if (manager != null) { if (manager.GetService(typeof(TypeDescriptionProviderService)) is TypeDescriptionProviderService service) { return(service.GetProvider(type)); } } return(null); }
protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) { if (typeof(IContainer).IsAssignableFrom(type)) { object service = manager.GetService(typeof(IContainer)); if (service != null) { manager.SetName(service, name); return(service); } } return(base.DeserializeInstance(manager, type, parameters, name, addToContainer)); }
protected override object DeserializeInstance(IDesignerSerializationManager manager, Type type, object[] parameters, string name, bool addToContainer) { if (typeof(IContainer).IsAssignableFrom(type)) { object service = manager.GetService(typeof(IContainer)); if (service != null) { manager.SetName(service, name); return service; } } return base.DeserializeInstance(manager, type, parameters, name, addToContainer); }
private MemberRelationship GetRelationship(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { MemberRelationshipService service = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; if (service != null) { return(service[value, descriptor]); } else { return(MemberRelationship.Empty); } }
public WorkflowMarkupSerializationManager(IDesignerSerializationManager manager) { if (manager == null) { throw new ArgumentNullException("manager"); } this.serializationManager = manager; AddSerializationProvider(new WellKnownTypeSerializationProvider()); // push standard mappings AddMappings(WorkflowMarkupSerializerMapping.WellKnownMappings); //Set the local assembly correctly ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider != null) { LocalAssembly = typeProvider.LocalAssembly; } this.designMode = (manager.GetService(typeof(ITypeResolutionService)) != null); }
public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { EventDescriptor e = descriptor as EventDescriptor; if (manager == null) { throw new ArgumentNullException("manager"); } if (value == null) { throw new ArgumentNullException("value"); } if (e == null) { throw new ArgumentNullException("descriptor"); } if (statements == null) { throw new ArgumentNullException("statements"); } try { IEventBindingService service = (IEventBindingService) manager.GetService(typeof(IEventBindingService)); if (service != null) { string methodName = (string) service.GetEventProperty(e).GetValue(value); if (methodName != null) { CodeExpression targetObject = base.SerializeToExpression(manager, value); if (targetObject != null) { CodeTypeReference delegateType = new CodeTypeReference(e.EventType); CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(delegateType, _thisRef, methodName); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(targetObject, e.Name); CodeAttachEventStatement statement = new CodeAttachEventStatement(eventRef, listener); statement.UserData[typeof(Delegate)] = e.EventType; statements.Add(statement); } } } } catch (Exception innerException) { if (innerException is TargetInvocationException) { innerException = innerException.InnerException; } manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { e.Name, innerException.Message })); } }
public override object Serialize(IDesignerSerializationManager manager, object value) { CodeExpression expression = new CodePrimitiveExpression(value); if (value == null || value is bool || value is char || value is int || value is float || value is double) { // work aroundf for J#, since they don't support auto-boxing of value types yet. CodeDomProvider codeProvider = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider; if (codeProvider != null && String.Equals(codeProvider.FileExtension, JSharpFileExtension)) { // See if we are boxing - if so, insert a cast. ExpressionContext cxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext; //Debug.Assert(cxt != null, "No expression context on stack - J# boxing cast will not be inserted"); if (cxt != null) { if (cxt.ExpressionType == typeof(object)) { expression = new CodeCastExpression(value.GetType(), expression); expression.UserData.Add("CastIsBoxing", true); } } } return expression; } String stringValue = value as string; if (stringValue != null) { // WinWS: The commented code breaks us when we have long strings //if (stringValue.Length > 200) //{ // return SerializeToResourceExpression(manager, stringValue); //} //else return expression; } // generate a cast for non-int types because we won't parse them properly otherwise because we won't know to convert // them to the narrow form. // return new CodeCastExpression(new CodeTypeReference(value.GetType()), expression); }
public override object Deserialize(IDesignerSerializationManager manager, object codeObject) { if ((manager == null) || (codeObject == null)) { throw new ArgumentNullException((manager == null) ? "manager" : "codeObject"); } IContainer service = (IContainer) manager.GetService(typeof(IContainer)); ArrayList list = null; if (service != null) { list = new ArrayList(service.Components.Count); foreach (IComponent component in service.Components) { Control control = component as Control; if (control != null) { control.SuspendLayout(); list.Add(control); } } } object obj2 = null; try { CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)); if (serializer == null) { return null; } obj2 = serializer.Deserialize(manager, codeObject); } finally { if (list != null) { foreach (Control control2 in list) { control2.ResumeLayout(false); } } } return obj2; }
public override object Serialize(IDesignerSerializationManager manager, object value) { CodeExpression expression = new CodePrimitiveExpression(value); if ((((value == null) || (value is bool)) || ((value is char) || (value is int))) || ((value is float) || (value is double))) { CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider; if ((service != null) && string.Equals(service.FileExtension, JSharpFileExtension)) { ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext; if ((context != null) && (context.ExpressionType == typeof(object))) { expression = new CodeCastExpression(value.GetType(), expression); expression.UserData.Add("CastIsBoxing", true); } } return expression; } if (value is string) { return expression; } return new CodeCastExpression(new CodeTypeReference(value.GetType()), expression); }
public override object Serialize(IDesignerSerializationManager manager, object value) { object obj2 = this.GetBaseSerializer(manager).Serialize(manager, value); TableLayoutPanel component = value as TableLayoutPanel; if (component != null) { InheritanceAttribute attribute = (InheritanceAttribute) TypeDescriptor.GetAttributes(component)[typeof(InheritanceAttribute)]; if ((attribute == null) || (attribute.InheritanceLevel != InheritanceLevel.InheritedReadOnly)) { IDesignerHost service = (IDesignerHost) manager.GetService(typeof(IDesignerHost)); if (this.IsLocalizable(service)) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(component)[LayoutSettingsPropName]; object obj3 = (descriptor != null) ? descriptor.GetValue(component) : null; if (obj3 != null) { string resourceName = manager.GetName(component) + "." + LayoutSettingsPropName; base.SerializeResourceInvariant(manager, resourceName, obj3); } } } } return obj2; }
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; }
private MemberRelationship GetRelationship (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { MemberRelationshipService service = manager.GetService (typeof (MemberRelationshipService)) as MemberRelationshipService; if (service != null) return service[value, descriptor]; else return MemberRelationship.Empty; }
protected void DeserializeStatement (IDesignerSerializationManager manager, CodeStatement statement) { if (statement == null) throw new ArgumentNullException ("statement"); if (manager == null) throw new ArgumentNullException ("manager"); // CodeAssignStatement // CodeAssignStatement assignment = statement as CodeAssignStatement; if (assignment != null) DeserializeAssignmentStatement (manager, assignment); // CodeExpressionStatement // CodeExpressionStatement expression = statement as CodeExpressionStatement; if (expression != null) this.DeserializeExpression (manager, null, expression.Expression); // CodeAttachEventStatement // CodeAttachEventStatement attachStatement = statement as CodeAttachEventStatement; if (attachStatement != null) { string methodName = null; CodeObjectCreateExpression createExpr = attachStatement.Listener as CodeObjectCreateExpression; if (createExpr != null && createExpr.Parameters.Count == 1 ) { // += new EventType (method) CodeMethodReferenceExpression handlerRef = createExpr.Parameters[0] as CodeMethodReferenceExpression; if (handlerRef != null) methodName = handlerRef.MethodName; } CodeDelegateCreateExpression delegateCreateExpr = attachStatement.Listener as CodeDelegateCreateExpression; if (delegateCreateExpr != null)// += new EventType (method) methodName = delegateCreateExpr.MethodName; CodeMethodReferenceExpression methodRef = attachStatement.Listener as CodeMethodReferenceExpression; if (methodRef != null) // += method methodName = methodRef.MethodName; object component = DeserializeExpression (manager, null, attachStatement.Event.TargetObject); if (component != null && component != _errorMarker && methodName != null) { string error = null; EventDescriptor eventDescriptor = TypeDescriptor.GetEvents (component)[attachStatement.Event.EventName]; if (eventDescriptor != null) { IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService; if (service != null) service.GetEventProperty (eventDescriptor).SetValue (component, methodName); else error = "IEventBindingService missing"; } else { error = "No event '" + attachStatement.Event.EventName + "' found in type '" + component.GetType ().Name + "'"; } if (error != null) { ReportError (manager, error, "Method Name: " + methodName + System.Environment.NewLine + "Event Name: " + attachStatement.Event.EventName + System.Environment.NewLine + "Listener Expression Type: " + methodRef.GetType ().Name + System.Environment.NewLine + "Event Holder Type: " + component.GetType ().Name + System.Environment.NewLine + "Event Holder Expression Type: " + attachStatement.Event.TargetObject.GetType ().Name); } } } }
protected object DeserializeExpression (IDesignerSerializationManager manager, string name, CodeExpression expression) { if (expression == null) throw new ArgumentNullException ("expression"); if (manager == null) throw new ArgumentNullException ("manager"); bool errorOccurred = false; object deserialized = null; // CodeThisReferenceExpression // CodeThisReferenceExpression thisExpr = expression as CodeThisReferenceExpression; if (thisExpr != null) { RootContext context = manager.Context[typeof (RootContext)] as RootContext; if (context != null) { deserialized = context.Value; } else { IDesignerHost host = manager.GetService (typeof (IDesignerHost)) as IDesignerHost; if (host != null) deserialized = host.RootComponent; } } // CodeVariableReferenceExpression // CodeVariableReferenceExpression varRef = expression as CodeVariableReferenceExpression; if (deserialized == null && varRef != null) { deserialized = manager.GetInstance (varRef.VariableName); if (deserialized == null) { ReportError (manager, "Variable '" + varRef.VariableName + "' not initialized prior to reference"); errorOccurred = true; } } // CodeFieldReferenceExpression (used for Enum references as well) // CodeFieldReferenceExpression fieldRef = expression as CodeFieldReferenceExpression; if (deserialized == null && fieldRef != null) { deserialized = manager.GetInstance (fieldRef.FieldName); if (deserialized == null) { object fieldHolder = DeserializeExpression (manager, null, fieldRef.TargetObject); FieldInfo field = null; if (fieldHolder is Type) // static field field = ((Type)fieldHolder).GetField (fieldRef.FieldName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static); else // instance field field = fieldHolder.GetType().GetField (fieldRef.FieldName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance); if (field != null) deserialized = field.GetValue (fieldHolder); } if (deserialized == null) ReportError (manager, "Field '" + fieldRef.FieldName + "' not initialized prior to reference"); } // CodePrimitiveExpression // CodePrimitiveExpression primitiveExp = expression as CodePrimitiveExpression; if (deserialized == null && primitiveExp != null) deserialized = primitiveExp.Value; // CodePropertyReferenceExpression // CodePropertyReferenceExpression propRef = expression as CodePropertyReferenceExpression; if (deserialized == null && propRef != null) { object target = DeserializeExpression (manager, null, propRef.TargetObject); if (target != null && target != _errorMarker) { bool found = false; if (target is Type) { PropertyInfo property = ((Type)target).GetProperty (propRef.PropertyName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Static); if (property != null) { deserialized = property.GetValue (null, null); found = true; } // NRefactory seems to produce PropertyReferences to reference some fields and enums // FieldInfo field = ((Type)target).GetField (propRef.PropertyName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static); if (field != null) { deserialized = field.GetValue (null); found = true; } } else { PropertyDescriptor property = TypeDescriptor.GetProperties (target)[propRef.PropertyName]; if (property != null) { deserialized = property.GetValue (target); found = true; } FieldInfo field = target.GetType().GetField (propRef.PropertyName, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance); if (field != null) { deserialized = field.GetValue (null); found = true; } } if (!found) { ReportError (manager, "Missing field '" + propRef.PropertyName + " 'in type " + (target is Type ? ((Type)target).Name : target.GetType ().Name) + "'"); errorOccurred = true; } } } // CodeObjectCreateExpression // CodeObjectCreateExpression createExpr = expression as CodeObjectCreateExpression; if (deserialized == null && createExpr != null) { Type type = manager.GetType (createExpr.CreateType.BaseType); if (type == null) { ReportError (manager, "Type '" + createExpr.CreateType.BaseType + "' not found." + "Are you missing a reference?"); errorOccurred = true; } else { object[] arguments = new object[createExpr.Parameters.Count]; for (int i=0; i < createExpr.Parameters.Count; i++) { arguments[i] = this.DeserializeExpression (manager, null, createExpr.Parameters[i]); if (arguments[i] == _errorMarker) { errorOccurred = true; break; } } if (!errorOccurred) { bool addToContainer = false; if (typeof(IComponent).IsAssignableFrom (type)) addToContainer = true; deserialized = this.DeserializeInstance (manager, type, arguments, name, addToContainer); if (deserialized == _errorMarker || deserialized == null) { string info = "Type to create: " + createExpr.CreateType.BaseType + System.Environment.NewLine + "Name: " + name + System.Environment.NewLine + "addToContainer: " + addToContainer.ToString () + System.Environment.NewLine + "Parameters Count: " + createExpr.Parameters.Count + System.Environment.NewLine; for (int i=0; i < arguments.Length; i++) { info += "Parameter Number: " + i.ToString () + System.Environment.NewLine + "Parameter Type: " + (arguments[i] == null ? "null" : arguments[i].GetType ().Name) + System.Environment.NewLine + "Parameter '" + i.ToString () + "' Value: " + arguments[i].ToString () + System.Environment.NewLine; } ReportError (manager, "Unable to create an instance of type '" + createExpr.CreateType.BaseType + "'", info); errorOccurred = true; } } } } // CodeArrayCreateExpression // CodeArrayCreateExpression arrayCreateExpr = expression as CodeArrayCreateExpression; if (deserialized == null && arrayCreateExpr != null) { Type arrayType = manager.GetType (arrayCreateExpr.CreateType.BaseType); if (arrayType == null) { ReportError (manager, "Type '" + arrayCreateExpr.CreateType.BaseType + "' not found." + "Are you missing a reference?"); errorOccurred = true; } else { ArrayList initializers = new ArrayList (); Type elementType = arrayType.GetElementType (); deserialized = Array.CreateInstance (arrayType, arrayCreateExpr.Initializers.Count); for (int i = 0; i < arrayCreateExpr.Initializers.Count; i++) { object element = this.DeserializeExpression (manager, null, arrayCreateExpr.Initializers[i]); errorOccurred = (element == _errorMarker); if (!errorOccurred) { if (arrayType.IsInstanceOfType (element)) { initializers.Add (element); } else { ReportError (manager, "Array initializer element type incompatible with array type.", "Array Type: " + arrayType.Name + System.Environment.NewLine + "Array Element Type: " + elementType + System.Environment.NewLine + "Initializer Type: " + (element == null ? "null" : element.GetType ().Name)); errorOccurred = true; } } } if (!errorOccurred) initializers.CopyTo ((Array)deserialized, 0); } } // CodeMethodInvokeExpression // CodeMethodInvokeExpression methodExpr = expression as CodeMethodInvokeExpression; if (deserialized == null && methodExpr != null) { object target = this.DeserializeExpression (manager, null, methodExpr.Method.TargetObject); object[] parameters = null; if (target == _errorMarker || target == null) { errorOccurred = true; } else { parameters = new object[methodExpr.Parameters.Count]; for (int i=0; i < methodExpr.Parameters.Count; i++) { parameters[i] = this.DeserializeExpression (manager, null, methodExpr.Parameters[i]); if (parameters[i] == _errorMarker) { errorOccurred = true; break; } } } if (!errorOccurred) { MethodInfo method = null; if (target is Type) { method = GetExactMethod ((Type)target, methodExpr.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, parameters); } else { method = GetExactMethod (target.GetType(), methodExpr.Method.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, parameters); } if (method != null) { deserialized = method.Invoke (target, parameters); } else { string info = "Method Name: " + methodExpr.Method.MethodName + System.Environment.NewLine + "Method is: " + (target is Type ? "static" : "instance") + System.Environment.NewLine + "Method Holder Type: " + (target is Type ? ((Type)target).Name : target.GetType ().Name) + System.Environment.NewLine + "Parameters Count: " + methodExpr.Parameters.Count + System.Environment.NewLine + System.Environment.NewLine; for (int i = 0; i < parameters.Length; i++) { info += "Parameter Number: " + i.ToString () + System.Environment.NewLine + "Parameter Type: " + (parameters[i] == null ? "null" : parameters[i].GetType ().Name) + System.Environment.NewLine + "Parameter " + i.ToString () + " Value: " + parameters[i].ToString () + System.Environment.NewLine; } ReportError (manager, "Method '" + methodExpr.Method.MethodName + "' missing in type '" + (target is Type ? ((Type)target).Name : target.GetType ().Name + "'"), info); errorOccurred = true; } } } // CodeTypeReferenceExpression // CodeTypeReferenceExpression typeRef = expression as CodeTypeReferenceExpression; if (deserialized == null && typeRef != null) { deserialized = manager.GetType (typeRef.Type.BaseType); if (deserialized == null) { ReportError (manager, "Type '" + typeRef.Type.BaseType + "' not found." + "Are you missing a reference?"); errorOccurred = true; } } // CodeCastExpression // CodeCastExpression castExpr = expression as CodeCastExpression; if (deserialized == null && castExpr != null) { Type targetType = manager.GetType (castExpr.TargetType.BaseType); object instance = DeserializeExpression (manager, null, castExpr.Expression); if (instance != null && instance != _errorMarker && targetType != null) { IConvertible convertible = instance as IConvertible; if (convertible != null) { try { instance = convertible.ToType (targetType, null); } catch { errorOccurred = true; } } else { errorOccurred = true; } if (errorOccurred) { ReportError (manager, "Unable to convert type '" + instance.GetType ().Name + "' to type '" + castExpr.TargetType.BaseType + "'", "Target Type: " + castExpr.TargetType.BaseType + System.Environment.NewLine + "Instance Type: " + (instance == null ? "null" : instance.GetType ().Name) + System.Environment.NewLine + "Instance Value: " + (instance == null ? "null" : instance.ToString()) + System.Environment.NewLine + "Instance is IConvertible: " + (instance is IConvertible).ToString()); } deserialized = instance; } } // CodeBinaryOperatorExpression // CodeBinaryOperatorExpression binOperator = expression as CodeBinaryOperatorExpression; if (deserialized == null && binOperator != null) { string errorText = null; IConvertible left = null; IConvertible right = null; switch (binOperator.Operator) { case CodeBinaryOperatorType.BitwiseOr: left = DeserializeExpression (manager, null, binOperator.Left) as IConvertible; right = DeserializeExpression (manager, null, binOperator.Right) as IConvertible; if (left is Enum && right is Enum) { deserialized = Enum.ToObject (left.GetType (), Convert.ToInt64 (left) | Convert.ToInt64 (right)); } else { errorText = "CodeBinaryOperatorType.BitwiseOr allowed only on Enum types"; errorOccurred = true; } break; default: errorText = "Unsupported CodeBinaryOperatorType: " + binOperator.Operator.ToString (); errorOccurred = true; break; } if (errorOccurred) { string info = "BinaryOperator Type: " + binOperator.Operator.ToString() + System.Environment.NewLine + "Left Type: " + (left == null ? "null" : left.GetType().Name) + System.Environment.NewLine + "Left Value: " + (left == null ? "null" : left.ToString ()) + System.Environment.NewLine + "Left Expression Type: " + binOperator.Left.GetType ().Name + System.Environment.NewLine + "Right Type: " + (right == null ? "null" : right.GetType().Name) + System.Environment.NewLine + "Right Value: " + (right == null ? "null" : right.ToString ()) + System.Environment.NewLine + "Right Expression Type: " + binOperator.Right.GetType ().Name; ReportError (manager, errorText, info); } } if (!errorOccurred) { if (deserialized == null && !(expression is CodePrimitiveExpression) && !(expression is CodeMethodInvokeExpression)) { ReportError (manager, "Unsupported Expression Type: " + expression.GetType ().Name); errorOccurred = true; } } if (errorOccurred) deserialized = _errorMarker; return deserialized; }
protected string GetUniqueName (IDesignerSerializationManager manager, object instance) { if (instance == null) throw new ArgumentNullException ("instance"); if (manager == null) throw new ArgumentNullException ("manager"); string name = manager.GetName (instance); if (name == null) { INameCreationService service = manager.GetService (typeof (INameCreationService)) as INameCreationService; name = service.CreateName (null, instance.GetType ()); if (name == null) name = instance.GetType ().Name.ToLower (); manager.SetName (instance, name); } return name; }
protected CodeExpression GetExpression (IDesignerSerializationManager manager, object instance) { if (manager == null) throw new ArgumentNullException ("manager"); if (instance == null) throw new ArgumentNullException ("instance"); CodeExpression expression = null; ExpressionTable expressions = manager.Context[typeof (ExpressionTable)] as ExpressionTable; if (expressions != null) // 1st try: ExpressionTable expression = expressions [instance] as CodeExpression; if (expression == null) { // 2nd try: RootContext RootContext context = manager.Context[typeof (RootContext)] as RootContext; if (context != null && context.Value == instance) expression = context.Expression; } if (expression == null) { // 3rd try: IReferenceService (instance.property.property.property string name = manager.GetName (instance); if (name == null || name.IndexOf (".") == -1) { IReferenceService service = manager.GetService (typeof (IReferenceService)) as IReferenceService; if (service != null) { name = service.GetName (instance); if (name != null && name.IndexOf (".") != -1) { string[] parts = name.Split (new char[] { ',' }); instance = manager.GetInstance (parts[0]); if (instance != null) { expression = SerializeToExpression (manager, instance); if (expression != null) { for (int i=1; i < parts.Length; i++) expression = new CodePropertyReferenceExpression (expression, parts[i]); } } } } } } return expression; }
protected void DeserializeStatement (IDesignerSerializationManager manager, CodeStatement statement) { if (statement == null) throw new ArgumentNullException ("statement"); if (manager == null) throw new ArgumentNullException ("manager"); bool deserialized = false; // CodeAssignStatement // CodeAssignStatement assignment = statement as CodeAssignStatement; if (assignment != null) { DeserializeAssignmentStatement (manager, assignment); deserialized = true; } // CodeExpressionStatement // CodeExpressionStatement expression = statement as CodeExpressionStatement; if (expression != null) { this.DeserializeExpression (manager, null, expression.Expression); deserialized = true; } // CodeAttachEventStatement // CodeAttachEventStatement attachStatement = statement as CodeAttachEventStatement; if (attachStatement != null) { string methodName = null; CodeObjectCreateExpression createExpr = attachStatement.Listener as CodeObjectCreateExpression; if (createExpr != null && createExpr.Parameters.Count == 1 ) { // += new EventType (method) CodeMethodReferenceExpression handlerRef = createExpr.Parameters[0] as CodeMethodReferenceExpression; if (handlerRef != null) methodName = handlerRef.MethodName; } CodeDelegateCreateExpression delegateCreateExpr = attachStatement.Listener as CodeDelegateCreateExpression; if (delegateCreateExpr != null)// += new EventType (method) methodName = delegateCreateExpr.MethodName; CodeMethodReferenceExpression methodRef = attachStatement.Listener as CodeMethodReferenceExpression; if (methodRef != null) // += method methodName = methodRef.MethodName; object component = DeserializeExpression (manager, null, attachStatement.Event.TargetObject); if (component != null) { EventDescriptor eventDescriptor = TypeDescriptor.GetEvents (component)[attachStatement.Event.EventName]; if (eventDescriptor != null) { IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService; if (service != null) { service.GetEventProperty (eventDescriptor).SetValue (component, methodName); deserialized = true; } } } } if (!deserialized) Console.WriteLine ("DeserializeStatement not supported for: " + statement); }
bool SerializeProjectResource(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { var propDesc = descriptor as PropertyDescriptor; if (propDesc == null) return false; var component = value as IComponent; if (component == null || component.Site == null) return false; if (!propDesc.ShouldSerializeValue(component)) { return false; } var dictService = component.Site.GetService(typeof(IDictionaryService)) as IDictionaryService; if (dictService == null) return false; var resourceInfo = dictService.GetValue(ProjectResourceService.ProjectResourceKey + propDesc.Name) as ProjectResourceInfo; if (resourceInfo == null) return false; if (!Object.ReferenceEquals(resourceInfo.OriginalValue, propDesc.GetValue(value))) { LoggingService.Info("Value of property '" + propDesc.Name + "' on component '" + value.ToString() + "' is not equal to stored project resource value. Ignoring this resource."); return false; } // Find the generated file with the resource accessing class. var prs = manager.GetService(typeof(ProjectResourceService)) as ProjectResourceService; if (prs == null) { LoggingService.Warn("ProjectResourceService not found"); return false; } IProject project = prs.ProjectContent.Project as IProject; if (project == null) { LoggingService.Warn("Serializer cannot proceed because project is not an IProject"); return false; } string resourceFileDirectory = Path.GetDirectoryName(resourceInfo.ResourceFile); string resourceFileName = Path.GetFileName(resourceInfo.ResourceFile); var items = project.Items .OfType<FileProjectItem>() .Where( fpi => FileUtility.IsEqualFileName(Path.GetDirectoryName(fpi.FileName), resourceFileDirectory) && FileUtility.IsEqualFileName(fpi.DependentUpon, resourceFileName) && fpi.ItemType == ItemType.Compile && fpi.VirtualName.ToUpperInvariant().Contains("DESIGNER") ); if (items.Count() != 1) { LoggingService.Info("Did not find exactly one possible file that contains the generated class for the resource file '" + resourceInfo.ResourceFile + "'. Ignoring this resource."); return false; } string resourceCodeFile = items.Single().FileName; // We expect a single class to be in this file. IClass resourceClass = ParserService.GetParseInformation(resourceCodeFile).CompilationUnit.Classes.Single(); // Here we assume that VerifyResourceName is the same name transform that // was used when generating the resource code file. // This should be true as long as the code is generated using the // custom tool in SharpDevelop or Visual Studio. string resourcePropertyName = StronglyTypedResourceBuilder.VerifyResourceName(resourceInfo.ResourceKey, prs.ProjectContent.Language.CodeDomProvider ?? LanguageProperties.CSharp.CodeDomProvider); if (resourcePropertyName == null) { throw new InvalidOperationException("The resource name '" + resourceInfo.ResourceKey + "' could not be transformed to a name that is valid in the current programming language."); } // Now do the actual serialization. LoggingService.Debug("Serializing project resource: Component '" + component.ToString() + "', Property: '" + propDesc.Name + "', Resource class: '" + resourceClass.FullyQualifiedName + "', Resource property: '" + resourcePropertyName + "'"); var targetObjectExpr = base.SerializeToExpression(manager, value); if (targetObjectExpr == null) { LoggingService.Info("Target object could not be serialized: " + value.ToString()); return false; } if (propDesc.SerializationVisibility == DesignerSerializationVisibility.Content) { LoggingService.Debug("-> is a content property, ignoring this."); return false; } var propRefSource = Easy.Type( new CodeTypeReference(resourceClass.FullyQualifiedName, CodeTypeReferenceOptions.GlobalReference) ).Property(resourcePropertyName); var extAttr = propDesc.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; if (extAttr != null && extAttr.Provider != null) { // This is an extender property. var extProvider = base.SerializeToExpression(manager, extAttr.Provider); if (extProvider == null) { throw new InvalidOperationException("Could not serialize the extender provider '" + extAttr.Provider.ToString() + "'."); } statements.Add( extProvider.InvokeMethod( "Set" + propDesc.Name, targetObjectExpr, propRefSource ) ); } else { // This is a standard property. statements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(targetObjectExpr, propDesc.Name), propRefSource) ); } return true; }
static ProjectResourceInfo GetProjectResourceFromPropertyReference(IDesignerSerializationManager manager, CodePropertyReferenceExpression propRefSource) { ProjectResourceService prs = manager.GetService(typeof(ProjectResourceService)) as ProjectResourceService; if (prs == null) { throw new InvalidOperationException("The required ProjectResourceService is not available."); } return prs.GetProjectResource(propRefSource); }
private object DeserializeName(IDesignerSerializationManager manager, string name, CodeStatementCollection statements) { object obj2 = null; using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName")) { obj2 = this._nameTable[name]; CodeObject obj3 = obj2 as CodeObject; string typeName = null; CodeMemberField field = null; if (obj3 != null) { obj2 = null; this._nameTable[name] = null; CodeVariableDeclarationStatement statement = obj3 as CodeVariableDeclarationStatement; if (statement != null) { typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type); } else { field = obj3 as CodeMemberField; if (field != null) { typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type); } else { CodeExpression expression = obj3 as CodeExpression; RootContext context = manager.Context[typeof(RootContext)] as RootContext; if (((context != null) && (expression != null)) && (context.Expression == expression)) { obj2 = context.Value; typeName = TypeDescriptor.GetClassName(obj2); } } } } else if (obj2 == null) { IContainer service = (IContainer) manager.GetService(typeof(IContainer)); if (service != null) { IComponent component = service.Components[name]; if (component != null) { typeName = component.GetType().FullName; this._nameTable[name] = component; } } } if (typeName == null) { return obj2; } Type valueType = manager.GetType(typeName); if (valueType == null) { manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName }), manager)); return obj2; } if ((statements == null) && this._statementTable.ContainsKey(name)) { statements = this._statementTable[name]; } if ((statements == null) || (statements.Count <= 0)) { return obj2; } CodeDomSerializer serializer = base.GetSerializer(manager, valueType); if (serializer == null) { manager.ReportError(new CodeDomSerializerException(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { valueType.FullName }), manager)); return obj2; } try { obj2 = serializer.Deserialize(manager, statements); if ((obj2 != null) && (field != null)) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"]; if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes))) { MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask; descriptor.SetValue(obj2, attributes); } } this._nameTable[name] = obj2; } catch (Exception exception) { manager.ReportError(exception); } } return obj2; }
public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { PropertyDescriptor member = descriptor as PropertyDescriptor; if (manager == null) { throw new ArgumentNullException("manager"); } if (value == null) { throw new ArgumentNullException("value"); } if (member == null) { throw new ArgumentNullException("descriptor"); } bool flag = member.ShouldSerializeValue(value); if (!flag) { SerializeAbsoluteContext context = (SerializeAbsoluteContext) manager.Context[typeof(SerializeAbsoluteContext)]; if ((context != null) && context.ShouldSerialize(member)) { if (!member.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)) { flag = false; } else { flag = true; } } } if (flag && !member.Attributes.Contains(DesignOnlyAttribute.Yes)) { return true; } MemberRelationshipService service = manager.GetService(typeof(MemberRelationshipService)) as MemberRelationshipService; if (service != null) { MemberRelationship relationship = service[value, descriptor]; if (relationship != MemberRelationship.Empty) { return true; } } return false; }
public virtual object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration) { if (manager == null) { throw new ArgumentNullException("manager"); } if (declaration == null) { throw new ArgumentNullException("declaration"); } object obj2 = null; using (CodeDomSerializerBase.TraceScope("TypeCodeDomSerializer::Deserialize")) { bool caseInsensitive = false; CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider; if (service != null) { caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None; } Type type = null; string name = declaration.Name; foreach (CodeTypeReference reference in declaration.BaseTypes) { Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference)); name = reference.BaseType; if ((type2 != null) && !type2.IsInterface) { type = type2; break; } } if (type == null) { CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeNotFound", new object[] { name }), "SerializerTypeNotFound"); } if (CodeDomSerializerBase.GetReflectionTypeFromTypeHelper(manager, type).IsAbstract) { CodeDomSerializerBase.Error(manager, System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName }), "SerializerTypeAbstract"); } ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName); manager.ResolveName += handler; obj2 = manager.CreateInstance(type, null, declaration.Name, true); int count = declaration.Members.Count; this._nameTable = new HybridDictionary(count, caseInsensitive); this._statementTable = new Dictionary<string, CodeDomSerializerBase.OrderedCodeStatementCollection>(count); Dictionary<string, string> names = new Dictionary<string, string>(count); RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2); manager.Context.Push(context); try { StringComparison comparisonType = caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; foreach (CodeTypeMember member in declaration.Members) { CodeMemberField field = member as CodeMemberField; if ((field != null) && !string.Equals(field.Name, declaration.Name, comparisonType)) { this._nameTable[field.Name] = field; if ((field.Type != null) && !string.IsNullOrEmpty(field.Type.BaseType)) { names[field.Name] = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type); } } } CodeMemberMethod[] initializeMethods = this.GetInitializeMethods(manager, declaration); if (initializeMethods == null) { throw new InvalidOperationException(); } foreach (CodeMemberMethod method in initializeMethods) { foreach (CodeStatement statement in method.Statements) { CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement; if (statement2 != null) { this._nameTable[statement2.Name] = statement; } } } this._nameTable[declaration.Name] = context.Expression; foreach (CodeMemberMethod method2 in initializeMethods) { CodeDomSerializerBase.FillStatementTable(manager, this._statementTable, names, method2.Statements, declaration.Name); } PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"]; if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager))) { foreach (string str2 in this._nameTable.Keys) { if (str2.Equals(declaration.Name) || !this._statementTable.ContainsKey(str2)) { continue; } CodeStatementCollection statements = this._statementTable[str2]; bool flag2 = false; foreach (CodeStatement statement3 in statements) { object obj3 = statement3.UserData["GeneratedStatement"]; if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3)) { flag2 = true; break; } } if (!flag2) { this._statementTable.Remove(str2); } } } base.DeserializePropertiesFromResources(manager, obj2, _designTimeFilter); CodeDomSerializerBase.OrderedCodeStatementCollection[] array = new CodeDomSerializerBase.OrderedCodeStatementCollection[this._statementTable.Count]; this._statementTable.Values.CopyTo(array, 0); Array.Sort(array, StatementOrderComparer.Default); CodeDomSerializerBase.OrderedCodeStatementCollection statements2 = null; foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements3 in array) { if (statements3.Name.Equals(declaration.Name)) { statements2 = statements3; } else { this.DeserializeName(manager, statements3.Name, statements3); } } if (statements2 != null) { this.DeserializeName(manager, statements2.Name, statements2); } } finally { this._nameTable = null; this._statementTable = null; manager.ResolveName -= handler; manager.Context.Pop(); } } return obj2; }
private object DeserializeName(IDesignerSerializationManager manager, string name) { string typeName = null; Type objectType = null; object obj2 = this.nameTable[name]; using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::DeserializeName")) { CodeMemberField field = null; CodeObject obj3 = obj2 as CodeObject; if (obj3 != null) { obj2 = null; this.nameTable[name] = null; if (obj3 is CodeVariableDeclarationStatement) { CodeVariableDeclarationStatement statement = (CodeVariableDeclarationStatement) obj3; typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, statement.Type); } else if (obj3 is CodeMemberField) { field = (CodeMemberField) obj3; typeName = CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, field.Type); } } else { if (obj2 != null) { return obj2; } IContainer service = (IContainer) manager.GetService(typeof(IContainer)); if (service != null) { IComponent component = service.Components[name]; if (component != null) { typeName = component.GetType().FullName; this.nameTable[name] = component; } } } if (name.Equals(this.ContainerName)) { IContainer container2 = (IContainer) manager.GetService(typeof(IContainer)); if (container2 != null) { obj2 = container2; } } else if (typeName != null) { objectType = manager.GetType(typeName); if (objectType == null) { manager.ReportError(new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { typeName }))); } else { CodeStatementCollection codeObject = (CodeStatementCollection) this.statementTable[name]; if ((codeObject != null) && (codeObject.Count > 0)) { CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer(objectType, typeof(CodeDomSerializer)); if (serializer == null) { manager.ReportError(System.Design.SR.GetString("SerializerNoSerializerForComponent", new object[] { objectType.FullName })); } else { try { obj2 = serializer.Deserialize(manager, codeObject); if ((obj2 != null) && (field != null)) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj2)["Modifiers"]; if ((descriptor != null) && (descriptor.PropertyType == typeof(MemberAttributes))) { MemberAttributes attributes = field.Attributes & MemberAttributes.AccessMask; descriptor.SetValue(obj2, attributes); } } } catch (Exception exception) { manager.ReportError(exception); } } } } } this.nameTable[name] = obj2; } return obj2; }
protected CodeExpression SerializeToReferenceExpression(IDesignerSerializationManager manager, object value) { CodeExpression expression = null; using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::SerializeToReferenceExpression")) { expression = base.GetExpression(manager, value); if ((expression != null) || !(value is IComponent)) { return expression; } string name = manager.GetName(value); bool flag = false; if (name == null) { IReferenceService service = (IReferenceService) manager.GetService(typeof(IReferenceService)); if (service != null) { name = service.GetName(value); flag = name != null; } } if (name == null) { return expression; } RootContext context = (RootContext) manager.Context[typeof(RootContext)]; if ((context != null) && (context.Value == value)) { return context.Expression; } if (flag && (name.IndexOf('.') != -1)) { int index = name.IndexOf('.'); return new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(_thisRef, name.Substring(0, index)), name.Substring(index + 1)); } return new CodeFieldReferenceExpression(_thisRef, name); } }
public override object Serialize(IDesignerSerializationManager manager, object value) { if ((manager == null) || (value == null)) { throw new ArgumentNullException((manager == null) ? "manager" : "value"); } CodeDomSerializer serializer = (CodeDomSerializer) manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)); if (serializer == null) { return null; } object obj2 = serializer.Serialize(manager, value); InheritanceAttribute attribute = (InheritanceAttribute) TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; InheritanceLevel notInherited = InheritanceLevel.NotInherited; if (attribute != null) { notInherited = attribute.InheritanceLevel; } if (notInherited != InheritanceLevel.InheritedReadOnly) { IDesignerHost service = (IDesignerHost) manager.GetService(typeof(IDesignerHost)); if (service != null) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(service.RootComponent)["Localizable"]; if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(service.RootComponent))) { this.SerializeControlHierarchy(manager, service, value); } } CodeStatementCollection statements = obj2 as CodeStatementCollection; if (statements == null) { return obj2; } Control parent = (Control) value; if (((service != null) && (parent == service.RootComponent)) || this.HasSitedNonReadonlyChildren(parent)) { this.SerializeSuspendLayout(manager, statements, value); this.SerializeResumeLayout(manager, statements, value); ControlDesigner designer = service.GetDesigner(parent) as ControlDesigner; if (this.HasAutoSizedChildren(parent) || ((designer != null) && designer.SerializePerformLayout)) { this.SerializePerformLayout(manager, statements, value); } } if (this.HasMixedInheritedChildren(parent)) { this.SerializeZOrder(manager, statements, parent); } } return obj2; }
public override object Deserialize(IDesignerSerializationManager manager, object codeObject) { if ((manager == null) || (codeObject == null)) { throw new ArgumentNullException((manager == null) ? "manager" : "codeObject"); } object obj2 = null; using (CodeDomSerializerBase.TraceScope("RootCodeDomSerializer::Deserialize")) { if (!(codeObject is CodeTypeDeclaration)) { throw new ArgumentException(System.Design.SR.GetString("SerializerBadElementType", new object[] { typeof(CodeTypeDeclaration).FullName })); } bool caseInsensitive = false; CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider; if (service != null) { caseInsensitive = (service.LanguageOptions & LanguageOptions.CaseInsensitive) != LanguageOptions.None; } CodeTypeDeclaration declaration = (CodeTypeDeclaration) codeObject; CodeTypeReference reference = null; Type type = null; foreach (CodeTypeReference reference2 in declaration.BaseTypes) { Type type2 = manager.GetType(CodeDomSerializerBase.GetTypeNameFromCodeTypeReference(manager, reference2)); if ((type2 != null) && !type2.IsInterface) { reference = reference2; type = type2; break; } } if (type == null) { Exception exception = new SerializationException(System.Design.SR.GetString("SerializerTypeNotFound", new object[] { reference.BaseType })) { HelpLink = "SerializerTypeNotFound" }; throw exception; } if (type.IsAbstract) { Exception exception2 = new SerializationException(System.Design.SR.GetString("SerializerTypeAbstract", new object[] { type.FullName })) { HelpLink = "SerializerTypeAbstract" }; throw exception2; } ResolveNameEventHandler handler = new ResolveNameEventHandler(this.OnResolveName); manager.ResolveName += handler; if (!(manager is DesignerSerializationManager)) { manager.AddSerializationProvider(new CodeDomSerializationProvider()); } obj2 = manager.CreateInstance(type, null, declaration.Name, true); this.nameTable = new HybridDictionary(declaration.Members.Count, caseInsensitive); this.statementTable = new HybridDictionary(declaration.Members.Count, caseInsensitive); this.initMethod = null; RootContext context = new RootContext(new CodeThisReferenceExpression(), obj2); manager.Context.Push(context); try { foreach (CodeTypeMember member in declaration.Members) { if (member is CodeMemberField) { if (string.Compare(member.Name, declaration.Name, caseInsensitive, CultureInfo.InvariantCulture) != 0) { this.nameTable[member.Name] = member; } } else if ((this.initMethod == null) && (member is CodeMemberMethod)) { CodeMemberMethod method = (CodeMemberMethod) member; if ((string.Compare(method.Name, this.InitMethodName, caseInsensitive, CultureInfo.InvariantCulture) == 0) && (method.Parameters.Count == 0)) { this.initMethod = method; } } } if (this.initMethod != null) { foreach (CodeStatement statement in this.initMethod.Statements) { CodeVariableDeclarationStatement statement2 = statement as CodeVariableDeclarationStatement; if (statement2 != null) { this.nameTable[statement2.Name] = statement; } } } if (this.nameTable[declaration.Name] != null) { this.nameTable[declaration.Name] = obj2; } if (this.initMethod != null) { this.FillStatementTable(this.initMethod, declaration.Name); } PropertyDescriptor descriptor = manager.Properties["SupportsStatementGeneration"]; if (((descriptor != null) && (descriptor.PropertyType == typeof(bool))) && ((bool) descriptor.GetValue(manager))) { foreach (string str in this.nameTable.Keys) { CodeDomSerializerBase.OrderedCodeStatementCollection statements = (CodeDomSerializerBase.OrderedCodeStatementCollection) this.statementTable[str]; if (statements != null) { bool flag2 = false; foreach (CodeStatement statement3 in statements) { object obj3 = statement3.UserData["GeneratedStatement"]; if (((obj3 == null) || !(obj3 is bool)) || !((bool) obj3)) { flag2 = true; break; } } if (!flag2) { this.statementTable.Remove(str); } } } } IContainer container = (IContainer) manager.GetService(typeof(IContainer)); if (container != null) { foreach (object obj4 in container.Components) { base.DeserializePropertiesFromResources(manager, obj4, designTimeProperties); } } object[] array = new object[this.statementTable.Values.Count]; this.statementTable.Values.CopyTo(array, 0); Array.Sort(array, StatementOrderComparer.Default); foreach (CodeDomSerializerBase.OrderedCodeStatementCollection statements2 in array) { string name = statements2.Name; if ((name != null) && !name.Equals(declaration.Name)) { this.DeserializeName(manager, name); } } CodeStatementCollection statements3 = (CodeStatementCollection) this.statementTable[declaration.Name]; if ((statements3 != null) && (statements3.Count > 0)) { foreach (CodeStatement statement4 in statements3) { base.DeserializeStatement(manager, statement4); } } return obj2; } finally { manager.ResolveName -= handler; this.initMethod = null; this.nameTable = null; this.statementTable = null; manager.Context.Pop(); } } return obj2; }