// Constructor. public ComponentChangedEventArgs(Object component, MemberDescriptor member, Object oldValue, Object newValue) { this.component = component; this.member = member; this.oldValue = oldValue; this.newValue = newValue; }
public MemberRelationship this[object sourceOwner, MemberDescriptor sourceMember] { get { if (sourceOwner == null) throw new ArgumentNullException("sourceOwner"); if (sourceMember == null) throw new ArgumentNullException("sourceMember"); return GetRelationship(new MemberRelationship(sourceOwner, sourceMember)); } set { if (sourceOwner == null) throw new ArgumentNullException("sourceOwner"); if (sourceMember == null) throw new ArgumentNullException("sourceMember"); SetRelationship(new MemberRelationship(sourceOwner, sourceMember), value); } }
/// <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) { bool shouldSerialize = _serializer.ShouldSerialize(manager, value, descriptor); if (!shouldSerialize && !descriptor.Attributes.Contains(DesignOnlyAttribute.Yes)) { switch (_model) { case CodeDomLocalizationModel.PropertyReflection: if (!shouldSerialize) { // hook up the event the first time to clear out our cache at the end of the serialization if (localizationLanguage is null) { manager.SerializationComplete += new EventHandler(OnSerializationComplete); } if (GetLocalizationLanguage(manager) != CultureInfo.InvariantCulture) { shouldSerialize = true; } } break; case CodeDomLocalizationModel.PropertyAssignment: // If this property contains its default value, we still want to serialize it if we are in // localization mode if we are writing to the default culture, but only if the object // is not inherited. InheritanceAttribute inheritance = (InheritanceAttribute)manager.Context[typeof(InheritanceAttribute)]; if (inheritance is null) { inheritance = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)]; if (inheritance is null) { inheritance = InheritanceAttribute.NotInherited; } } if (inheritance.InheritanceLevel != InheritanceLevel.InheritedReadOnly) { shouldSerialize = true; } break; default: break; } } return(shouldSerialize); }
/// <summary> /// This serializes the given member on the given object. /// </summary> public virtual CodeStatementCollection SerializeMemberAbsolute(IDesignerSerializationManager manager, object owningObject, MemberDescriptor member) { throw new NotImplementedException(SR.NotImplementedByDesign); }
/// <summary> /// Returns true if the given member should be serialized in this context. /// </summary> public bool ShouldSerialize(MemberDescriptor member) { return(Member == null || Member == member); }
public bool ShouldSerialize(MemberDescriptor member) { return(member == _member); }
protected void RaiseComponentChanging (MemberDescriptor member) { throw new NotImplementedException(); }
public override void SerializeMemberAbsolute(SerializationStore store, object owningObject, MemberDescriptor member) => throw new NotImplementedException();
/// <summary> /// Creates a new member relationship. /// </summary> public MemberRelationship(object owner, MemberDescriptor member) { Owner = owner ?? throw new ArgumentNullException(nameof(owner)); Member = member ?? throw new ArgumentNullException(nameof(member)); }
/// <summary> /// Creates a new member relationship. /// </summary> public MemberRelationship(object owner, MemberDescriptor member) { if (owner == null) throw new ArgumentNullException(nameof(owner)); if (member == null) throw new ArgumentNullException(nameof(member)); Owner = owner; Member = member; }
/// <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) { if (manager is null) { throw new ArgumentNullException(nameof(manager)); } if (value is null) { throw new ArgumentNullException(nameof(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 != 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 MemberDescriptorXamlMember(MemberDescriptor member, XamlType declaringType) : base(member.CheckNotNull("member").Name, declaringType, false) { Descriptor = member; }
/// <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 PropertyDescriptor propertyToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } if (statements is null) { throw new ArgumentNullException(nameof(statements)); } try { ExtenderProvidedPropertyAttribute exAttr = (ExtenderProvidedPropertyAttribute)propertyToSerialize.Attributes[typeof(ExtenderProvidedPropertyAttribute)]; bool isExtender = (exAttr != null && exAttr.Provider != null); bool serializeContents = propertyToSerialize.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); CodeDomSerializer.Trace("Serializing property {0}", propertyToSerialize.Name); if (serializeContents) { SerializeContentProperty(manager, value, propertyToSerialize, isExtender, statements); } else if (isExtender) { SerializeExtenderProperty(manager, value, propertyToSerialize, statements); } else { SerializeNormalProperty(manager, value, propertyToSerialize, statements); } } 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, propertyToSerialize.Name, e.Message), manager)); } }
/// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.EventDescriptor'/> class with /// the name in the specified <see cref='System.ComponentModel.MemberDescriptor'/> and the /// attributes in both the <see cref='System.ComponentModel.MemberDescriptor'/> and the <see cref='System.Attribute'/> array. /// </para> /// </summary> protected EventDescriptor(MemberDescriptor descr, Attribute[] attrs) : base(descr, attrs) { }
/// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.EventDescriptor'/> class with the name and attributes in /// the specified <see cref='System.ComponentModel.MemberDescriptor'/>. /// </para> /// </summary> protected EventDescriptor(MemberDescriptor descr) : base(descr) { }
internal RelationshipEntry(MemberRelationship rel) { _owner = new WeakReference(rel.Owner); _member = rel.Member; _hashCode = rel.Owner == null ? 0 : rel.Owner.GetHashCode(); }
public override bool ShouldSerialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor) { return(this.baseSerializer.ShouldSerialize(manager, value, descriptor)); }
public MockPropertyDescriptor(MemberDescriptor reference) : base(reference) { }
public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { if (!this.SerializeProjectResource(manager, value, descriptor, statements)) { this.baseSerializer.Serialize(manager, value, descriptor, statements); } }
public MockMemberDescriptor(MemberDescriptor other, Attribute[] attributes) : base(other, attributes) { }
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).MostRecentCompilationUnit.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); }
/// <summary> /// Returns an object to describe this member reference. /// </summary> /// <returns>An object to describe this member reference.</returns> protected virtual MemberDescriptor GetDescriptor() { return this._descriptor ?? ( this._descriptor = this.Name.Contains(" ") ? MemberDescriptor.Parser(this.Signature.AsStream()) .TryGetValue(out this._descriptor) .Let(_ => this._descriptor) : new MemberDescriptor(this.Name) ); }
//error CS0534: 'System.Workflow.ComponentModel.Design.XomlComponentSerializationService' does not implement inherited abstract member 'System.ComponentModel.Design.Serialization.ComponentSerializationService.SerializeMemberAbsolute(System.ComponentModel.Design.Serialization.SerializationStore, object, System.ComponentModel.MemberDescriptor)' public override void SerializeMemberAbsolute(SerializationStore store, object owningObject, MemberDescriptor member) { this.SerializeMember(store, owningObject, member); }
protected override bool ShouldReportOnMethodCall(InvocationExpressionSyntax invocation, SemanticModel semanticModel, MemberDescriptor memberDescriptor) { var methodDeclaration = invocation.FirstAncestorOrSelf <MethodDeclarationSyntax>(); if (methodDeclaration == null) { // We want to report on all calls not made from a method return(true); } var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration); if (!methodSymbol.IsIDisposableDispose()) { return(true); } return(false); }
public override void SerializeMember(SerializationStore store, object owningObject, MemberDescriptor member) { if (store == null) { throw new ArgumentNullException("store"); } if (owningObject == null) { throw new ArgumentNullException("owningObject"); } if (member == null) { throw new ArgumentNullException("member"); } WorkflowMarkupSerializationStore xomlStore = store as WorkflowMarkupSerializationStore; if (xomlStore == null) { throw new InvalidOperationException(SR.GetString(SR.Error_UnknownSerializationStore)); } xomlStore.AddMember(owningObject, member); }
public SerializeAbsoluteContext(MemberDescriptor member) { _member = member; }
/// <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) { ArgumentNullException.ThrowIfNull(manager); ArgumentNullException.ThrowIfNull(value); if (!(descriptor is EventDescriptor eventToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } ArgumentNullException.ThrowIfNull(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 is not null) { Trace("Event {0} bound to {1}", eventToSerialize.Name, methodName); CodeExpression eventTarget = SerializeToExpression(manager, value); TraceWarningIf(eventTarget is null, "Object has no name and no property ref in context so we cannot serialize events: {0}", value); if (eventTarget is not 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)); } }
/// <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) { // We push the localization model to indicate that our serializer is in control. Our // serialization provider looks for this and decides what type of resource serializer // to give us. manager.Context.Push(_model); try { _serializer.Serialize(manager, value, descriptor, statements); } finally { manager.Context.Pop(); } }
/// <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) => true;
/// <summary> /// This method serializes the given member on the given object, /// but also serializes the member if it contains the default value. /// Note that for some members, containing the default value and setting /// the same value back to the member are different concepts. For example, /// if a property inherits its value from a parent object if no local value /// is set, setting the value back to the property can may not be what is desired. /// SerializeMemberAbsolute takes this into account and would clear the state of /// the property in this case. /// </summary> public abstract void SerializeMemberAbsolute(SerializationStore store, object owningObject, MemberDescriptor member);
public void SerializeAbsoluteContext_Ctor_MemberDescriptor(MemberDescriptor member) { var context = new SerializeAbsoluteContext(member); Assert.Same(member, context.Member); }
protected virtual bool ShouldReportOnMethodCall(TInvocationExpressionSyntax invocation, SemanticModel semanticModel, MemberDescriptor memberDescriptor) => true;
public void SerializeAbsoluteContext_ShouldSerialize_Invoke_ReturnsExpected(SerializeAbsoluteContext context, MemberDescriptor member, bool expected) { Assert.Equal(expected, context.ShouldSerialize(member)); }
/// <summary> /// Generate a thread-safe accessor for a regular field-like event. /// /// DelegateType tmp0 = _event; //backing field /// DelegateType tmp1; /// DelegateType tmp2; /// do { /// tmp1 = tmp0; /// tmp2 = (DelegateType)Delegate.Combine(tmp1, value); //Remove for -= /// tmp0 = Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1); /// } while ((object)tmp0 != (object)tmp1); /// /// Note, if System.Threading.Interlocked.CompareExchange<T> is not available, /// we emit the following code and mark the method Synchronized (unless it is a struct). /// /// _event = (DelegateType)Delegate.Combine(_event, value); //Remove for -= /// /// </summary> internal static BoundBlock ConstructFieldLikeEventAccessorBody_Regular(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, DiagnosticBag diagnostics) { CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode; TypeSymbol delegateType = eventSymbol.Type; MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; ParameterSymbol thisParameter = accessor.ThisParameter; TypeSymbol boolType = compilation.GetSpecialType(SpecialType.System_Boolean); SpecialMember updateMethodId = isAddMethod ? SpecialMember.System_Delegate__Combine : SpecialMember.System_Delegate__Remove; MethodSymbol updateMethod = (MethodSymbol)compilation.GetSpecialTypeMember(updateMethodId); BoundStatement @return = new BoundReturnStatement(syntax, refKind: RefKind.None, expressionOpt: null) { WasCompilerGenerated = true }; if (updateMethod == null) { MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(updateMethodId); diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), syntax.Location)); return BoundBlock.SynthesizedNoLocals(syntax, @return); } Binder.ReportUseSiteDiagnostics(updateMethod, diagnostics, syntax); BoundThisReference fieldReceiver = eventSymbol.IsStatic ? null : new BoundThisReference(syntax, thisParameter.Type) { WasCompilerGenerated = true }; BoundFieldAccess boundBackingField = new BoundFieldAccess(syntax, receiver: fieldReceiver, fieldSymbol: eventSymbol.AssociatedField, constantValueOpt: null) { WasCompilerGenerated = true }; BoundParameter boundParameter = new BoundParameter(syntax, parameterSymbol: accessor.Parameters[0]) { WasCompilerGenerated = true }; BoundExpression delegateUpdate; MethodSymbol compareExchangeMethod = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T); if ((object)compareExchangeMethod == null) { // (DelegateType)Delegate.Combine(_event, value) delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax, operand: BoundCall.Synthesized(syntax, receiverOpt: null, method: updateMethod, arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundParameter)), conversion: Conversion.ExplicitReference, type: delegateType); // _event = (DelegateType)Delegate.Combine(_event, value); BoundStatement eventUpdate = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundBackingField, right: delegateUpdate, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; return BoundBlock.SynthesizedNoLocals(syntax, statements: ImmutableArray.Create<BoundStatement>( eventUpdate, @return)); } compareExchangeMethod = compareExchangeMethod.Construct(ImmutableArray.Create<TypeSymbol>(delegateType)); Binder.ReportUseSiteDiagnostics(compareExchangeMethod, diagnostics, syntax); GeneratedLabelSymbol loopLabel = new GeneratedLabelSymbol("loop"); const int numTemps = 3; LocalSymbol[] tmps = new LocalSymbol[numTemps]; BoundLocal[] boundTmps = new BoundLocal[numTemps]; for (int i = 0; i < numTemps; i++) { tmps[i] = new SynthesizedLocal(accessor, TypeWithAnnotations.Create(delegateType), SynthesizedLocalKind.LoweringTemp); boundTmps[i] = new BoundLocal(syntax, tmps[i], null, delegateType) { WasCompilerGenerated = true }; } // tmp0 = _event; BoundStatement tmp0Init = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[0], right: boundBackingField, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // LOOP: BoundStatement loopStart = new BoundLabelStatement(syntax, label: loopLabel) { WasCompilerGenerated = true }; // tmp1 = tmp0; BoundStatement tmp1Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[1], right: boundTmps[0], type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // (DelegateType)Delegate.Combine(tmp1, value) delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax, operand: BoundCall.Synthesized(syntax, receiverOpt: null, method: updateMethod, arguments: ImmutableArray.Create<BoundExpression>(boundTmps[1], boundParameter)), conversion: Conversion.ExplicitReference, type: delegateType); // tmp2 = (DelegateType)Delegate.Combine(tmp1, value); BoundStatement tmp2Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[2], right: delegateUpdate, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1) BoundExpression compareExchange = BoundCall.Synthesized(syntax, receiverOpt: null, method: compareExchangeMethod, arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundTmps[2], boundTmps[1])); // tmp0 = Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1); BoundStatement tmp0Update = new BoundExpressionStatement(syntax, expression: new BoundAssignmentOperator(syntax, left: boundTmps[0], right: compareExchange, type: delegateType) { WasCompilerGenerated = true }) { WasCompilerGenerated = true }; // tmp0 == tmp1 // i.e. exit when they are equal, jump to start otherwise BoundExpression loopExitCondition = new BoundBinaryOperator(syntax, operatorKind: BinaryOperatorKind.ObjectEqual, left: boundTmps[0], right: boundTmps[1], constantValueOpt: null, methodOpt: null, resultKind: LookupResultKind.Viable, type: boolType) { WasCompilerGenerated = true }; // branchfalse (tmp0 == tmp1) LOOP BoundStatement loopEnd = new BoundConditionalGoto(syntax, condition: loopExitCondition, jumpIfTrue: false, label: loopLabel) { WasCompilerGenerated = true }; return new BoundBlock(syntax, locals: tmps.AsImmutable(), statements: ImmutableArray.Create<BoundStatement>( tmp0Init, loopStart, tmp1Update, tmp2Update, tmp0Update, loopEnd, @return)) { WasCompilerGenerated = true }; }
public ComponentChangingEventArgs (object component, MemberDescriptor member) { this.component = component; this.member = member; }
public MockPropertyDescriptor(MemberDescriptor reference, Attribute [] attrs) : base(reference, attrs) { }
/// <devdoc> /// Creates a new member relationship. /// </devdoc> public MemberRelationship(object owner, MemberDescriptor member) { if (owner == null) throw new ArgumentNullException("owner"); if (member == null) throw new ArgumentNullException("member"); _owner = owner; _member = member; }
internal static Symbol GetRuntimeMember(NamedTypeSymbol declaringType, ref MemberDescriptor descriptor, SignatureComparer <MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol accessWithinOpt) { Symbol result = null; SymbolKind targetSymbolKind; MethodKind targetMethodKind = MethodKind.Ordinary; bool isStatic = (descriptor.Flags & MemberFlags.Static) != 0; switch (descriptor.Flags & MemberFlags.KindMask) { case MemberFlags.Constructor: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.Constructor; // static constructors are never called explicitly Debug.Assert(!isStatic); break; case MemberFlags.Method: targetSymbolKind = SymbolKind.Method; break; case MemberFlags.PropertyGet: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.PropertyGet; break; case MemberFlags.Field: targetSymbolKind = SymbolKind.Field; break; case MemberFlags.Property: targetSymbolKind = SymbolKind.Property; break; default: throw ExceptionUtilities.UnexpectedValue(descriptor.Flags); } foreach (var member in declaringType.GetMembers(descriptor.Name)) { Debug.Assert(member.Name.Equals(descriptor.Name)); if (member.Kind != targetSymbolKind || member.IsStatic != isStatic || !(member.DeclaredAccessibility == Accessibility.Public || ((object)accessWithinOpt != null && Symbol.IsSymbolAccessible(member, accessWithinOpt)))) { continue; } switch (targetSymbolKind) { case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; MethodKind methodKind = method.MethodKind; // Treat user-defined conversions and operators as ordinary methods for the purpose // of matching them here. if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator) { methodKind = MethodKind.Ordinary; } if (method.Arity != descriptor.Arity || methodKind != targetMethodKind || ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract)) { continue; } if (!comparer.MatchMethodSignature(method, descriptor.Signature)) { continue; } } break; case SymbolKind.Property: { PropertySymbol property = (PropertySymbol)member; if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract)) { continue; } if (!comparer.MatchPropertySignature(property, descriptor.Signature)) { continue; } } break; case SymbolKind.Field: if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature)) { continue; } break; default: throw ExceptionUtilities.UnexpectedValue(targetSymbolKind); } // ambiguity if ((object)result != null) { result = null; break; } result = member; } return(result); }
public MockMemberDescriptor(MemberDescriptor other) : base(other) { }
internal RelationshipEntry(MemberRelationship rel) { Owner = new WeakReference(rel.Owner); Member = rel.Member; hashCode = rel.Owner == null ? 0 : rel.Owner.GetHashCode(); }
/// <summary> /// Here is where all the fun stuff starts. We create the structure and apply the naming here. /// </summary> private void CreateStandardToolStrip(IDesignerHost host, ToolStrip tool) { // build the static menu items structure. // string[] menuItemNames = new string[] { SR.StandardMenuNew, SR.StandardMenuOpen, SR.StandardMenuSave, SR.StandardMenuPrint, "-", SR.StandardToolCut, SR.StandardMenuCopy, SR.StandardMenuPaste, "-", SR.StandardToolHelp }; // build a image list mapping one-one the above menuItems list... this is required so that the in LOCALIZED build we dont use the Localized item string. string[] menuItemImageNames = new string[] { "new", "open", "save", "print", "-", "cut", "copy", "paste", "-", "help" }; Debug.Assert(host != null, "can't create standard menu without designer _host."); if (host == null) { return; } tool.SuspendLayout(); ToolStripDesigner.s_autoAddNewItems = false; // create a transaction so this happens as an atomic unit. DesignerTransaction createMenu = _host.CreateTransaction(SR.StandardMenuCreateDesc); try { INameCreationService nameCreationService = (INameCreationService)_provider.GetService(typeof(INameCreationService)); string defaultName = "standardMainToolStrip"; string name = defaultName; int index = 1; if (host != null) { while (_host.Container.Components[name] != null) { name = defaultName + (index++).ToString(CultureInfo.InvariantCulture); } } //keep an index in the MenuItemImageNames .. so that mapping is maintained. int menuItemImageNamesCount = 0; // now build the menu items themselves. foreach (string itemText in menuItemNames) { name = null; // for separators, just use the default name. Otherwise, remove any non-characters and get the name from the text. defaultName = "ToolStripButton"; name = NameFromText(itemText, typeof(ToolStripButton), nameCreationService, true); ToolStripItem item = null; if (name.Contains("Separator")) { // create the componennt. item = (ToolStripSeparator)_host.CreateComponent(typeof(ToolStripSeparator), name); IDesigner designer = _host.GetDesigner(item); if (designer is ComponentDesigner) { ((ComponentDesigner)designer).InitializeNewComponent(null); } } else { // create the component. item = (ToolStripButton)_host.CreateComponent(typeof(ToolStripButton), name); IDesigner designer = _host.GetDesigner(item); if (designer is ComponentDesigner) { ((ComponentDesigner)designer).InitializeNewComponent(null); } PropertyDescriptor displayStyleProperty = TypeDescriptor.GetProperties(item)["DisplayStyle"]; Debug.Assert(displayStyleProperty != null, "Could not find 'Text' property in ToolStripItem."); if (displayStyleProperty != null) { displayStyleProperty.SetValue(item, ToolStripItemDisplayStyle.Image); } PropertyDescriptor textProperty = TypeDescriptor.GetProperties(item)["Text"]; Debug.Assert(textProperty != null, "Could not find 'Text' property in ToolStripItem."); if (textProperty != null) { textProperty.SetValue(item, itemText); } Bitmap image = null; try { image = GetImage(menuItemImageNames[menuItemImageNamesCount]); } catch { // eat the exception.. as you may not find image for all MenuItems. } if (image != null) { PropertyDescriptor imageProperty = TypeDescriptor.GetProperties(item)["Image"]; Debug.Assert(imageProperty != null, "Could not find 'Image' property in ToolStripItem."); if (imageProperty != null) { imageProperty.SetValue(item, image); } item.ImageTransparentColor = Color.Magenta; } } tool.Items.Add(item); //increment the counter... menuItemImageNamesCount++; } // finally, add it to the Main ToolStrip. MemberDescriptor topMember = TypeDescriptor.GetProperties(tool)["Items"]; _componentChangeSvc.OnComponentChanging(tool, topMember); _componentChangeSvc.OnComponentChanged(tool, topMember, null, null); } catch (Exception e) { if (e is InvalidOperationException) { IUIService uiService = (IUIService)_provider.GetService(typeof(IUIService)); uiService.ShowError(e.Message); } if (createMenu != null) { createMenu.Cancel(); createMenu = null; } } finally { //Reset the AutoAdd state ToolStripDesigner.s_autoAddNewItems = true; if (createMenu != null) { createMenu.Commit(); createMenu = null; } tool.ResumeLayout(); // Select the Main Menu... ISelectionService selSvc = (ISelectionService)_provider.GetService(typeof(ISelectionService)); if (selSvc != null) { selSvc.SetSelectedComponents(new object[] { _designer.Component }); } //Refresh the Glyph DesignerActionUIService actionUIService = (DesignerActionUIService)_provider.GetService(typeof(DesignerActionUIService)); if (actionUIService != null) { actionUIService.Refresh(_designer.Component); } // this will invalidate the Selection Glyphs. SelectionManager selMgr = (SelectionManager)_provider.GetService(typeof(SelectionManager)); selMgr.Refresh(); } }
/// <summary> /// Here is where all the fun stuff starts. We create the structure and apply the naming here. /// </summary> private void CreateStandardMenuStrip(System.ComponentModel.Design.IDesignerHost host, MenuStrip tool) { // build the static menu items structure. string[][] menuItemNames = new string[][] { new string[] { SR.StandardMenuFile, SR.StandardMenuNew, SR.StandardMenuOpen, "-", SR.StandardMenuSave, SR.StandardMenuSaveAs, "-", SR.StandardMenuPrint, SR.StandardMenuPrintPreview, "-", SR.StandardMenuExit }, new string[] { SR.StandardMenuEdit, SR.StandardMenuUndo, SR.StandardMenuRedo, "-", SR.StandardMenuCut, SR.StandardMenuCopy, SR.StandardMenuPaste, "-", SR.StandardMenuSelectAll }, new string[] { SR.StandardMenuTools, SR.StandardMenuCustomize, SR.StandardMenuOptions }, new string[] { SR.StandardMenuHelp, SR.StandardMenuContents, SR.StandardMenuIndex, SR.StandardMenuSearch, "-", SR.StandardMenuAbout } }; // build the static menu items image list that maps one-one with above menuItems structure. this is required so that the in LOCALIZED build we dont use the Localized item string. string[][] menuItemImageNames = new string[][] { new string[] { "", "new", "open", "-", "save", "", "-", "print", "printPreview", "-", "" }, new string[] { "", "", "", "-", "cut", "copy", "paste", "-", "" }, new string[] { "", "", "" }, new string[] { "", "", "", "", "-", "" } }; Keys[][] menuItemShortcuts = new Keys[][] { new Keys[] { /*File*/ Keys.None, /*New*/ Keys.Control | Keys.N, /*Open*/ Keys.Control | Keys.O, /*Separator*/ Keys.None, /*Save*/ Keys.Control | Keys.S, /*SaveAs*/ Keys.None, Keys.None, /*Print*/ Keys.Control | Keys.P, /*PrintPreview*/ Keys.None, /*Separator*/ Keys.None, /*Exit*/ Keys.None }, new Keys[] { /*Edit*/ Keys.None, /*Undo*/ Keys.Control | Keys.Z, /*Redo*/ Keys.Control | Keys.Y, /*Separator*/ Keys.None, /*Cut*/ Keys.Control | Keys.X, /*Copy*/ Keys.Control | Keys.C, /*Paste*/ Keys.Control | Keys.V, /*Separator*/ Keys.None, /*SelectAll*/ Keys.None }, new Keys[] { /*Tools*/ Keys.None, /*Customize*/ Keys.None, /*Options*/ Keys.None }, new Keys[] { /*Help*/ Keys.None, /*Contents*/ Keys.None, /*Index*/ Keys.None, /*Search*/ Keys.None, /*Separator*/ Keys.None, /*About*/ Keys.None } }; Debug.Assert(host != null, "can't create standard menu without designer _host."); if (host == null) { return; } tool.SuspendLayout(); ToolStripDesigner.s_autoAddNewItems = false; // create a transaction so this happens as an atomic unit. DesignerTransaction createMenu = _host.CreateTransaction(SR.StandardMenuCreateDesc); try { INameCreationService nameCreationService = (INameCreationService)_provider.GetService(typeof(INameCreationService)); string defaultName = "standardMainMenuStrip"; string name = defaultName; int index = 1; if (host != null) { while (_host.Container.Components[name] != null) { name = defaultName + (index++).ToString(CultureInfo.InvariantCulture); } } // now build the menu items themselves. for (int j = 0; j < menuItemNames.Length; j++) { string[] menuArray = menuItemNames[j]; ToolStripMenuItem rootItem = null; for (int i = 0; i < menuArray.Length; i++) { name = null; // for separators, just use the default name. Otherwise, remove any non-characters and get the name from the text. string itemText = menuArray[i]; name = NameFromText(itemText, typeof(ToolStripMenuItem), nameCreationService, true); ToolStripItem item = null; if (name.Contains("Separator")) { // create the componennt. item = (ToolStripSeparator)_host.CreateComponent(typeof(ToolStripSeparator), name); IDesigner designer = _host.GetDesigner(item); if (designer is ComponentDesigner) { ((ComponentDesigner)designer).InitializeNewComponent(null); } item.Text = itemText; } else { // create the componennt. item = (ToolStripMenuItem)_host.CreateComponent(typeof(ToolStripMenuItem), name); IDesigner designer = _host.GetDesigner(item); if (designer is ComponentDesigner) { ((ComponentDesigner)designer).InitializeNewComponent(null); } item.Text = itemText; Keys shortcut = menuItemShortcuts[j][i]; if ((item is ToolStripMenuItem) && shortcut != Keys.None) { if (!ToolStripManager.IsShortcutDefined(shortcut) && ToolStripManager.IsValidShortcut(shortcut)) { ((ToolStripMenuItem)item).ShortcutKeys = shortcut; } } Bitmap image = null; try { image = GetImage(menuItemImageNames[j][i]); } catch { // eat the exception.. as you may not find image for all MenuItems. } if (image != null) { PropertyDescriptor imageProperty = TypeDescriptor.GetProperties(item)["Image"]; Debug.Assert(imageProperty != null, "Could not find 'Image' property in ToolStripItem."); if (imageProperty != null) { imageProperty.SetValue(item, image); } item.ImageTransparentColor = Color.Magenta; } } // the first item in each array is the root item. if (i == 0) { rootItem = (ToolStripMenuItem)item; rootItem.DropDown.SuspendLayout(); } else { rootItem.DropDownItems.Add(item); } //If Last SubItem Added the Raise the Events if (i == menuArray.Length - 1) { // member is OK to be null... MemberDescriptor member = TypeDescriptor.GetProperties(rootItem)["DropDownItems"]; _componentChangeSvc.OnComponentChanging(rootItem, member); _componentChangeSvc.OnComponentChanged(rootItem, member, null, null); } } // finally, add it to the MainMenu. rootItem.DropDown.ResumeLayout(false); tool.Items.Add(rootItem); //If Last SubItem Added the Raise the Events if (j == menuItemNames.Length - 1) { // member is OK to be null... MemberDescriptor topMember = TypeDescriptor.GetProperties(tool)["Items"]; _componentChangeSvc.OnComponentChanging(tool, topMember); _componentChangeSvc.OnComponentChanged(tool, topMember, null, null); } } } catch (Exception e) { if (e is InvalidOperationException) { IUIService uiService = (IUIService)_provider.GetService(typeof(IUIService)); uiService.ShowError(e.Message); } if (createMenu != null) { createMenu.Cancel(); createMenu = null; } } finally { ToolStripDesigner.s_autoAddNewItems = true; if (createMenu != null) { createMenu.Commit(); createMenu = null; } tool.ResumeLayout(); // Select the Main Menu... ISelectionService selSvc = (ISelectionService)_provider.GetService(typeof(ISelectionService)); if (selSvc != null) { selSvc.SetSelectedComponents(new object[] { _designer.Component }); } //Refresh the Glyph DesignerActionUIService actionUIService = (DesignerActionUIService)_provider.GetService(typeof(DesignerActionUIService)); if (actionUIService != null) { actionUIService.Refresh(_designer.Component); } // this will invalidate the Selection Glyphs. SelectionManager selMgr = (SelectionManager)_provider.GetService(typeof(SelectionManager)); selMgr.Refresh(); } }
protected void RaiseComponentChanged (MemberDescriptor member, object oldValue, object newValue) { throw new NotImplementedException(); }